text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
showdialog() not working in fragment
I have a datepicker dialog and listview. And I wanted the dialog to show up when onclick but the method in onClick for showdialog() got deprecated. I got no idea where my error is.
Any idea how to solve it?
fragment.class
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class RankingFragment extends Fragment implements View.OnClickListener {
private ImageView iv;
private Calendar cal;
private int day;
private int month;
private int year;
private EditText et;
String[] member_names;
TypedArray profile_pics;
String[] statues;
static final String TAG_IMAGES = "images";
List<RankingRowItem> rankingRowItems;
ListView mylistview;
View rootView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_ranking, container, false);
iv = (ImageView) rootView.findViewById(R.id.imageView1);
cal = Calendar.getInstance();
day = cal.get(Calendar.DAY_OF_MONTH);
month = cal.get(Calendar.MONTH);
year = cal.get(Calendar.YEAR);
et = (EditText) rootView.findViewById(R.id.editText);
iv.setOnClickListener(this);
rankingRowItems = new ArrayList<RankingRowItem>();
member_names = getResources().getStringArray(R.array.Member_names);
profile_pics = getResources().obtainTypedArray(R.array.profile_pics);
statues = getResources().getStringArray(R.array.statues);
for (int i = 0; i < member_names.length; i++) {
RankingRowItem item = new RankingRowItem(member_names[i],
profile_pics.getResourceId(i, -1), statues[i]);
rankingRowItems.add(item);
}
mylistview = (ListView) rootView.findViewById(R.id.list);
RankingCustomAdapter adapter = new RankingCustomAdapter(getActivity(), rankingRowItems);
mylistview.setAdapter(adapter);
profile_pics.recycle();
return rootView;
}
@Override
public void onClick(View v)
{
getActivity().showDialog(0);
}
@Deprecated
protected Dialog onCreateDialog(int id) {
return new DatePickerDialog(getActivity(), datePickerListener, year, month, day);
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
et.setText(selectedDay + " / " + (selectedMonth + 1) + " / "
+ selectedYear);
}
};
}
A:
I think you need to impelement
protected Dialog onCreateDialog(int id) {
return new DatePickerDialog(getActivity(), datePickerListener, year, month, day);
}
inside the Activity you are calling showDialog() on.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use method in a view that i put controls on it from subclass of one of that controls
I subclass a NSTextField and in subclass use an event method (keyUp),i want to call a method in main view (view that i put NSTextFiled on it) when user push Enter key.i use below code but don't how to call specific method in main view
- (void)keyUp:(NSEvent *)theEvent
{
NSString *theArrow = [theEvent charactersIgnoringModifiers];
unichar keyChar = 0;
keyChar = [theArrow characterAtIndex:0];
if ( keyChar == NSEnterCharacter )
{
//call method that exist in main view
}
}
A:
1.in main view set : textField.delegate=self;
2.add <NSTextFieldDelegate> to mainview.h and subclass.h
3.use this code Instead of comment
if ( self.delegate && [self.delegate respondsToSelector:@selector(textFieldDidPressEnter:)] )
[self.delegate performSelector:@selector(textFieldDidPressEnter:) withObject:self];
4.implement this method in mainview.m
-(void)textFieldDidPressEnter:(NSTextField *)txt
{
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Python: remove a value from dictionary and raise exception
The order doesn't matter, how do you remove a value until all the values are empty?
It also raise exception with no value existed
For example:
d = {'a':1,'b':2,'c':1,'d':3}
remove a : {'b':2,'c':1,'d':3}
remove b : {'b':1,'c':1,'d':3}
remove b : {'c':1,'d':3}
remove c : {'d':3}
remove d : {'d':2}
remove d : {'d':1}
remove d : {}
ValueError: d.remove(a): not in d
A:
d = {'a':1,'b':2,'c':1,'d':3}
while True:
try:
k = next(iter(d))
d[k] -= 1
if d[k] <= 0: del d[k]
print d
except StopIteration:
raise ValueError, "d.remove(a): not in d"
{'c': 1, 'b': 2, 'd': 3}
{'b': 2, 'd': 3}
{'b': 1, 'd': 3}
{'d': 3}
{'d': 2}
{'d': 1}
{}
Traceback (most recent call last):
File "/home/jamylak/weaedwas.py", line 10, in <module>
raise ValueError, "d.remove(a): not in d"
ValueError: d.remove(a): not in d
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to manually verify a user against the ASP.NET memberhip database?
I would like to know how I can verify a user's credential against an existing asp.net membership database. The short story is that we want provide single sign on access.
So what I've done is to connect directly to the membership database and tried to run a sql query against the aspnet_Membership table:
private bool CanLogin(string userName, string password)
{
// Check DB to see if the credential is correct
try
{
string passwordHash = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "SHA1");
string sql = string.Format("select 1 from aspnet_Users a inner join aspnet_Membership b on a.UserId = b.UserId and a.applicationid = b.applicationid where a.username = '{0}' and b.password='{1}'", userName.ToLowerInvariant(), passwordHash);
using (SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString))
using (SqlCommand sqlCmd = new SqlCommand(sql, sqlConn))
{
sqlConn.Open();
int count = sqlCmd.ExecuteNonQuery();
return count == 1;
}
}
catch (Exception ex)
{
return false;
}
}
The problem is the password value, does anyone know how the password it is hashed?
A:
if you have two asp.net apps on the same IIS server, you can do SSO like this. I asked this question and answered it myself.
here
Once you have both apps pointing at your asp_membership database by placing the following in the system.web section of your web config
<authentication mode="Forms" />
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="membership"
applicationName="/"
/>
</providers>
</membership>
<roleManager enabled="true" />
make sure both have the same applicationname property set.
I was using IIS 6 so I configured it to autogenerate a machine key for both applications. Because both of these applications live on the same machine the key would be identical, this is the critical part to making the SSO work. After setting up IIS the following was added to my web.config
<machineKey decryptionKey="AutoGenerate" validation="SHA1" validationKey="AutoGenerate" />
That was all there was to it. Once that was done I could log into app1 and then browse to app2 and keep my security credentials.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Angular Input Restriction Directive - Negating Regular Expressions
EDIT: Please feel free to add additional validations that would be useful for others, using this simple directive.
--
I'm trying to create an Angular Directive that limits the characters input into a text box. I've been successful with a couple common use cases (alphbetical, alphanumeric and numeric) but using popular methods for validating email addresses, dates and currency I can't get the directive to work since I need it negate the regex. At least that's what I think it needs to do.
Any assistance for currency (optional thousand separator and cents), date (mm/dd/yyyy) and email is greatly appreciated. I'm not strong with regular expressions at all.
Here's what I have currently:
http://jsfiddle.net/corydorning/bs05ys69/
HTML
<div ng-app="example">
<h1>Validate Directive</h1>
<p>The Validate directive allow us to restrict the characters an input can accept.</p>
<h3><code>alphabetical</code> <span style="color: green">(works)</span></h3>
<p>Restricts input to alphabetical (A-Z, a-z) characters only.</p>
<label><input type="text" validate="alphabetical" ng-model="validate.alphabetical"/></label>
<h3><code>alphanumeric</code> <span style="color: green">(works)</span></h3>
<p>Restricts input to alphanumeric (A-Z, a-z, 0-9) characters only.</p>
<label><input type="text" validate="alphanumeric" ng-model="validate.alphanumeric" /></label>
<h3><code>currency</code> <span style="color: red">(doesn't work)</span></h3>
<p>Restricts input to US currency characters with comma for thousand separator (optional) and cents (optional).</p>
<label><input type="text" validate="currency.us" ng-model="validate.currency" /></label>
<h3><code>date</code> <span style="color: red">(doesn't work)</span></h3>
<p>Restricts input to the mm/dd/yyyy date format only.</p>
<label><input type="text" validate="date" ng-model="validate.date" /></label>
<h3><code>email</code> <span style="color: red">(doesn't work)</span></h3>
<p>Restricts input to email format only.</p>
<label><input type="text" validate="email" ng-model="validate.email" /></label>
<h3><code>numeric</code> <span style="color: green">(works)</span></h3>
<p>Restricts input to numeric (0-9) characters only.</p>
<label><input type="text" validate="numeric" ng-model="validate.numeric" /></label>
JavaScript
angular.module('example', [])
.directive('validate', function () {
var validations = {
// works
alphabetical: /[^a-zA-Z]*$/,
// works
alphanumeric: /[^a-zA-Z0-9]*$/,
// doesn't work - need to negate?
// taken from: http://stackoverflow.com/questions/354044/what-is-the-best-u-s-currency-regex
currency: /^[+-]?[0-9]{1,3}(?:,?[0-9]{3})*(?:\.[0-9]{2})?$/,
// doesn't work - need to negate?
// taken from here: http://stackoverflow.com/questions/15196451/regular-expression-to-validate-datetime-format-mm-dd-yyyy
date: /(?:0[1-9]|1[0-2])\/(?:0[1-9]|[12][0-9]|3[01])\/(?:19|20)[0-9]{2}/,
// doesn't work - need to negate?
// taken from: http://stackoverflow.com/questions/46155/validate-email-address-in-javascript
email: /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i,
// works
numeric: /[^0-9]*$/
};
return {
require: 'ngModel',
scope: {
validate: '@'
},
link: function (scope, element, attrs, modelCtrl) {
var pattern = validations[scope.validate] || scope.validate
;
modelCtrl.$parsers.push(function (inputValue) {
var transformedInput = inputValue.replace(pattern, '')
;
if (transformedInput != inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
A:
I am pretty sure, there is better way, probably regex is also not best tool for that, but here is mine proposition.
This way you can only restrict which characters are allowed for input and to force user to use proper format, but you will need to also validate final input after user will finish typing, but this is another story.
The alphabetic, numeric and alphanumeric are quite simple, for input and validating input, as it is clear what you can type, and what is a proper final input. But with dates, mails, currency, you cannot validate input with regex for full valid input, as user need to type it in first, and in a meanwhile the input need to by invalid in terms of final valid input. So, this is one thing to for example restrict user to type just digits and / for a date format, like: 12/12/1988, but in the end you need to check if he typed proper date or just 12/12/126 for example. This need to be checked when answer is submited by user, or when text field lost focus, etc.
To just validate typed character, you can try with this:
JSFiddle DEMO
First change:
var transformedInput = inputValue.replace(pattern, '')
to
var transformedInput = inputValue.replace(pattern, '$1')
then use regular expressions:
/^([a-zA-Z]*(?=[^a-zA-Z]))./ - alphabetic
/^([a-zA-Z0-9]*(?=[^a-zA-Z0-9]))./ - alphanumeric
/(\.((?=[^\d])|\d{2}(?![^,\d.]))|,((?=[^\d])|\d{3}(?=[^,.$])|(?=\d{1,2}[^\d]))|\$(?=.)|\d{4,}(?=,)).|[^\d,.$]|^\$/- currency (allow string like: 343243.34, 1,123,345.34, .05 with or without $)
^(((0[1-9]|1[012])|(\d{2}\/\d{2}))(?=[^\/])|((\d)|(\d{2}\/\d{2}\/\d{1,3})|(.+\/))(?=[^\d])|\d{2}\/\d{2}\/\d{4}(?=.)).|^(1[3-9]|[2-9]\d)|((?!^)(3[2-9]|[4-9]\d)\/)|[3-9]\d{3}|2[1-9]\d{2}|(?!^)\/\d\/|^\/|[^\d/] - date (00-12/00-31/0000-2099)
/^(\d*(?=[^\d]))./ - numeric
/^([\w.$-]+\@[\w.]+(?=[^\w.])|[\w.$-]+\@(?=[^\w.-])|[\w.@-]+(?=[^\w.$@-])).$|\.(?=[^\w-@]).|[^\w.$@-]|^[^\w]|\.(?=@).|@(?=\.)./i - email
Generally, it use this pattern:
([valid characters or structure] captured in group $1)(?= positive lookahead for not allowed characters) any character
in effect it will capture all valid character in group $1, and if user type in an invalid character, whole string is replaced with already captured valid characters from group $1. It is complemented by part which shall exclude some obvious invalid character(s), like @@ in a mail, or 34...2 in currency.
With understanding how these regular expression works, despite that it looks quite complex, I think it easy to extend it, by adding additional allowed/not allowed characters.
Regular expression for validating currency, dates and mails are easy to find, so I find it redundant to post them here.
OffTopic. Whats more the currency part in your demo is not working, it is bacause of: validate="currency.us" instead of validate="currency", or at least it works after this modification.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
OpenGL ES Perform Selector After Random Delay
I am working on an OpenGL ES application where I have a spaceship with 6 guns. Each gun uses keyframe animation to interpolate between 2 sets of vertices of a start and end position.
I have a method rotateGun: that I pass the gunNumber variable to that refers to which gun should fire. When rotateGun: fires, it creates a laser blast that I move away from the ship through a vector pointing down the gun barrel at it's location when the method is called. This all works fine but I want to add random time intervals for each gun to fire since right now they appear to fire at the same time.
I've tried to create a time delay and fire off my rotateGun: method using performSelector:afterDelay:, but this doesn't work. I then attempted to use the method mainGunFire: after a delay and then call rotateGun: on the main thread… this also didn't work. By "didn't work" I mean that the NSLog I inserted just before my drawing calls within the rotateGun: method does print, but the guns and blasts are never drawn.
If I simply do a performSelectorOnMainThread to call rotateGun:, then the guns and blasts are drawn as before and the blasts appear to fire at the same time. I'm clearly not understanding something. Can someone please help me understand how to slightly randomize my laser blasts so they don't all fire at the same time? Thanks!
// Randomly Fire Gun
- (void)mainGunFire:(NSNumber *)gunNumber {
// Perform the Gun animation and fire on main thread
[self performSelectorOnMainThread:@selector(rotateGun:) withObject:gunNumber waitUntilDone:YES];
}
// Draw and Rotate the Guns
- (void)drawRotateGuns {
// Only shoot if this is not a ship life
if ( self.isLife == NO ) {
// Gun 1
// Set the pass variable to 1 and call the method
// after a variable amount of time
int randomTime = 0;
//[self performSelector:@selector(mainGunFire:) withObject:[NSNumber numberWithInt:1] afterDelay:randomTime];
[self performSelectorOnMainThread:@selector(rotateGun:) withObject:[NSNumber numberWithInt:1] waitUntilDone:YES];
// Gun 2 ...
// Gun 3 ...
}
}
A:
The easiest solution is to use !(rand()%some_number) instead of 1. Experiment with some_number value (it must be different for each gun). But it should be not very big.
For example if you use 2, then probability of !(rand()%2) == 1 is about 0.5. So if you're rendering 60 frames per second you'll get about 30 fires per second. For the !(rand()%20) you should get about 3 fires per second. Hope you get it. Some pseudocode:
if( !(rand()%2) ) {
[gun1 fire];
}
if( !(rand()%3) ) {
[gun2 fire];
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Prove that, for $p > 3$, $(\frac 3p) = 1$ when $p \equiv 1,11 \pmod{12}$ and $(\frac 3p) = -1$ when $p \equiv 5,7 \pmod{12}$
$(\frac 3p)$ is the Legendre symbol here, not a fraction, if that wasn't clear.
This is what I have so far:
We know by Gauss's Lemma that $(\frac qp) = (-1)^v$ where
$$v = \#\left\{1 \le a \le \frac{p-1}{2} \mid aq \equiv k_a \pmod{12}),\space -p/2 < k_a < 0\right\}$$
And we also know that multiples of $(\dfrac{p-1}{2}) \times 3$ must be between $0$ and $p/2$, between $p/2$ and $p$, or between $p$ and $3p/2$.
Representing $p$ as $12k + r$ seems like the next step, but I'm not sure where to go from there.
A:
By Quadratic Reciprocity $$\left(\frac{3}{p}\right)=\left(\frac{p}{3}\right)(-1)^{(p-1)(3-1)/4}=\left(\frac{p}{3}\right)(-1)^{(p-1)/2}=\left(\frac{p}{3}\right)\left(\frac{-1}{p}\right).$$ We will use the fact that $-1$ is a quadratic residue modulo $p$ if $p\equiv 1\pmod{4}$ and is not if $p\equiv -1\pmod{4}$. Since $3\nmid p$, $p\equiv 1,2\pmod{3}$. Thus, $\left(\frac{p}{3}\right)=\left(\frac{1}{3}\right)=1$ or $\left(\frac{p}{3}\right)=\left(\frac{2}{3}\right)=-1$. Now, for $\left(\frac{3}{p}\right)=1$ either $\left(\frac{p}{3}\right)=1$ and $\left(\frac{-1}{p}\right)=1$, or they are both equal to $-1$. In the former case, $p\equiv 1\pmod{4}$ and $p\equiv 1\pmod{3}$, so by CRT, $p\equiv 1\pmod{12}$. In the latter case $p\equiv 3\pmod{4}$ and $p\equiv 2\pmod{3}$, so again by CRT $p\equiv 11\equiv -1\pmod{12}$. The result follows from here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Safari not displaying text
I have a fresh Mac OS X 10.10 (Yosemite) install, with every update available installed, on a iMac (2011). Safari (9.0) is acting up. Firefox is working just as it should.
I have tried the usual suspects, disk repair and deleting the cache to no avail. I have but a few apps installed, Logic X and a couple of other music apps, but the system is super fresh, it should not act up like this. Any ideas?
A:
I would recommend clearing your font cache using OnyX and rebooting to clear things up.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Tableview swipe in iOS
Hi I'm new to iOS Development. I want to design something similar to Groupon app for iPhone.
I need 4 or 5 table views (each table view is a category which lists the products in that category )which I can slide or swipe through like in the Groupon app.
I'm confused on whether I should have all the table views in one page view which can be swiped through or one page view per table view.
Any help is appreciated.
Thanks.
A:
UIPageViewController does exactly what you need:
A page view controller lets the user navigate between pages of
content, where each page is managed by its own view controller object.
Navigation can be controlled programmatically by your app or directly
by the user using gestures. When navigating from page to page, the
page view controller uses the transition that you specify to animate
the change.
Here is a very nice tutorial on how to implement it:
http://www.appcoda.com/uipageviewcontroller-tutorial-intro/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What would happen to my bitcoins?
I have a Bitcoin wallet for android and I would like to know what happens if I back up the wallet and restore it in other phone. Will I be able to use the bitcoins in both devices?
Thanks in advance
A:
Yes you will be able to access the same coins with both devices. You can think about it like if you make a copy of a key to your home, and give it to someone; both people will be able to open the same door.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Design pattern for passing implicit data to components (Implicit meaning not through parameters).
Specifically, I am looking for a pattern to provide components with information about the current run-time specific to the current thread.
Currently, to pass the user who is in charge of the given process to the thread, I set the thread name to the user's identification number. The components can then get the information about who owns the process through the thread name.
This seems to me like an abuse of thread names. Is there a better way to hold this information?
A:
The Java class ThreadLocal is the right way to go about this. It will keep information in the thread's context and you can use it to set the user information at one point, and then access it from the same thread a later point, e.g. from a different layer of your application. This will work as long as the components/services are running in the same thread.
Documentation: http://docs.oracle.com/javase/6/docs/api/java/lang/ThreadLocal.html
Tutorial: http://javaboutique.internet.com/tutorials/localdata/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is a set that consists of a single point connected?
If $S=\{a\}$ then surely for every two points from that set there is a path that joins them, choose $x_1=a$ and $x_2=a$ and define continuous function on $[0,1]$ such that $f(x)=a$. Or, one point cannot be represented as union of two or more disjoint nonempty open subsets.
What would happen if we would consider one-point set as neither connected nor disconnected (or both connected and disconnected)?
Is this situation similar to "should $1$ be considered prime or not"?
A:
Your first paragraph conflates "connectedness" and "path connectedness"; they're not the same.
For the second paragraph, this is like asking, "What if we said 2 was the same as $\pi$?" Your proposed "thing to say" might be amusing, but it contradicts both of the definitions of connectedness, for all possible topologies. So it's not very helpful.
I guess it's a little like the "is 1 prime" question, in the sense that there appears to be a widely accepted definition with which you have some qualms.
Let me add a little detail. We could say "a set $X$ is connected if (a) $X$ does not consist of a single point, and (b) for every pair of disjoint open sets $U$ and $V$ such that $U \cup V = X$, one of $U$ or $V$ is empty." And we could define "disconnected" similarly, and then observe that one-point sets are neither connected nor disconnected.
The result would be that virtually every proof about connectedness would have an extra paragraph to say something about 1-point sets, or exclude 1-point sets in some way. I don't believe that this would lead to greater insight.
A:
As you've correctly demonstrated, the definition of connectedness resp. path-connectednes applies perfectly fine to the one-point space. So there is really no need to make an exemption. I also would not draw the analogy to the Is $1$ prime?- Question because in this case there are just no arguments for the one-point-space not to be path-connected.
Moreover one likes to think about path-connectedness as a property not only of spaces but also of homotopy classes of spaces. (https://en.wikipedia.org/wiki/Homotopy#Homotopy_equivalence)
For example the one-point-set is homotopy equivalent to $\mathbb{R}^n$ (and by definition also to every other contractible space). So if you want to consider euclidean space as path-connected, then you should also consider the one-point-space as path-connected.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Sonar - Ignore Lombok code via custom annotation
I'm trying to ignore Lombok code (generated code) from Sonar analysis based on files which have a custom annotation, @ExcludeLombok.
I've tried this guide which did not work.
In fact, I've even tried excluding an entire directory from analysis and it still wouldn't work.
I've also tirelessly searched through StackOverflow looking for a solution, and I've seen this has been discussed a good bit on here, but I've seen that people have been suggesting to write a single test to get the coverage up, which is pointless since we should not test auto generated code.
The solution I'm looking for is to exclude files based on a custom annotation.
But so far, anything I attempt to exclude does not get excluded.
Any help would be greatly appreciated.
A:
There is currently no easy way to exclude issues raised by the SonarQube rules from the SonarQube Java Analyzer, except from using approaches described in the "Narrowing the focus" documentation you quote.
Now, we introduced recently the concept of issue filters in the SonarQube Java Analyzer. This mechanism is at the moment only used internally to exclude issues raised by rules at analysis time, based on specific criteria.
We plan to extends this mechanism in order to allow users to implements their own custom issue filters, the same way custom rules can be implemented. This approach would cover your case and allow you to filter any rules on code annotated with your custom annotation. This new feature will be handled in the following JIRA ticket: SONARJAVA-1761
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Custom data labels for charts with XlsxWriter
I'm trying to create a some of a complex chart using XlsxWriter, thus I need to add some data labels to my series. The problem is that the data labels I need are different from the series value.
Within Excel is something simple to do:
1) right click format data labels
2) label contains: values from cells
3) I then select the cells I want and it creates the data labels
If there is any way to do this, thanks in advance.
A:
This feature isn't supported since it wasn't part of the original Excel 2007 file format.
There is a feature request for this: XlsxWriter/feature_request/343.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Unable to render a Ext.form.TextField into the output of an XTemplate
I want to render some Ext components into the output of an XTemplate. We want to have the flexibility of using an XTemplate to render the HTML but retain the styling, behaviour, and handlers of using Ext components rather than plain old HTML elements.
I am currently successfully doing this with an Ext.Button. In the template I am writing a placeholder div like so:
<div id="paceholder-1"></div>
After I have called apply() on the template I then create a new Ext component and render it in like so:
this._replacePlaceholders.defer(1, this, [html, 'placeholder-1', collection]);
The _replacePlaceholders function looks like this:
_replacePlaceholders: function(html, id, collection) {
var emailField = new Ext.form.TextField({
emptyText: 'Email address',
hideLabel: true
});
var downloadButton = new Ext.Button({
text: 'Download as...',
icon: 'images/down.png',
scope: this,
menu: this._createDownloadOptionsMenu(collection) // Create Menu for this Button (works fine)
});
var form = new Ext.form.FormPanel({
items: [emailField, downloadButton]
});
downloadButton.render(html, id);
}
This works and renders the button into the html correctly. The button menu behaves as expected.
But if I change the last line of replacePlaceholders to emailField.render(html, id); or form.render(html, id); I get a javascript error.
TypeError: ct is null
ct.dom.insertBefore(this.el.dom, position);
ext-all-debug.js (line 10978)
I'm a bit confused because from what I can tell from the docs the render() method called is going to be the same one (from Ext.Component). But I've had a bit of a play around and can't seem to track down what is happening here.
So is there any good reason why these components behave differently from Ext.Button? and is it possible to render an Ext.form.TextField or an Ext.form.FormPanel or anything that will let me use an Ext text field in mt XTemplate html?
NB. I am using ExtJS 3.3.1 and don't have the opportunity to upgrade the version. I believe ExtJS 4 has functionality which would make doing what I doing much easier.
Thanks!
A:
Solution is quite simple - use form.render(id) instead of form.render(html, id).
See [api][1] if you have doubts.
The reason why button is rendering properly is that it has weird onRender implementation, different from Component.
onRender : function(ct, position){
[...]
if(position){
btn = this.template.insertBefore(position, targs, true);
}else{
btn = this.template.append(ct, targs, true);
}
[...]
}
As you can see in code above, if you provide position (which is basically second argument provided to render) it doen't use ct (which is first argument passed to render).
In normal component onRender method looks like this:
onRender : function(ct, position){
[...]
if(this.el){
this.el = Ext.get(this.el);
if(this.allowDomMove !== false){
ct.dom.insertBefore(this.el.dom, position);
if (div) {
Ext.removeNode(div);
div = null;
}
}
}
}
In code above, you can see, that ct is called always, despite the position is not null.
The bottom line is that rendering of button works by accident.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Best practice making an AjaxRequest from domain A to domain B in ExtJs4
So I'm currently implementing a mobile app (Sencha Touch 2.3.1 + PhoneGap 3) that uses JSONP proxies to connect to a Java Jersey REST application so far so good (or kinda...) with that I can load my stores...
But what if let's say I don't want to load anything into a store I just want to call to myBusinessMethodFoo(param1, param2) what are my options in that case?
If it were a web application one option would be to make an Ajax request to my own back-end and then consume a service in another domain and then send data back to my front-end, but since I'm talking about a mobile app that's not an option ...
So, what is the best practice in this case?
A:
JSONP technique http://es.wikipedia.org/wiki/JSONP
There is also a JSONP request in Ext (this worked)
Ext.data.JsonP.request({
url: "http://10.1.50.66:7001/Simulador/webresources/hello",
callbackKey: 'callback1',
params: {
},
success : function(response) {
console.log("Spiffing, everything worked");
// success property
console.log(response.success);
// result property
console.log(response.result);
console.log(response.msj);
},
failure: function(response) {
console.log(response);
Ext.Msg.alert('Error', 'Please try again.', Ext.emptyFn);
}
});
I'll have to compare thi approach to CORS.
best regards @code4jhon
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can I test method call order with AAA syntax in Rhino-Mocks 3.6?
Is it possible to test for the following example if the Method1 called 1st, then Method2 called after and then Method3 by using the AAA syntax, in Rhino-mocks 3.6 ?
// Assert
var mock = MockRepository.GenerateMock<ISomeService>();
// Act
myObject.Service = mock;
// How should I change this part to ensure that Rhino Mocks check the call order as well?
mock.AssertWasCalled(m=>m.Method1());
mock.AssertWasCalled(m=>m.Method2());
mock.AssertWasCalled(m=>m.Method3());
A:
Here's one way to do it...
mock.AssertWasCalled(m=>m.Method1(), options => options.WhenCalled(w => mockService.AssertWasNotCalled(x=>x.Method2())));
mock.AssertWasCalled(m=>m.Method2(), options => options.WhenCalled(w => mockService.AssertWasNotCalled(x=>x.Method3())));
mock.AssertWasCalled(m=>m.Method3());
A:
You can, but you really shouldn't. You should focus on testing the externall observable behaviors, rather than the implementation.
Method call order can change without affecting the contract with the client of the API. In that case, your test will fail, even when it shouldn't.
In short, testing implementation leads to brittle tests. Brittle tests lead to abandonment of the tests. You don't want to go there.
Hope this helps.
A:
Here is how to do it nicely.
var mocks = new MockRepository();
var fooMock = mocks.DynamicMock<IFoo>();
using (mocks.Ordered())
{
fooMock.Expect(x => x.Method1());
fooMock.Expect(x => x.Method2());
}
fooMock.Replay();
var bar = new Bar(fooMock);
bar.DoWork();
fooMock.VerifyAllExpectations();
Found the answer from this blog.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to load large Ntriple data into jena tdb
I'm using Dbpedia in my project and I wanted to create a local sparql end point as the online one is not reliable. I downloaded data dumps (large NT files) and decided to use Jena TDB. Using the NetBeans IDE am using an input stream to read in the source NT file and then using the following line of code to load the NT file into a datasetGraph:
TDBLoader.load(indexingDataset, inputs, true);
I let it run for about 5 hrs now and it still isnt done. Whilst doing this everything on my laptop seems to slow down probably because of it taking all my physical memory space. Is there a faster way to do this???
The documentation says to use tdbloader2 but its only available for linux while am using windows. Would be really helpful if anyone could tel me how to use this tool in windows using cygwin. Please take into consideration I have never really used Cygwin in windows.
A:
The latest release of TDB has two command line utilities for bulk loading: tdbloader and tdbloader2. The first is pure Java and it runs on Windows as well as on any machine with a JVM. The second is a mix of Java and UNIX shell script (in particular it uses UNIX sort). It runs on Linux, I am not sure it runs on Cygwin. I suggest you use tdbloader on a 64-bit machine with as much RAM as you can find. :-)
The latest release of TDB is available here:
http://www.apache.org/dist/incubator/jena/jena-tdb-0.9.0-incubating/jena-tdb-0.9.0-incubating-distribution.zip
The development version of TDB has an additional bulk loader command: tdbloader3. This is a pure Java version of tdbloader2. Instead of using UNIX sort (which works only on text files) we used a pure Java external sort with binary files. For more details on tdbloader3, search for the JENA-117 issue.
You can find a SNAPSHOT of TDB in the Apache snapshots repository, you are warned, that has not been released yet.
For the more adventurous there is also tdbloader4 which is not included in Apache Jena and it is to be considered an experimental prototype.
tdbloader4 builds TDB indexes (i.e. B+Tree indexes) using MapReduce (this is stretching a little bit the MapReduce model, but it works).
You can find tdbloader4 here: https://github.com/castagna/tdbloader4
To conclude, my advise to you, on Windows, is: download the latest official release of TDB and use tdbloader with a 64-bit machine with a lot of RAM. If you do not have one, use an m1.xlarge EC2 instance (i.e. 15 GB of RAM) (or equivalent).
For more help, I invite you to join the official [email protected] mailing list where, I am sure, you'll have better and faster support.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I programmatically select an object (and have that object show as selected) in the new NSCollectionView?
I have sucessfully implemented a 10.11 version of NSCollectionView in my Mac app. It displays the 10 items that I want, but I want the first item to be automatically selected when the app starts.
I have tried the following in the viewDidLoad and alternatively in the viewDidAppear functions;
let indexPath = NSIndexPath(forItem: 0, inSection: 0)
var set = Set<NSIndexPath>()
set.insert(indexPath)
collectionView.animator().selectItemsAtIndexPaths(set, scrollPosition: NSCollectionViewScrollPosition.Top)
I have tried line 4 above with and without the animator
I have also tried the following in place of line 4
collectionView.animator().selectionIndexPaths = set
with and without the animator()
While they both include the index path in the selected index paths, neither actually displays the item as selected.
Any clues where I am going wrong?
A:
I propose not to use the scroll position. In Swift 3 the following code in viewDidLoad is working for me
// select first item of collection view
collectionView(collectionView, didSelectItemsAt: [IndexPath(item: 0, section: 0)])
collectionView.selectionIndexPaths.insert(IndexPath(item: 0, section: 0))
The second code line is necessary, otherwise the item is never deselected.
The following is working, too
collectionView.selectItems(at: [IndexPath(item: 0, section: 0)], scrollPosition: NSCollectionViewScrollPosition.top)
For both code snippets it is essential to have a NSCollectionViewDelegate with the function
func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
// if you are using more than one selected item, code has to be changed
guard let indexPath = indexPaths.first
else { return }
guard let item = collectionView.item(at: indexPath) as? CollectionViewItem
else { return }
item.setHighlight(true)
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Regexp.match.length returns NULL if not found
I've a JS regexp.
var t1 = str.match(/\[h1\]/g).length;
If str contains the word [h1] it works fine else it shows error !
How to solve the problem ?
A:
var t1 = (str.match(/\[h1\]/g)||[]).length;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why do I get weird results when I subdivide this mesh?
What do I do?
I subdivide then bend it, then this happens.
A:
It could be one of a few things:
Make sure your mesh is thick enough and isn't intersecting with itself
Make sure your normals are calculated correctly (Ctrl+N)
Make sure you don't have any doubled up vertices (select the vertices, hit W, and select Remove Doubles)
Make sure you don't subdivide with triangular faces as they don't deform nicely
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Fix Tic-Tac-Toe Minimax ai
I have a board class which represents the game board in Tic-Tac-Toe, but my AI is not working. I would really appreciate any help. Thanks!
I am attempting to use a minimax type of algorithm to try and see what the best move that can be made on the board is, but I am getting strange results. Right now in order to test my code, I am just running the testAI() method.
public class Board
{
private int[] board = {0,0,0,0,0,0,0,0,0};
private final int HUMAN = -1;
private final int COMPUTER = 1;
private final int[][] winList = {
{0, 1, 2},
{3, 4, 5},
{6, 7, 8},
{0, 3, 6},
{1, 4, 7},
{2, 5, 8},
{0, 4, 8},
{2, 4, 6}
};
private int[] choice = new int[10000];
private int choiceCount = 0;
private int[] scoreArray = new int[10000];
public void reset() {
for (int i = 0; i < board.length; i++) {
board[i] = 0;
}
}
public void set(int index, int player) {
board[index] = player;
}
public int[] set(int[] board2, int index, int player) {
board2[index] = player;
return board2;
}
public boolean checkEmpty(int index) {
if (board[index] == 0) {
return true;
} else {
return false;
}
}
public boolean isGameOver() {
for (int i = 0; i < board.length; i++) {
if (board[i] == 0) {
return false;
}
}
return true;
}
public boolean isGameOver(int[] board2) {
for (int i = 0; i < board2.length; i++) {
if (board2[i] == 0) {
return false;
}
}
return true;
}
public int chooseRandomSpot() {
while (true) {
int r = (int)(9 * Math.random());
if (checkEmpty(r))
return r;
}
}
private String[] toStringArray() {
String[] y = new String[9];
for (int i = 0; i < board.length; i++) {
if (board[i] == 0) {
y[i] = " ";
} else if (board[i] == 1) {
y[i] = "x";
} else if (board[i] == -1) {
y[i] = "o";
}
}
return y;
}
public void printBoard() {
String[] y = toStringArray();
System.out.println(" a b c");
for (int i = 0; i < 3; i++) {
if (i == 0) {
System.out.println("a " + y[0] + " " + y[1] + " " + y[2]);
} else if (i == 1) {
System.out.println("b " + y[3] + " " + y[4] + " " + y[5]);
} else if (i == 2) {
System.out.println("c " + y[6] + " " + y[7] + " " + y[8]);
}
}
}
public boolean checkForWin(int player) {
for (int i = 0; i < 8; i++) {
int a = winList[i][0];
int b = winList[i][1];
int c = winList[i][2];
if (board[a] == player && board[b] == player && board[c] == player) {
return true;
}
}
return false;
}
public boolean checkForWin(int[] board2, int player) {
for (int i = 0; i < 8; i++) {
int a = winList[i][0];
int b = winList[i][1];
int c = winList[i][2];
if (board2[a] == player && board2[b] == player && board2[c] == player) {
return true;
}
}
return false;
}
public int getMaxChoice() {
int loc = 0;
int max = Integer.MIN_VALUE;
for (int i = 0; i < choice.length; i++) {
if (scoreArray[i] > max) {
max = scoreArray[i];
loc = choice[i];
}
}
return loc;
}
public void testAI() {
int[] x = {1,0,0,-1,1,0,-1,0,0};
board = x;
printBoard();
minimax(x,COMPUTER);
printBoard();
System.out.println(getMaxChoice();
int[] y = set(x,getMaxChoice(),COMPUTER);
board = y;
printBoard();
}
private int score(int[] board2) {
if (checkForWin(board2, COMPUTER)) {
return 10;
} else if (checkForWin(board2, HUMAN)) {
return -10;
} else {
return 0;
}
}
private int minimax(int[] board2, int player) {
//System.out.println("In here!!");
int oppPlayer = 0;
if (player == COMPUTER) {
oppPlayer = HUMAN;
} else {
oppPlayer = COMPUTER;
}
if (isGameOver(board2) || checkForWin(board2, COMPUTER) || checkForWin(board2, HUMAN)) {
return score(board2);
}
int amt = 0; // find the amount of possible moves
for (int i = 0; i < board2.length; i++) {
if (board2[i] == 0) {
amt++;
}
}
int[] scores = new int[amt];
int[] moves = new int[amt];
int count = 0; //the index of the moves array
for (int i = 0; i < amt; i++) {
if (board2[i] == 0) { //if the space is empty
moves[count] = i;// appends the index of the next empty space to the moves array
count++;
}
//int[] newBoard = set(board2, moves[count], player); //make a new board with each move
//scores[count] = minimax(newBoard, oppPlayer);
}
for (int i = 0; i < moves.length; i++) {
//int[] newBoard = set(board2, moves[i], player); //make a new board with each move
int[] newBoard = new int[board2.length];
for (int m = 0; m < board2.length; m++) {
newBoard[m] = board2[m];
}
newBoard = set(newBoard, moves[i], player);
scores[i] = minimax(newBoard, oppPlayer); //populate the scores array with the final score of each move
}
if (player == COMPUTER) {
int max = Integer.MIN_VALUE;
int indexOfMax = 0;
for (int i = 0; i < scores.length; i++) {
if (scores[i] > max) {
max = scores[i];
indexOfMax = i;
}
}
choice[choiceCount] = moves[indexOfMax];
scoreArray[choiceCount] = scores[indexOfMax];
choiceCount++;
System.out.println(choice);
return max;
} else {
int min = Integer.MAX_VALUE;
int indexOfMin = 0;
for (int i = 0; i < scores.length; i++) {
if (scores[i] < min) {
min = scores[i];
indexOfMin = i;
}
}
choice[choiceCount] = moves[indexOfMin];
scoreArray[choiceCount] = scores[indexOfMin];
choiceCount++;
return min;
}
}
public int getIndex(String r, String c) {
if (r.equals("a")) {
if (c.equals("a")) {
return 0;
} else if (c.equals("b")) {
return 1;
} else if (c.equals("c")) {
return 2;
}
} else if (r.equals("b")) {
if (c.equals("a")) {
return 3;
} else if (c.equals("b")) {
return 4;
} else if (c.equals("c")) {
return 5;
}
} else if (r.equals("c")) {
if (c.equals("a")) {
return 6;
} else if (c.equals("b")) {
return 7;
} else if (c.equals("c")) {
return 8;
}
}
return 0;
}
}
A:
for (int i = 0; i < amt; i++) {
if (board2[i] == 0) { //if the space is empty
moves[count] = i;// appends the index of the next empty space to the moves array
count++;
}
}
shoudn't this loop run over the whole board?
like
for (int i = 0; i < board2.length; i++) {
(don't know if thats your problem, just saw that and thought it may be incorrect)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Pass phone number as destination of my message
Am trying to pass the phone number I picked from contact list of my device. I have edittext to write my message and then by one click I want to pick a number from the list and send at same time. Access phone number is confusing to me rather than access the name itself.( I don't need the name, i want to send my message to him/her as they have phone number.) I'm having java.lang.IllegalArgumentException: Invalid destinationAddress for sms.sendTextMessage**
public void Send(View view){
String myMsg = myMessage.getText().toString();
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(no,null,myMsg,null,null);//"8044842795
}
String no = "";
@Override
protected void onActivityResult(int reqCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(reqCode, resultCode, data);
if(reqCode == PICK_CONTACT) {
if(resultCode == ActionBarActivity.RESULT_OK) {
Uri contactData = data.getData();
Cursor cur = getContentResolver().query(contactData, null, null, null, null);
ContentResolver contect_resolver = getContentResolver();
if (cur.moveToFirst()) {
String id = cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
Cursor phoneCur = contect_resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);
if (phoneCur.moveToFirst()) {
no = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
}
}
}
}
A:
You need to send the SMS in onActivityResult. Until that is called, you don't know who was chosen so you can't get their number.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Distance of compact sets- Proof without subsequence convergence and continuity
There are many examples of this question in this platform, but what I am looking is a proof that uses open neighborhoods i.e., topological properties.
Let $X$ be metric space $A,B$ compact and define
$$dist(A,B)=\inf\{ d(x,y):x\in A,y\in B \}
$$
Prove that there exists $a\in A$ and $b\in B$ such that $dist(A,B)=d(a,b)$
As I said I am aware one can prove this by using every sequence in a compatc set has a convergent subsequence in the set, or by using continuity of the distance functions. However, I tried to prove by using open sets. Here is what I attempt:
Suppose $A\cap B=\emptyset$ otherwise the result is trivial. Now for each $y\in B$ there exist open neighborhood $U_y$ such that $U_y\cap A=\emptyset$. If not some $y\in B$ will be limit point of $A$ which implies $y\in A$ due to compactness, but this contradicts $A\cap B=\emptyset$. Similarly, for each $x\in A$ there exists $V_x$ such that $V_x\cap B=\emptyset$. We can cover $A$ with $\{V_x\}$ and $B$ with $\{U_y\}$. By compactness
$$
A\subset \bigcup_{i=1}^n V_i=\mathcal{V} \text{ and } B\subset\bigcup_{j=1}^mU_j=\mathcal{U}
$$
Plainly $A\cap \mathcal{U}=\emptyset$ and $B\cap\mathcal{V}=\emptyset$. From here I tried various things without any success. So any help from here or the proof without using previously mentioned methods are greatly appreciated. Thanks!
A:
Let $d(A,B)=:\rho$. If there is no pair of points $(a,b)\in A\times B$ with $d(a,b)=\rho$ then for each pair $(x,y)\in A\times B$ there is an $\epsilon>0$ (depending on $x$ and $y$) such that $d(x,y)\geq\rho+3\epsilon$. The triangle inequality allows to conclude that $d(x',y')\geq\rho+\epsilon$ for all $(x',y')\in U_\epsilon(x)\times U_\epsilon(y)$.
Since $A\times B$ is compact finitely many "boxes" $U_{\epsilon_k}(x_k)\times U_{\epsilon_k}(y_k)$ will cover $A\times B$. Put $\epsilon_*:=\min_k \epsilon_k$. Then $$d(x,y)\geq\rho+\epsilon_*\qquad\forall x\in A,\quad\forall y\in B\ ,$$
contradicting the definition of $\rho$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Do you need to see where you move a flaming sphere as a bonus action?
Example: Cast the sphere then duck around a corner away from the fight and move it on each of your turns as a bonus action while staying safe and keeping concentration.
Flaming Sphere (PHB 242-243)
A 5-foot-diameter Sphere of fire appears in an unoccupied space of your choice within range and lasts for the Duration. Any creature that ends its turn within 5 feet of the Sphere must make a Dexterity saving throw. The creature takes 2d6 fire damage on a failed save, or half as much damage on a successful one.
As a Bonus Action, you can move the Sphere up to 30 feet. If you ram the Sphere into a creature, that creature must make the saving throw against the sphere's damage, and the Sphere stops moving this turn.
When you move the Sphere, you can direct it over barriers up to 5 feet tall and jump it across pits up to 10 feet wide. The Sphere ignites flammable Objects not being worn or carried, and it sheds bright light in a 20-foot radius and dim light for an additional 20 feet.
At Higher Levels: When you cast this spell using a spell slot of 3rd Level or higher, the damage increases by 1d6 for each slot level above 2nd.
Do you need to be able to see where you want to move a flaming sphere to?
A:
No you don’t need to see where you are moving it
According to Jeremy Crawford:
The text of the flaming sphere spell explains how the sphere interacts with barriers, creatures, and pits as it rolls around. As the caster, you don't have to see where you move it –January 25, 2018 SageAdvice.
This may be unofficial but it seems to back up the "spells do what they say they do" aspect of spell casting. Since there is no mention of moving it to "where you can see" it therefore doesn't need to be moved to where you can see.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Arrow before and after a box with CSS
I'm trying to create in a single box, two arrows, one as a pointer and the other one into the box just behind.
Can not find the way to get the arrow right behind.
Someone can help me??
here i post the link with the sample: http://jsfiddle.net/7Esu2/
CSS:
.arrow {
width:210px;
height:40px;
background-color:#CBCBCB;
border: 1px solid #CBCBCB;
position:relative;
text-align:center;
font-size:20px;
font-weight:bold;
line-height:40px;
}
.arrow:after {
content:'';
position:absolute;
top:-1px;
left:210px;
width:0;
height:0;
border:21px solid transparent;
border-left:15px solid #CBCBCB;
}
.arrow:before {
content:'';
position:absolute;
top:-1px;
left:211px;
width:0;
height:0;
border:21px solid transparent;
border-left:15px solid #CBCBCB;
}
HTML:
<div class="arrow">
FLECHA
</div>
A:
I prefer using inline-blocks over absolute positioning. Also, :before and :after create child elements (inside) the element you specify them on (at the beginning and end). For this, it would probably be best to have a wrapper (or inner) block, like so:
<div class="arrow">
<div class="inner-arrow">
FLECHA
</div>
</div>
Then the inner block is going to get most of the styling, as the wrapper is primarily there to contain the :before and :after. The wrapper (.arrow) needs to have font-size: 0 (or some other method to make the white-space around the inner block, .inner-arrow, go away).
.arrow {
font-size: 0;
}
.inner-arrow {
width:210px;
height:40px;
display: inline-block;
background-color:#CBCBCB;
text-align:center;
font-size:20px;
font-weight:bold;
line-height:40px;
vertical-align: middle;
}
Most of the styles for .arrow:before and .arrow:after will be the same, so we'll group those. Then specify the differences below (they have to be below to override the common styles).
.arrow:before,
.arrow:after {
content:'';
display: inline-block;
width:0;
height:0;
border:20px solid transparent;
vertical-align: middle;
}
.arrow:before {
border-top-color: #CBCBCB;
border-bottom-color: #CBCBCB;
border-right-color: #CBCBCB;
}
.arrow:after {
border-left-color: #CBCBCB;
}
This is all in the a fiddle.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Як перекласти "bagging" з машинного навчання?
Неодноразово стикався з терміном bagging з розділу машинного навчання, але допоки не знайшов нормального українського перекладу (без прямої транслітерації).
Джерело на вікі - тут.
Українське джерело, де описується термін "bagging". Але він з транслітерацією.
Ще тут, але тут просто зробили транслітерацію.
По суті, bagging збирає різні варіанти моделей й узагальнює - створюється своєрідна "торба", куди складаються прийнятні варіанти -> "торбування" :-)
A:
Зайшов на Вікі, подивився на інтервікі, отже, німці використали bagging, a корейці, японці і китайці просто транслітерували. І лише іспанці використали синонімічну назву, щось на схоже на групування бутстрепів нашою. Тому, як варіант можна бегінг.
Власне термін означає алгоритм використовний для уникнення перенавчання. Тобто спочатку робиться декілька вибірок із повторами, припасовують криву до кожної з них. Всі ці криві дуже хвилясті, бо надто точно відповідають даним. А тоді якимось чином усереднюють між цими кривими, в результаті виходить гладка крива. Дивись зображення для ясності.
Знов до перекладу, було б класно якось погратись із усередненням між кривими, чи, радше, припасуванням кривої, так, щоб найкраще схопити дані з цілого жмута входових кривих і прямим перекладом bagging - мішковина, пакування в мішки.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why i'm getting OutOfMemoryException even if i release/dispose the Bitmap?
I have this class where i using the code to take screenshots:
using System;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Drawing.Imaging;
namespace WindowsFormsApplication1
{
/// <summary>
/// Provides functions to capture the entire screen, or a particular window, and save it to a file.
/// </summary>
public class ScreenCapture
{
/// <summary>
/// Creates an Image object containing a screen shot of the entire desktop
/// </summary>
/// <returns></returns>
public Image CaptureScreen()
{
return CaptureWindow(User32.GetDesktopWindow());
}
/// <summary>
/// Creates an Image object containing a screen shot of a specific window
/// </summary>
/// <param name="handle">The handle to the window. (In windows forms, this is obtained by the Handle property)</param>
/// <returns></returns>
public Image CaptureWindow(IntPtr handle)
{
// get te hDC of the target window
IntPtr hdcSrc = User32.GetWindowDC(handle);
// get the size
User32.RECT windowRect = new User32.RECT();
User32.GetWindowRect(handle, ref windowRect);
int width = windowRect.right - windowRect.left;
int height = windowRect.bottom - windowRect.top;
// create a device context we can copy to
IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc);
// create a bitmap we can copy it to,
// using GetDeviceCaps to get the width/height
IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc, width, height);
// select the bitmap object
IntPtr hOld = GDI32.SelectObject(hdcDest, hBitmap);
// bitblt over
GDI32.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, GDI32.SRCCOPY);
// restore selection
GDI32.SelectObject(hdcDest, hOld);
// clean up
GDI32.DeleteDC(hdcDest);
User32.ReleaseDC(handle, hdcSrc);
// get a .NET image object for it
Image img = Image.FromHbitmap(hBitmap);
// free up the Bitmap object
GDI32.DeleteObject(hBitmap);
return img;
}
/// <summary>
/// Captures a screen shot of a specific window, and saves it to a file
/// </summary>
/// <param name="handle"></param>
/// <param name="filename"></param>
/// <param name="format"></param>
public void CaptureWindowToFile(IntPtr handle, string filename, ImageFormat format)
{
using (Image img = CaptureWindow(handle))
{
img.Save(filename, format);
}
}
/// <summary>
/// Captures a screen shot of the entire desktop, and saves it to a file
/// </summary>
/// <param name="filename"></param>
/// <param name="format"></param>
public void CaptureScreenToFile(string filename, ImageFormat format)
{
using (Image img = CaptureScreen())
{
img.Save(filename, format);
}
}
/// <summary>
/// Helper class containing Gdi32 API functions
/// </summary>
private class GDI32
{
public const int SRCCOPY = 0x00CC0020; // BitBlt dwRop parameter
[DllImport("gdi32.dll")]
public static extern bool BitBlt(IntPtr hObject, int nXDest, int nYDest,
int nWidth, int nHeight, IntPtr hObjectSource,
int nXSrc, int nYSrc, int dwRop);
[DllImport("gdi32.dll")]
public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth,
int nHeight);
[DllImport("gdi32.dll")]
public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
[DllImport("gdi32.dll")]
public static extern bool DeleteDC(IntPtr hDC);
[DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
[DllImport("gdi32.dll")]
public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
}
/// <summary>
/// Helper class containing User32 API functions
/// </summary>
private class User32
{
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
[DllImport("user32.dll")]
public static extern IntPtr GetDesktopWindow();
[DllImport("user32.dll")]
public static extern IntPtr GetWindowDC(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);
[DllImport("user32.dll")]
public static extern IntPtr GetWindowRect(IntPtr hWnd, ref RECT rect);
}
}
}
Then i have a new class i created where i'm using AviFile to create avi movie files from screenshots in real time:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AviFile;
using System.Drawing;
namespace WindowsFormsApplication1
{
class ScreenshotsToAvi
{
int count = 0;
VideoStream aviStream;
AviManager aviManager;
Bitmap bmp;
public ScreenshotsToAvi()
{
aviManager = new AviManager(@"d:\testdata\new.avi", false);
}
public void CreateAvi(ScreenCapture sc)
{
bmp = new Bitmap(sc.CaptureScreen());
count++;
if (count == 1)
{
aviStream = aviManager.AddVideoStream(false, 25, bmp);
}
aviStream.AddFrame(bmp);
bmp.Dispose();
}
public AviManager avim
{
get
{
return aviManager;
}
set
{
aviManager = value;
}
}
}
}
Then in form i use it like this:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
ScreenshotsToAvi screens2avi;
int count;
ScreenCapture sc;
public Form1()
{
InitializeComponent();
screens2avi = new ScreenshotsToAvi();
label2.Text = "0";
count = 0;
sc = new ScreenCapture();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
count++;
sc.CaptureScreen();
screens2avi.CreateAvi(this.sc);
label2.Text = count.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
screens2avi.avim.Close();
}
private void button3_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
string[] filePaths = Directory.GetFiles(@"c:\temp\screens7\");
foreach (string filePath in filePaths)
File.Delete(filePath);
label2.Text = "0";
}
}
}
After the program i running for about a minute or two it's getting to the ScreenShotsToAvi class and on this line throw the exception:
bmp = new Bitmap(sc.CaptureScreen());
Out of memory
System.OutOfMemoryException was unhandled
HResult=-2147024882
Message=Out of memory.
Source=System.Drawing
StackTrace:
at System.Drawing.Graphics.CheckErrorStatus(Int32 status)
at System.Drawing.Graphics.DrawImage(Image image, Int32 x, Int32 y, Int32 width, Int32 height)
at System.Drawing.Bitmap..ctor(Image original, Int32 width, Int32 height)
at System.Drawing.Bitmap..ctor(Image original)
at WindowsFormsApplication1.ScreenshotsToAvi.CreateAvi(ScreenCapture sc) in d:\C-Sharp\ReadWriteToMemory\WindowsFormsApplication1\WindowsFormsApplication1\ScreenshotsToAvi.cs:line 26
at WindowsFormsApplication1.Form1.timer1_Tick(Object sender, EventArgs e) in d:\C-Sharp\ReadWriteToMemory\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs:line 41
at System.Windows.Forms.Timer.OnTick(EventArgs e)
at System.Windows.Forms.Timer.TimerNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at WindowsFormsApplication1.Program.Main() in d:\C-Sharp\ReadWriteToMemory\WindowsFormsApplication1\WindowsFormsApplication1\Program.cs:line 19
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
And again im disposing the bmp all the time so why the exception is coming up ? Do i need to dispose anything else too ?
public void CreateAvi(ScreenCapture sc)
{
bmp = new Bitmap(sc.CaptureScreen());
count++;
if (count == 1)
{
aviStream = aviManager.AddVideoStream(false, 25, bmp);
}
aviStream.AddFrame(bmp);
bmp.Dispose();
}
A:
bmp = new Bitmap(sc.CaptureScreen());
That's a Big Red Flag. I'd assume that the CaptureScreen() method returns an Image or Bitmap object. Then you make a copy of it for some reason. And only dispose the copy, you do not dispose the original image that was returned by CaptureScreen().
That won't last long.
Assuming you actually need the copy (I have no idea why), you'll have to write it like this:
using (var img = sc.CaptureScreen())
using (var bmp = new Bitmap(img)) {
// etc..
}
There are very few Image objects that are not actually a Bitmap. Only a Metafile could be the other flavor, you won't get one from a screen-shot. So do try:
using (var bmp = (Bitmap)sc.CaptureScreen()) {
// etc..
}
Look at the VM size of your process in Task Manager to verify that your memory usage is now reasonably stable and no longer explodes. You want to see it rapidly increase, then bounce up and down as the program keeps running. The AVI encoder could be a resource hog as well if it doesn't stream the avi data directly to the file. You may need to switch to 64-bit code if it requires too much memory. Add the GDI Objects column in Task Manager, it reliably tells you if you are still leaking bitmap objects.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to create a UITableView that can scroll horizontally?
I am trying to create a verticalTableView that has a horizontalTableView inside each verticalTableViewCell that can scroll horizontally (same concept as the 'Pulse' app). And I have found a number of tutorials (two examples below), but they are all in the days of XIBs. Can anyone explain how to do it/give me a link to a tutorial on how to do the same with a Storyboard instead?
First Tutorial
Second Tutorial
Update: I have since found another question on SO that was answered by the same person that asked the question. This person has managed to implement the protocols for a tableView using a UITableViewCell class, question is how? And does it matter that the tableView that contains the dynamic tableView is static?
dynamic UITableView in static UITableViewCell
A:
Use the below part of code to create the required table.
UITableView *horizontalTable = [[UITableView alloc] init];
[horizontalTable setDelegate:self];
[horizontalTable setDataSource:self];
horizontalTable.transform = CGAffineTransformMakeRotation(-M_PI * 0.5);
horizontalTable.autoresizesSubviews=NO;
frame =CGRectMake(140, 0 , 642, 85);
//frame is important this has to be set accordingly. if we did not set it properly, tableview will not appear some times in the view
[self.view addSubview:customTable];
and in the custom cell's CustomCell Class, we find the below method.
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
in that method,
use this.
self.transform = CGAffineTransformMakeRotation(M_PI * 0.5);
A:
Thanks to @christoph, I finally figured it out. See sample code in his question.
dynamic UITableView in static UITableViewCell
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to Increase max file upload in PHP?
I have a small problem with upload file.
I was set in php.ini:
upload_max_filesize = 64M
post_max_size = 64M
max_execution_time = 300
But when I re-check, it still have old value
upload_max_filesize 2M
value in phpinfo()
I used php7-fpm with nginx, and restarted after change php.ini.
Please help me, thanks.
A:
Do Changes in you config file /etc/php/7.0/fpm/php.ini and save it.
Then run the following commands:
sudo service php7-fpm restart
sudo service nginx restart
Check phpinfo() it will work!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Moving items between arrays in vue.js
I have two arrays with custom components in each.
List a is a search result. List b is a list of selected items.
Each component has a template that renders the item in the array.
So... the trouble I'm having is, once I have my list in list a, i want to click a link and have it add to list b. But when I try to add the item, I'm being told that Cannot read property 'push' of undefined
Here's my entire Vue. What am I doing wrong?
new Vue({
el: '#search',
data: {
query: '',
listA: '',
listB: ''
},
methods: {
search: function(event) {
if (this.query != "") {
this.$http({url: '/list-a?search=' + this.query, method: 'GET'}).then(function(response) {
this.listA = response.data
});
};
event.preventDefault();
}
},
components: {
listaitem: {
template: '#listaitem-template',
props: ['lista-item'],
methods: {
selected: function(listaitem) {
// When clicked, this will add this listaitem to listB
this.listB.push(listaitem);
}
}
},
listbitem: {
template: '#listbitem-template',
props: ['listbitem']
}
}
});
A:
You should initialize listA and listB as empty arrays instead of empty strings like
data: {
query: '',
listA: [],
listB: []
}
This will allow you use this.listB.push(listaitem); in the listaitem component without throwing an error
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Bootstrap offcanvas sidebar toggling for any canvas size
Could you please explain how offcanvas sidebar toggling works?
I can't make the actual sidebar disappear for sm. I can make the button visible (visible-sm), but toggling doesn't work - the sidebar is always visible.
Toggling works for xs size, that's fine, but I want to make it work for sm the same way, or any other size for that matter.
Partial answer: Changing max-width in offcanvas.css makes toggling work for bigger sizes as well, sm in this case:
@media screen and (max-width: 991px) {
/* 991px instead of 767px makes toggling work for sm as well */
.row-offcanvas {
/* ... */
}
/* and so on */
}
But there's still a problem - when canvas width is between 780 and 991px, the sidebar is visible even if it's toggled off. Any idea how to fix this?
Thanks a lot
A:
How does the Bootstrap off canvas example works?
The Bootstrap offcanvas example uses the grid system. For xs screens, the content spans 12 columns (full screen width) and sidebar spans 6 columns (1/2 screen width).
Normally the sidebar would be pushed under the content. However in offcanvas.css there is a rule that uses absolute positioning to place it on the right top, outside the screen.
When you press 'Toggle nav', it moves the .row half the screen width (50%) to the left, revealing the sidebar.
Why is the sidebar shown for screen widths between 768px and 992px?
Your problem is caused by the .container placed around the .row. A container has a fixed width for viewports above 768px. You can solve this by using width: auto for small screens.
@media (max-width: 991px) {
.container-smooth-sm {
width: auto;
max-width: none;
}
}
A more advanced off canvas plugin
For my projects, this approach proved to limited. Therefor I've created the offcanvas plugin and navmenu component. The plugin can also be used to show the navbar as offcanvas menu for small screens.
Here are some examples using the Jasny Bootstrap offcanvas plugin
Slide in effect
Push effect
Reveal effect
Offcanvas navbar
|
{
"pile_set_name": "StackExchange"
}
|
Q:
VBA: Speeding up Copying
I have two questions regarding VBA efficiency. My VBA code grabs a cell value from one sheet, places it in another excel workbook which then performs it's own calculations and returns a result, and I copy that result back into the original workbook.A simplified version of my code is:
dim currentWB as workbook
dim currentSheet as worksheet
dim calcWB as workbook
dim calcSheet as worksheet
dim numRows as integer
dim i as integer
dim target as range
dim result as range
set currentWB = workbooks.Open(...)
set currentSheet = currentWB.Sheets("sheetName")
set calcWB = workbooks.Open(...)
set calcSheet = calcWB.Sheets("sheetName")
set target = calcSheet.Cells(1,1)
set result = calcSheet.Cells(2,1)
numRows = activeSheet.UsedRange.Rows.count
For i = 0 to numRows
target.Value = currentSheet.Cells(i,1).Value
currentSheet.Cells(i,2) = result.Value
next i
currentWB.Close SaveChanges:=True
calcWB.Close SaveChanges:=False
In the actual script, we're copying over not one like above, but 13. The loop goes through ~ 15,000 records. Right now, I'm averaging 1.5 seconds per loop.
The two questions I have are:
Should I be naming and setting these ranges, i.e.:
dim target as range
set target = calcSheet.Cells(1,1)
target.Value = currentSheet.Cells(i,1).Value
Instead of
calcSheet.Cells(1,1).Value = currentSheet.Cells(i,1).Value
Is there a better way to do the copy of several non sequential cells from one sheet to another, i.e.
Instead of
curSheet.Cells(i, 1) = someRange.Value
curSheet.Cells(i, 2) = someRange2.Value
curSheet.Cells(i, 3) = someRange3.Value
...
curSheet.Cells(i, 14) = someRange14.Value
curSheet.Cells(i, 15) = someRange15.Value
curSheet.Cells(i, 16) = someRange16.Value
Something quicker?
Thank you all so much!
With gratitude,
Zac
**This code took 66 seconds to run 50 records (compare with solutions below)
A:
If you want to copy many values at once then use a direct assignment
currentSheet.Range("A1").Resize(numRows,1).Value = otherSheet.Range("A1").Resize(numRows,1).Value
The .Range() property convers a single cell into a range of cells with the given dimensions and all their values can be assigned or copied.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
re-assigning parameters
I've seen the following in legacy code:
public void someFunction(List myList){
List myList2 = myList;
}
Is there a good reason to re-assign parameters as local variables in a function?
A:
Not really. Aliasing or reuse of names should be avoided, in my opinion.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
execute javascript on every reload - ruby on rails
I am reloading partial using ajax this way:
new Ajax.PeriodicalUpdater('content', '/shouts/update.js', { method: 'get', frequency: 1});
The reload is working great.
I added this javascript code to update.js to make the partial content fade:
$('content').fade({ duration: 3.0, from: 0, to: 1 });
And the problem is that nothing happens (the content doesn't fade).
What do you think is the problem?
A:
I think the problem is that there is no fade function in JQuery... Try fadeTo
$('content').fadeTo(3000, 0);
also there is the function fadeToggle(). There you have a simple switch :)
UPDATE: thought it is was jquery... within Ajax.PeriodicalUpdater you can set the parameter evalScripts to true then the script will be available...
http://api.prototypejs.org/ajax/Ajax/Updater/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a mapping in the standard library between Swift's String.Encoding and the IANA character set names?
Does a mapping exist in the standard library between the String.Encoding enumeration and the standard IANA character set names, e.g., "UTF-8" for String.Encoding.utf8? I was not able to find one.
I'm aware that Foundation's CFStringEncoding can be mapped to IANA character set names, but I could not find a way to go from String.Encoding to CFStringEncoding. CFStringEncoding is just a type alias for UInt32, and the String.Encoding enumeration is backed by a UInt, but unless I've made some simple error, they do not seem to correspond.
A:
The raw value of a String.Encoding is an NSStringEncoding and that can be converted to a CFStringEncoding with CFStringConvertNSStringEncodingToEncoding. The IANA charset name is then determined with CFStringConvertEncodingToIANACharSetName. This function returns an optional CFString which can be toll-free bridged to an optional Swift String.
Example:
let enc = String.Encoding.isoLatin2
let cfEnc = CFStringConvertNSStringEncodingToEncoding(enc.rawValue)
if let ianaName = CFStringConvertEncodingToIANACharSetName(cfEnc) as String? {
print(ianaName) // iso-8859-2
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Where is the state saved for arbitrary state processing using mapGroupsWithState?
I am using mapGroupsWithState on a streaming dataset to maintain state across batches. Where is this data/state stored? Executors, the driver or somewhere else?
A:
but I am not sure where this data/state is stored? (Executor or driver)
State is persisted to [checkpointLocation]/state that should be on a reliable HDFS-compliant distributed file system so executors (and tasks) can access it when required.
That gives [checkpointLocation]/state.
There could be many stateful operators, each with its own operatorId that is used to store operator-specific state. That's why you may have zero, one or more state subdirectories for every stateful operator.
That gives [checkpointLocation]/state/[operatorId].
There are even more subdirectories in stateful operator-specific state directory for partitions.
That gives the following state-specific directory layout:
[checkpointLocation]/state/[operatorId]/[partitionId]
Use web UI to find out the checkpointLocation, operatorId and the number of partitions.
The state of a stateful operator is recreated from [checkpointLocation]/state using StateStoreRestoreExec unary physical operator (use explain to find it). StateStoreRestoreExec restores (reads) a streaming state from a state store for the keys that are given by the child physical operator. My understanding is that the state is recreated every micro-batch.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Set automatically the name ID of many mosaics in Google Earth Engine
I'm using a code wrote here in Stack in the question Mosaicking a Image Collection by Date (day) in Google Earth Engine to generate mosaics of Sentinel-1 by date (day) with images that cover a region. But in the code, the new Image Collection don't have a ID for each mosaic, anything like the date of the images or the date of images interval that it uses. There is any way to do this?
My code is:
var start = ee.Date('2014-10-01');
var finish = ee.Date('2018-03-31');
var collection = ee.ImageCollection('COPERNICUS/S1_GRD')
.filterDate(start, finish)
.filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV'))
.filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VH'))
.filter(ee.Filter.eq('instrumentMode', 'IW'))
.filterMetadata('resolution_meters', 'equals', 10)
.filterBounds(poly);
print(collection,"Original collection");
// Difference in days between start and finish
var diff = finish.difference(start, 'day');
print(diff, "Diferenca em dias");
// Make a list of all dates
var range = ee.List.sequence(0, diff.subtract(1)).map(function(day){return start.advance(day,'day')});
print(range, "Lista de todas as datas");
// Funtion for iteraton over the range of dates
var day_mosaics = function(date, newlist) {
// Cast
date = ee.Date(date);
newlist = ee.List(newlist);
// Filter collection between date and the next day
var filtered = collection.filterDate(date, date.advance(1,'day'));
// get date as YEARMONTHDAY. For example, for January 8th 2010
// would be: 20100108
var date_formatted = ee.Number.parse(date.format('YYYYMMdd'))
// make date band as an 32 bit unsigned integer and rename it as 'date'
var dateband = ee.Image.constant(date_formatted).toUint32().rename('date');
// Make the mosaic
var image = ee.Image(filtered.mosaic());
// Add the mosaic to a list only if the collection has images
return ee.List(ee.Algorithms.If(filtered.size(), newlist.add(image), newlist));
};
// Iterate over the range to make a new list, and then cast the list to an imagecollection
var newcol = ee.ImageCollection(ee.List(range.iterate(day_mosaics, ee.List([]))));
print(newcol, "Collection with mosaic images");
Map.centerObject(poly);
Map.addLayer(newcol, {bands: 'VV', min: -20, max: -5});
Follow the link to my code: Mosaicking by date.
A:
Use the set Image method to add an ID property to each image passed through the day_mosaics function. From your example, try this at line 40:
var image = ee.Image(filtered.mosaic())
.set('ID', date_formatted);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Speechless mathematical proofs.
Do you have proofs without word?
Your proofs are not necessary has zero word, you may add a bit explanations.
As an example, I has a "Speechless proof" for
$$\frac{1}{4}+\frac{1}{4^2}+\frac{1}{4^3}+...=\frac{1}{3}$$
I welcome all aspects of mathematical proofs. Thank you.
A:
The best one I have ever seen is to prove $$1 + 2 + 3 + \cdots + n = \dfrac{n(n+1)}2$$
A:
Found this great one surfing the web recently.
$$
\displaystyle \huge \frac12+\frac14+\frac18+\frac1{16}+\frac1{32}+\ldots =1
$$
A:
Reciprocals of squares converge.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
jqGrid reload from custom editFunc not working
I have a code for jqGrid with custom "editFunc" that opens my own jQuery-UI Panel to edit the data.
It saves the data without problems, but I can't get jqGrid to be updated with new data automatically using "$("#blog-posts").trigger("reloadGrid");" It doesn't work from "editFunc". The code is below. Not sure how to fix it.
What I'm doing wrong here?
Another way I thought about is to do not do a full jqGrid reload, but update only the edited data. How to update a successfully edited jqGrid row with sucessfuly changed record data "manually" from editFunc, without reloading all records?
Here is my jqGrid config:
<table id="blog-posts">
</table>
<div id="blog-posts-nav">
</div>
<div id="edit-blog-post">
</div>
<script type="text/javascript">
function wireUpForm(dialog, updateTargetId, updateUrl) {
$('form', dialog).submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
// Check whether the post was successful
if (result.success) {
// Close the dialog
$(dialog).dialog('close');
// reload doesn't work if called from here
$("#blog-posts").trigger("reloadGrid");
} else {
// Reload the dialog to show model errors
$(dialog).html(result);
// Setup the ajax submit logic
wireUpForm(dialog, updateTargetId, updateUrl);
}
}
});
return false;
});
}
$('#blog-posts').jqGrid({
url: 'http://localhost:24533/Admin/BlogPosts',
datatype: "json",
colModel: [
{ name: 'id', index: 'id', label: 'Post ID', width: 55 },
{ name: 'enabled', index: 'enabled', label: 'Enabled', width: 60, editable: true, edittype: "checkbox", editoptions: { value: "Yes:No"} },
{ name: 'slug', index: 'slug', label: 'Slug', width: 300, editable: true, editoptions: { style: "width:300px;"} },
{ name: 'header', index: 'header', label: 'Header', width: 300, editable: true },
{ name: 'HtmlTitle', index: 'HtmlTitle', label: 'HTML Title', width: 300, editable: true },
{name: 'created', index: 'created', label: 'Created', width: 100, editable: true },
{ name: 'lastUpdate', index: 'lastUpdate', label: 'Last Update', width: 100 }
],
rowNum: 10,
rowList: [10, 20, 30],
pager: '#blog-posts-nav',
sortname: 'id',
viewrecords: true,
sortorder: "desc",
caption: "Blog Posts",
height: 210,
});
$('#blog-posts').jqGrid('navGrid', '#blog-posts-nav',
{
editfunc: function (rowid) {
var element = $(this);
// Retrieve values from the HTML5 data attributes of the link
var dialogId = '#edit-blog-post';
var dialogTitle = 'Dialog Title';
var updateTargetId = '#container-to-update';
var updateUrl = 'http://localhost:24533/Admin/BlogPostEdit/';
// Load the form into the dialog div
$(dialogId).load('http://localhost:24533/Admin/BlogPostEdit?id=' + rowid, function () {
$(this).dialog({
modal: false,
resizable: true,
minWidth: 650,
minHeight: 300,
height: $(window).height() * 0.95,
title: dialogTitle,
buttons: {
"Save": function () {
// Manually submit the form
var form = $('form', this);
//alert('1');
$(form).submit();
$("#blog-posts").trigger("reloadGrid");
//alert('2');
},
"Cancel": function () {
//alert($("#blog-posts"));
//$("#blog-posts").trigger("reloadGrid");
//alert($("#blog-posts").getCell(2,2));
//alert($("#blog-posts").getGridParam('caption'));
$("#blog-posts").trigger("reloadGrid");
//alert(element.serialize());
//element.trigger("reloadGrid");
//alert(element.attr('id'));
//$(this).dialog('close');
}
}
});
wireUpForm(this, updateTargetId, updateUrl);
});
return false;
},
{ height: 280, reloadAfterSubmit: true }, // edit options
{width: 600, reloadAfterSubmit: true, top: 100, left: 300, addCaption: 'Add Blog Post' }, // add options
{reloadAfterSubmit: true }, // del options
{} // search options
);
$('.wysiwyg').livequery(function () {
$(this).wysiwyg();
});
</script>
UPDATE: The problematic line of code is
$(dialogId).load('http://localhost:24533/Admin/BlogPostEdit?id=' + rowid, function () {
After you do jQuery.load() the jqGrid's programmatic reload binding call trigger("reloadGrid") doesn't work anymore. The only way to reload the data that works after you do jQuery.load() is the reload button in the toolbar. I still don't know how to fix it.
UPDATE2 (solution): The problem was in HTML returned from jQuery.ajax() it was a full HTML page with HTML head and body tags. After server side started to return only the form jqGrid reload started to work.
A:
I think the problem exist because you use $(form).submit(). What you probably want to do is to send data from the form to the server and refresh the data in the grid after the server processed the form submittion.
The $(form).submit() will be used in the case that your page consist mostly from the form. In the case you submit the data and the page will be refreshed. What you probably really want to do you can implement with respect of $.ajax with type: 'POST' parameter or with respect of its simplified form $.post. You can set the submit event handler (or click handler if you rename the type of the button) and inside the handler you can send the data to the server per $.ajax manually. In the case you can use success handler to reload the grid. Inside of submit event handler you can get the form data with $(form).serialize() and you should return false to prevent standard submitting of the form. See here an example. You should don't forget to define name attribute to all fields of the form which you want send to the server (see here).
I don't know exactly which relationship has the form to the grid data, but one more possible option which you have is to use postData parameter of jqGrid. See here for more details.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Edit entity when have a database in production
I have create my app with jhipster in july, and i have put it in production.
Now i need edit a entity.
When i use jhipster entity the subgenerator update the initial xml generate for the entity, but not is thes the correct work, the code need create a new xml with the update like: mvn liquibase:diff
Searching on the web i have foud this answere: Add new field to existing entity with JHipster. At a certain point the user say:
create a new migration file to add only the new column (see addColumn
documentation), revert the creation migration to its original content
using git, run your app to apply changes to your database. This is
what you would do when your app is in production.
In reference the last phrase, is the true? Jhipster entity subgenerator not support update of db but only initial creation?
tks
A:
Yes it's correct.
Either you write a manual Liquibase migration or you use liquibase:diff to help you in this process.
See official docs: https://www.jhipster.tech/development/#database-updates-with-the-maven-liquibasediff-goal
|
{
"pile_set_name": "StackExchange"
}
|
Q:
paperclip upload picture
Here is my need:
I have three prize, each prize has one pic, like:
prize1 pic1
prize2 pic2
prize3 pic3
Here is my design:
I use four record in my database, row 1 to 3 is mappingt to prize1 to prize3, and row4 is a default prize which can be used as adding prize.
Here comes the question:
When is user paperclip to upload my pic, there's some problem to identify each pic. Details are following:
<form>
<input type="file" name="pic[]">
<input type="file" name="pic[]">
<input type="file" name="pic[]">
<input type="submit">
</form>
When I choose choose file to upload and submit the form, pic array will be passed by params, so I can get the the pic, and save them by the ordering of array.
However, when I only choose file for one prize, the array's size will be 1, and I couldn't judge which one has changed in the backend, so I'd like to hear from all of you, let me have a look at how you design it or could I make some changes to solve it!
Tanks any way
A:
You will want to make sure that the photo upload is the correct resource that is updating the prize that you are wanting.
Assuming that each prize in your database has its own row and paperclip column set up correctly you will want the form to be like this:
= form_for @prize, method: 'put', html: { multipart: true } do |f|
= f.file 'pic'
= f.submit
This should PUT the the picture information to the /prize/1234 and the controller should consider the photo fields/params as attributes and update accordingly.
Things to watch out for:
Don't forget to add multi-part
Make sure that paperclip is configured properly
Make sure that other attributed in thr form for the product can be updated as well
Good luck!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Generic variable tree Error infinity loop
I am creating a variable tree, but I've got an error, seemingly in the insert or print_wevr function.
When I run the program I get an infinite loop.
How can I go about this?
/*5 - VarTrees*/
/*var_trees.c*/
#include <stdio.h>
#include <stdlib.h>
#include "var_trees.h"
/*Defining the struture of variable tree.
* The nodes has tree fields:
info: an generic information
first: the first child-node
next: the next sibling-node
*/
struct var_tree{
void* info;
Var_Tree* first;
Var_Tree* next;
};
/*Create the tree*/
Var_Tree* create(void* info)
{
Var_Tree* t = (Var_Tree*) malloc(sizeof(Var_Tree));
t->info = info;
t->first = NULL;
t->next = NULL;
return t;
}
/*Insert a node*/
void insert(Var_Tree* t,Var_Tree* st)
{
st->next = t->first;
t->first = st;
}
/*go_through the tree*/
void go(Var_Tree* t, void (*cb)(void*))
{
Var_Tree* p;
cb(t->info);
for(p = t->first; p != NULL; p = p->next)
go(t,cb);
printf(">");
}
/*Remove a node*/
//void remov(Var_Tree* t, void* info);
/*5 - VarTrees*/
/*main.c*/
#include <stdio.h>
#include <stdlib.h>
#include "var_trees.h"
Var_Tree* create_int(int info)
{
return create(&info);
}
void print_int(void* info)
{
int* t = (int*) info;
printf("<%d",*t);
}
int main(void)
{
Var_Tree* a = create_int(4);
Var_Tree* b = create_int(3);
Var_Tree* c = create_int(23);
Var_Tree* d = create_int(1);
Var_Tree* e = create_int(2);
insert(a,b);
go(a,print_tree);
}
The function create_int is a function for creating a node with the field info as int.
print_int is a callback function that prints an integer (the '<' creates a type of textual notation for trees).
A:
Here in go function, you are making a recursive call without changing the parameters that eventually lead to infinite recursion.
void go(Var_Tree* t, void (*cb)(void*))
{
Var_Tree* p;
cb(t->info);
for(p = t->first; p != NULL; p = p->next)
go(t,cb); //<-----here you are calling the same
function with the same parameter that leads to an infinite loop
printf(">");
}
You should pass the value of p in place of t.
void go(Var_Tree* t, void (*cb)(void*))
{
Var_Tree* p;
cb(t->info);
for(p = t->first; p != NULL; p = p->next)
go(p,cb); //<----change t to p
printf(">");
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Online tripet generation - am I doing it right?
I'm trying to train a convolutional neural network with triplet loss (more about triplet loss here) in order to generate face embeddings (128 values that accurately describe a face).
In order to select only semi-hard triplets (distance(anchor, positive) < distance(anchor, negative)), I first feed all values in a mini-batch and calculate the distances:
distance1, distance2 = sess.run([d_pos, d_neg], feed_dict={x_anchor:input1, x_positive:input2, x_negative:input3})
Then I select the indices of the inputs with distances that respect the formula above:
valids_batch = compute_valids(distance1, distance2, batch_size)
The function compute_valids:
def compute_valids(distance1, distance2, batch_size):
valids = list();
for q in range(0, len(distance1)):
if(distance1[q] < distance2[q]):
valids.append(q)
return valids;
Then I learn only from the training examples with indices returned by this filter function:
input1_valid = [input1[q] for q in valids_batch]
input2_valid = [input2[q] for q in valids_batch]
input3_valid = [input3[q] for q in valids_batch]
_, loss_value, summary = sess.run([optimizer, cost, summary_op], feed_dict={x_anchor:input1_valid, x_positive:input2_valid, x_negative:input3_valid})
Where optimizer is defined as:
model1 = siamese_convnet(x_anchor)
model2 = siamese_convnet(x_positive)
model3 = siamese_convnet(x_negative)
d_pos = tf.reduce_sum(tf.square(model1 - model2), 1)
d_neg = tf.reduce_sum(tf.square(model1 - model3), 1)
cost = triplet_loss(d_pos, d_neg)
optimizer = tf.train.AdamOptimizer(learning_rate = 1e-4).minimize( cost )
But something is wrong because accuracy is very low (50%).
What am I doing wrong?
A:
There are a lot of reasons why your network is performing poorly. From what I understand, your triplet generation method is fine. Here are some tips that may help improve your performance.
The model
In deep metric learning, people usually use some pre-trained models on ImageNet classification task as these models are pretty expressive and can generate good representation for image. You can fine-tuning your model on the basis of these pre-trained models, e.g., VGG16, GoogleNet, ResNet.
How to fine-tuing
Even if you have a good pre-trained model, it is often difficult to directly optimize the triplet loss using these model on your own dataset. Since these pre-trained models are trained on ImageNet, if your dataset is vastly different from ImageNet, you can first fine-tuning the model using classification task on your dataset. Once your model performs reasonably well on the classification task on your custom dataset, you can use the classification model as base network (maybe a little tweak) for triplet network. It will often lead to much better performance.
Hyper parameters
Hyper parameters such as learning rate, momentum, weight_decay etc. are also extremely important for good performance (learning rate maybe the most important factor). Since your are fine-tuning and not training the network from scratch. You should use a small learning rate, for example, lr=0.001 or lr=0.0001. For momentum, 0.9 is a good choice. For weight_decay, people usually use 0.0005 or 0.00005.
If you add some fully connected layers, then for these layers, the learning rate may be higher than other layers (0.01 for example).
Which layer to fine-tuing
As your network has several layers, you need to decide which layer to fine-tune. Researcher have found that the lower layers in network just produce some generic features such as line or edges. Typically, people will freeze the updating of lower layers and only update the weight of upper layers which tend to produce task-oriented features. You should try to optimize starting from different lower layers and see which setting performs best.
Reference
Fast rcnn(Section 4.5, which layers to fine-tune)
Deep image retrieval(section 5.2, Influence of fine-tuning the representation)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
positions of page numbers, position of chapter headings, chapters AND Table of Contents, References
I am writing my PhD thesis (120+ pages) in latex, the deadline is approaching and I am struggling with layout problems.
I am using the documentstyle book.
I am posting both problems in this one thread because I am not sure if the solution might be related to both problems or not.
Problems are:
1.) The page numbers are mostly located on the top-right of each page (this is correct and where I want them to be).
However, only on the first page of chapters and on the first page of what I call "special chapters", the page number is located bottom-centered.
With "special chapters" I mean: List of Contents, List of Figures, List of Tables, References, Index.
My university will not accept the thesis like this. The page number must ALWAYS be top-right one each page, even if the page is the first page of a chapter or the first page of something like the List of Contents.
How can I fix this?
2.) On the first page of chapters and "special chapters" (List of Contents...), the chapter title is located far too low on the page. This is the standard layout of LaTeX with documentstyle book I think.
However, the chapter title must start at the very top of the page! I.e. the same height as the normal text on the pages that follow.
I mean the chapter title, not the header.
I.e., if there is a chapter called
"Chapter 1
Dynamics of foobar under mechanical stress"
then that text has to start from the top the page, but right now it starts several centimeters below the top.
How can I fix this?
Have tried all kinds of things to no effect, I'd be very thankful for a solution!
Thanks.
A:
A try to answer
problem #1.
Even if you're using the headings pagestyle, or your custom pagestyle, the special pages (chapter beginnings and so on) are formatted with the plain pagestyle.
To avoid this, load the fancyhdr package (as mentioned in the previous answer) with
\usepackage{fancyhdr}
in your preamble. Then, (always in the preamble) define your custom pagestyle.
For normal pages (assuming you're not using twoside as an option of \documentclass[]{}):
\fancypagestyle{phdthesis}{%
\fancyhf %clear all headers and footers fields
\fancyhead[R]{\thepage} %prints the page number on the right side of the header
}
For special pages:
\fancypagestyle{plain}{%redefining plain pagestyle
\fancyhf %clear all headers and footers fields
\fancyhead[R]{\thepage} %prints the page number on the right side of the header
}
After doing this, you can set you page style declaring \pagestyle{phdthesis} right before \begin{document}.
For further details, refer to the fancyhdr package documentation.
Now trying to answer
problem #2
As a first attempt, you can use the titlesec package, using the option compact. In the preamble, type:
\usepackage[compact]{titlesec}
If you're not completely satisfied with this solution, you can specify the spacing above and below the titles with \titlespacing
\usepackage{titlesec}
\titleformat{ command }[ shape ]{ format }{ label }{ sep }{ before }[ after ]
\titlespacing{ command }{ left }{ beforesep }{ aftersep }[ right ]
With \titleformat you can define your own style for chapter titles, and then you can define the spacing with \titlespacing.
I don't know which style of titles you have to use, so it's better for you to have a look to the package documentation (you can recall package documentation typing texdoc NameOfThePackage in a terminal).
Please note that you need to define the chapter title format in order to specify its vertical spacing (page 5 of the documentation). As an example:
\usepackage{titlesec}
\titleformat{\chapter}[hang]{\huge}{\thechapter}{1em}{}
\titlespacing{\chapter}{0pt}{0pt}{1cm}
With these commands you have the chapter title with the number and the chapter name on the same line, a 0 pt space before the title, and a 1 cm space between the title and the follwing text.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Proofs for Relational Predicate Logic --Difficult Question!
I have been working on this problem for four and a half hours and I think I have simply missed something. I need the help of my peers here. The rules I am allowed to use are the Basic Inference rules (MP, MT, HS, Simp, Conj, DS, Add, Dil.), the Replacement Rules (DN, Comm, Assoc, Dup, DeM, BE, Contrap, CE, Exp, Dist.), CP, IP, and EI, UI, EG, UG.
Here is the problem:
(x)[(∃y)Rxy --> (y)Ryx]
Rab /∴ (x)(y)Rxy
My professor gave us the hint to use premise 1 two times.
I feel very silly because I know I have missed something simple (as usual) but I need a second pair of eyes. Please and thank you for your help.
A:
Your premisses are:
$1.\quad \forall x(\exists yRxy \to \forall yRyx)$
$2. \quad Rab$
Instantiate the first universal with $a$ (what else?) to get
$3. \quad \exists yRay \to \forall yRya$
Given a conditional, you always look to see if you can get the antecedent and use modus ponens. And yes! Of course you can. By existential generalization on $b$, (2) gives you the antecedent of (3), so we can use modus ponens to get to
$4. \quad \forall yRya$.
But now where? If we are going to get to a universally quantified conclusion, we know we are going to need to get it from some wff where the only parameters are arbitrary (not a fixed constant like $a$), so we can then generalize on them. So we are going to need something other than $4$. Hmmmm. Ok, let's use the purely general (1) and instantiate with a new parameter (arbitrary name, free variable, however you like to think of if) $v$. That's just brute force, but what else can we do? It is the only option. That gives us
$5. \quad \exists yRvy \to \forall yRyv$
But aha! Another conditional. Can we get the antecedent? But it is immediate that (4) gives us $Rva$ and hence $\exists yRvy$, so modus ponens again gives us
$6 \quad \forall yRyv$
And now the end is in sight.
But drat! We can't just quantify that as is (or rather, we can but then n we'd get $\forall x\forall yRyx$ which has things the wrong way around). To get the quantifiers the right way round, we have to take another step. Instantiate (6) with a new parameter $u$ to get
$7 \quad Ruv$.
But $u$ and $v$ were arbitrary, so you can universally quantify twice (do it in the right order!) and you get, lo and behold,
$8 \quad \forall x\forall yRxy$.
[Happily, this is what is sometimes called a "Just Do It" proof -- i.e. at every step you do the only sensible thing, and it all works out fine!]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to make directives work on elements I insert into the DOM later?
I need to conditionally apply ng-disabled to an element that is enclosed by a controller but does not exists at time of original compile. It is created later on by an AJAX callback and needs to be enabled/disabled based on certain conditions. I guess it needs a directive, but how do I go about it?
I need to use ng-disabled and no other solution as it is well handled by IE<11, which do not support pointer-events.
The real code is too complicated to be quoted here, but let me rephrase the problem.
A jQuery lib does something like:
$.get(url, function(){
$('<a class="btn"/>').appendTo(myDiv)
});
myDiv is within an angular controller. The <a/> element does not exist at time of compilation/directive linkage. Right after it gets appended, I should call some code to test and apply ng-disabled condition. Should it be a directive or a watch?
A:
You could create a directive with an ngIf (so that it's created just when ngIf condition equals true. You can enable this condition after the response returns). Then in the link function you could:
link: function( scope, element, attrs ){
element.removeAttr("name-of-the-directive");
element.attrs("ng-disabled", "{{myExpression}}");
$compile( element)(scope);
}
The line element.removeAttr("name-of-the-directive"); is necessary to avoid infinite compiling loop.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
If a cryptanalytic breakthrough is made, what process should be followed?
If a researcher manages to make a cryptanalytic breakthrough on a cryptographic algorithm or protocol that is in use, what should they do?
Has this ever happened before? What are the implications for release and how do those relying on such systems ensure they are not caught in a situation where the crypto-system on which they depend is trivially broken?
Specifically:
What details would you make available online?
Who would you release full details to?
How are affected parties notified?
A:
Well, first off, the question doesn't arise that often in practice. People do find cryptographical weaknesses; however, generally they are purely of theoretical interest, or if they could be used in a real attack, it may take quite a while before someone figures out how to use it. As an example of the second case, Ms. Wang announced an efficient way to create MD5 collisions; this is a severe break of the MD5 security properties, but it took people quite a while to figure out how to translate that into being able to obtain a bogus certificate (by asking for an innocuous one from a CA).
On the other hand, it does happen on occasion; one example that springs to mind is WEP and the key recovery attack.
Now, in my opinion, the ethical thing to try to do is to get people to stop using the broken protocol, and switch to something which doesn't have known weaknesses. However, in practice, that appears to be difficult. Once they have a system in place, quite a lot of people are loathe to update it. In addition, when cryptographical hardware is involved, sometimes the fix involves hardware modification, and so updating things would involve real money (rather than just a software update). One example of someone ignoring an announced attack would be the TJX credit card breach; this attack was done using the WEP key recovery attack that was announced 5+ years earlier.
So, what should we do? Well, I don't see any good options. Not publishing the result doesn't appear to work (we leave the weaknesses in place for the blackhats to find and exploit). Publishing the result does mean that some will update, but others won't bother. Publishing the fact that we have a result will generally mean that you won't be taken seriously (unless you're already a cryptographical Big Name), and the blackhats will be alerted that there is a weakness.
My personal feeling is that publishing the result is the "least worse".
[Hmmmm, we're supposed to avoid statements based on opinions; for a question about ethics like this, I don't see how I can avoid it]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use promises to wait for async API calls
I am creating an API that when GET, a series of calls to the News API are made, news article titles are extracted into a giant string, and that string is processed into an object to be delivered to a wordcloud on the front-end. So far, I've been able to use underscore's _.after and request-promise to make my app wait till all API calls have completed before calling processWordBank() which takes the giant string and cleans it up into an object. However, once processWordBank() is called, I don't understand where the flow of the program is. Ideally, processWordBank() returns obj to cloudObj in the router, so that the obj can be passed to res.json() and spit out as the response. I believe my use of _.after has put me in a weird situation, but it's the only way I've been able to get async calls to finish before proceeding to next desired action. Any suggestions?
(I've tried to leave out all unnecessary code but let me know if this is insufficient)
// includes...
var sourceString = ""
// router
export default ({ config }) => {
let news = Router()
news.get('/', function(req, res){
var cloudObj = getSources()
res.json({ cloudObj })
})
return news
}
// create list of words (sourceString) by pulling news data from various sources
function getSources() {
return getNewsApi()
}
// NEWS API
// GET top 10 news article titles from News API (news sources are determined by the values of newsApiSource array)
function getNewsApi() {
var finished = _.after(newsApiSource.length, processWordBank)
for(var i = 0; i < newsApiSource.length; i++) {
let options = {
uri: 'https://newsapi.org/v1/articles?source=' + newsApiSource[i] + '&sortBy=' + rank + '&apiKey=' + apiKey,
json: true
}
rp(options)
.then(function (res) {
let articles = res.articles // grab article objects from the response
let articleTitles = " " + _.pluck(articles, 'title') // extract title of each news article
sourceString += " " + articleTitles // add all titles to the word bank
finished() // this async task has finished
})
.catch(function (err) {
console.log(err)
})
}
}
// analyse word bank for patterns/trends
function processWordBank(){
var sourceArray = refineSource(sourceString)
sourceArray = combineCommon(sourceArray)
sourceArray = getWordFreq(sourceArray)
var obj = sortToObject(sourceArray[0], sourceArray[1])
console.log(obj)
return obj
}
A:
A big issue in your asynchronous flow is that you use a shared variable sourceString to handle the results. When you have multiple calls to getNewsApi() your result is not predictable and will not always be the same, because there is no predefined order in which the asynchronous calls are executed. Not only that, but you never reset it, so all subsequent calls will also include the results of the previous calls. Avoid modifying shared variables in asynchronous calls and instead use the results directly.
I've been able to use underscore's _.after and request-promise to make my app wait till all API calls have completed before calling processWordBank()
Although it would possible to use _.after, this can be done very nicely with promises, and since you're already using promises for your requests, it's just a matter of collecting the results from them. So because you want to wait until all API calls are completed you can use Promise.all which returns a promise that resolves with an array of the values of all the promises, once all of them are fulfilled. Let's have a look at a very simple example to see how Promise.all works:
// Promise.resolve() creates a promise that is fulfilled with the given value
const p1 = Promise.resolve('a promise')
// A promise that completes after 1 second
const p2 = new Promise(resolve => setTimeout(() => resolve('after 1 second'), 1000))
const p3 = Promise.resolve('hello').then(s => s + ' world')
const promises = [p1, p2, p3]
console.log('Waiting for all promises')
Promise.all(promises).then(results => console.log('All promises finished', results))
console.log('Promise.all does not block execution')
Now we can modify getNewsApi() to use Promise.all. The array of promises that is given to Promise.all are all the API request you're doing in your loop. This will be created with Array.protoype.map. And also instead of creating a string out of the array returned from _.pluck, we can just use the array directly, so you don't need to parse the string back to an array at the end.
function getNewsApi() {
// Each element is a request promise
const apiCalls = newsApiSource.map(function (source) {
let options = {
uri: 'https://newsapi.org/v1/articles?source=' + source + '&sortBy=' + rank + '&apiKey=' + apiKey,
json: true
}
return rp(options)
.then(function (res) {
let articles = res.articles
let articleTitles = _.pluck(articles, 'title')
// The promise is fulfilled with the articleTitles
return articleTitles
})
.catch(function (err) {
console.log(err)
})
})
// Return the promise that is fulfilled with all request values
return Promise.all(apiCalls)
}
Then we need to use the values in the router. We know that the promise returned from getNewsApi() fulfils with an array of all the requests, which by themselves return an array of articles. That is a 2d array, but presumably you would want a 1d array with all the articles for your processWordBank() function, so we can flatten it first.
export default ({ config }) => {
let news = Router()
new.get('/', (req, res) => {
const cloudObj = getSources()
cloudObj.then(function (apiResponses) {
// Flatten the array
// From: [['source1article1', 'source1article2'], ['source2article1'], ...]
// To: ['source1article1', 'source1article2', 'source2article1', ...]
const articles = [].concat.apply([], apiResponses)
// Pass the articles as parameter
const processedArticles = processWordBank(articles)
// Respond with the processed object
res.json({ processedArticles })
})
})
}
And finally processWordBank() needs to be changed to use an input parameter instead of using the shared variable. refineSource is no longer needed, because you're already passing an array (unless you do some other modifications in it).
function processWordBank(articles) {
let sourceArray = combineCommon(articles)
sourceArray = getWordFreq(sourceArray)
var obj = sortToObject(sourceArray[0], sourceArray[1])
console.log(obj)
return obj
}
As a bonus the router and getNewsApi() can be cleaned up with some ES6 features (without the comments from the snippets above):
export default ({ config }) => {
const news = Router()
new.get('/', (req, res) => {
getSources().then(apiResponses => {
const articles = [].concat(...apiResponses)
const processedArticles = processWordBank(articles)
res.json({ processedArticles })
})
})
}
function getNewsApi() {
const apiCalls = newsApiSource.map(source => {
const options = {
uri: `https://newsapi.org/v1/articles?source=${source}&sortBy=${rank}&apiKey=${apiKey}`,
json: true
}
return rp(options)
.then(res => _.pluck(res.articles, 'title'))
.catch(err => console.log(err))
})
return Promise.all(apiCalls)
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Multiple Array elements to Class Object
What is best practices to convert multiple array objects into class objects?
I have following use case,
class Queue {
private $id;
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
return $this;
}
private $name;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public static function getAll( ) {
// Guzzle HTTP Request returns JSON
$responseArray = json_decode ( $response->getBody() );
}
}
This is part of composer package. So now when using this Queue we can request multiple Queues from parent application. Now how do i convert this json response to Queue Object.
Also is it a good decision to declare getAll() method static?
A:
I assume the JSON response contains an associative array, with the keys being the property names you want in your object. If so, you can use the solution found in this answer. Basically, you just iterate through the array and use the key found in your array as the property name and the value as the property value:
$queue = new Queue();
foreach ($array as $key => $value)
{
$queue->$key = $value;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
django prefetch_related not working
I am trying to export all my database with a prefetch_related but I only get data from the main model.
My models:
class GvtCompoModel(models.Model):
gvtCompo= models.CharField(max_length=1000, blank=False, null=False)
...
class ActsIdsModel(models.Model):
year = models.IntegerField(max_length=4, blank=False, null=False)
...
class RespProposModel(models.Model):
respPropos=models.CharField(max_length=50, unique=True)
nationResp = models.ForeignKey('NationRespModel', blank=True, null=True, default=None)
nationalPartyResp = models.ForeignKey('NationalPartyRespModel', blank=True, null=True, default=None)
euGroupResp = models.ForeignKey('EUGroupRespModel', blank=True, null=True, default=None)
class ActsInfoModel(models.Model):
#id of the act
actId = models.OneToOneField(ActsIdsModel, primary_key=True)
respProposId1=models.ForeignKey('RespProposModel', related_name='respProposId1', blank=True, null=True, default=None)
respProposId2=models.ForeignKey('RespProposModel', related_name='respProposId2', blank=True, null=True, default=None)
respProposId3=models.ForeignKey('RespProposModel', related_name='respProposId3', blank=True, null=True, default=None)
gvtCompo= models.ManyToManyField(GvtCompoModel)
My view:
dumpDB=ActsInfoModel.objects.all().prefetch_related("actId", "respProposId1", "respProposId2", "respProposId3", "gvtCompo")
for act in dumpDB.values():
for field in act:
print "dumpDB field", field
When I display "field", I see the fields from ActsInfoModel ONLY, the starting model. Is it normal?
A:
It is normal, that you are seeing fields from ActsInfoModel only. You can access related models via dot notation, like:
acts = ActsInfoModel.objects.all().prefetch_related("actId", "respProposId1", "respProposId2", "respProposId3", "gvtCompo")
for act in acts:
print act.respProposId1.respPropos
Related models are already prefetched, so it won't produce any additional queries. FYI, quote from docs:
Returns a QuerySet that will automatically retrieve, in a single
batch, related objects for each of the specified lookups.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to sort String array by length using Arrays.sort()
I am trying to sort an array of strings according to their length using Arrays.sort(), but this sorts the strings lexicographically rather than by length. Here is my code:
S = "No one could disentangle correctly"
String W[] = S.split(" ");
Arrays.sort(W);
After sorting :
correctly
could
disentangle
no
one
but what I want is
no //length = 2
one //length = 3
could //length = 4 and likewise
correctly
disentangle
How can I get the above output? Please give answer for JDK 1.7 & JDK1.8.
A:
For java 8 and above
Arrays.sort(W, (a, b)->Integer.compare(a.length(), b.length()));
A more concise way is to use Comparator.comparingInt from Mano's answer here.
A:
Alternative to and slightly simpler than matt's version
Arrays.sort(W, Comparator.comparingInt(String::length));
A:
If you are using JDK 1.8 or above then you could use lambda expression like matt answer. But if you are using JDK 1.7 or earlier version try to write a custom Comparator like this:
String S = "No one could disentangle correctly";
String W[] = S.split(" ");
Arrays.sort(W, new java.util.Comparator<String>() {
@Override
public int compare(String s1, String s2) {
// TODO: Argument validation (nullity, length)
return s1.length() - s2.length();// comparision
}
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to share a bitmap on facebook as a photo in C#?
Ok so I am 100% new to sharing things from C# on facebook.
I need a sample code of how to share an Image on my facebook as a photo ?
Please do NOT answer with ( Google it, I dnt know, why ?, impossible, Facebook SDK )...
A:
Your question is a bit vague. When you say "in C#", you mean in a web, a window, or a service environment? Because the way Facebook does it is that there has to be some authentication in the process, and that is achieved via redirecting to Facebook for a user to login, and THEN send the photo for sharing. It's quite a process, not just a one-line code that does magic.
In any case, you have to do the following, and you have to figure out where you place it in your environment:
Create a Facebook app that corresponds to your app; Facebook will then give you an app code, and an app secret code.
Using the app code, redirect to Facebook to authenticate the user who wants the photo shared on their Facebook.
Receive back a code from Facebook.
Authorize your app by communicating to Facebook via a service call to allow photo sharing using the app code, the app secret code, and the code we got from step 2.
Receive back a token from Facebook that will be used from now on to upload photos.
NOW you can start uploading the photo via another service call to Facebook using that token.
Here's the code:
// Step 2: you have to research what TheScope will be from Facebook API that gives you access to photos
Response.Redirect(string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&scope={1}&redirect_uri={2}"), MyAppCode, TheScope, MyRedirectingURL);
// Step 3: this is on the `Page_Load` of MyRedirectingURL.
// AnotherRedirectingURL will be your final destination on your app
using (var wc = new WebClient())
{
string token = wc.DownloadString(string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&code={2}&redirect_uri={3}", MyAppCode, MyAppSecretCode, TheCode, AnotherRedirectingURL));
}
// Step 4: Use the token to start stream up or down
using (var wc = new WebClient())
{
Uri uploadUri = new Uri(string.Format("https://graph.facebook.com/{0}?{1}", PhotoUploadCommand, token));
// Find out what the PhotoUploadCommand is supposed to be from the Facebook API
// use wc and uploadUri to upload the photo
}
Bottom line, you have to do your research on this... it's not that straightforward. It's the sad truth that I had to go through to do what you're doing.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Find all the occurences of a string as a subsequence in a given string
Given strings A and B, find all the occurrences of B in A as a subsequence.
Example:
A = "mañana de la mañana"
B = "mañana"
Answer:
0 -> mañana de la mañana
1 -> mañana de la mañana
2 -> mañana de la mañana
...
Based on an algorithm I found here which counts the number of occurrences there are 16 of those. I need an algorithm that finds all such subsequences and reports their indices.
A:
The basic recursion be like
/**
* @param {[type]} iA current letter index in A
* @param {[type]} iB current letter index in B
*/
function rec (A, B, iA, iB, indices, solutions) {
if (iB === B.length) {
// copy the array if solution
solutions.push(indices.slice(0))
return
}
if (iA === A.length) {
return
}
const cb = B[iB]
// find all occurrences of cb in A
for (let i = iA; i < A.length; ++i) {
const ca = A[i]
if (ca === cb) {
indices[iB] = i
//match the next char
rec(A, B, i + 1, iB + 1, indices, solutions)
}
}
}
const A = "mañana de la mañana"
const B = "mañana"
const solutions = []
rec(A, B, 0, 0, [], solutions)
console.log(solutions.map(x => [
x.join(','), A.split('').map((c, i) => x.includes(i) ? c.toUpperCase() : c).join('')
]))
For the dynamic approach
build all sequences ending in m and store them to S_m
build all sequences ending in a from S_m and store them to S_{ma}
and so forth
const A = "mañana de la mañana"
const B = "mañana"
let S = A.split('').flatMap((a, i) => a === B[0] ? [[i]] : [])
// S is initially [ [0], [13] ]
B.split('').slice(1).forEach(b => {
const S_m = []
S.forEach(s => {
const iA = s[s.length - 1]
// get the last index from current sequence
// and look for next char in A starting from that index
for (let i = iA + 1; i < A.length; ++i) {
const ca = A[i]
if (ca === b) {
S_m.push(s.concat(i))
}
}
})
S = S_m
})
console.log(S.map(x => [
x.join(','), A.split('').map((c, i) => x.includes(i) ? c.toUpperCase() : c).join('')
]))
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Getting my own .apk file name
Possible Duplicate:
How to get the file *.apk location in Android device
How should I get the my own application name , including path which is installed on android phone.
Through code it should happen.
A:
what about getPackageResourcePath()
and
getPackageArchiveInfo(archiveFilePath, flags)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Error- Full Calendar won't POST
How can we make the following work so it will POST the events?
The events can be added to the calendar just fine, we just need to POST them to our API. Fiddle: https://jsfiddle.net/H_INGRAM/9oup1jfb/4/
This is my first time working with Ajax.
$(document).ready(function()
{
/*
date store today date.
d store today date.
m store current month.
y store current year.
*/
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var calendar = $('#calendar').fullCalendar(
{
header:
{
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultView: 'agendaWeek',
selectable: true,
selectHelper: true,
select: function(start, end, allDay)
{
var title = prompt('Event Title:');
if (title)
{
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
allDay: allDay
},
true // make the event "stick"
);
}
calendar.fullCalendar('unselect');
},
editable: true,
events: [
{
title: 'All Day Event',
start: new Date(y, m, 1)
},
{
title: 'Long Event',
start: new Date(y, m, d-5),
end: new Date(y, m, d-2)
},
{
id: 999,
title: 'Repeating Event',
start: new Date(y, m, d-3, 16, 0),
allDay: false
},
{
id: 999,
title: 'Repeating Event',
start: new Date(y, m, d+4, 16, 0),
allDay: false
},
{
title: 'Meeting',
start: new Date(y, m, d, 10, 30),
allDay: false
},
{
title: 'Lunch',
start: new Date(y, m, d, 12, 0),
end: new Date(y, m, d, 14, 0),
allDay: false
},
{
title: 'Birthday Party',
start: new Date(y, m, d+1, 19, 0),
end: new Date(y, m, d+1, 22, 30),
allDay: false
},
{
title: 'Click for Google',
start: new Date(y, m, 28),
end: new Date(y, m, 29),
url: 'http://google.com/'
}
]
});
});
$(document).ready(function () {
$('#fullcal').fullCalendar({
eventClick: function() {
alert('a day has been clicked!');
},
events: function (start, end, callback) {
$.ajax({
type: "POST", //WebMethods will not allow GET
url: "/events-truett-volunteership.html", //url of a webmethod - example below
data: "{'userID':'" + $('#<%= hidUserID.ClientID %>').val() + "'}", //this is what I use to pass who's calendar it is
//completely take out 'data:' line if you don't want to pass to webmethod - Important to also change webmethod to not accept any parameters
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (doc) {
var events = []; //javascript event object created here
var obj = $.parseJSON(doc.d); //.net returns json wrapped in "d"
$(obj.event).each(function () { //yours is obj.calevent
events.push({
title: $(this).attr('title'), //your calevent object has identical parameters 'title', 'start', ect, so this will work
start: $(this).attr('start'), // will be parsed into DateTime object
end: $(this).attr('end'),
id: $(this).attr('id')
});
});
callback(events);
}
});
}
});
});
A:
definitely you will have a submit handler or button click to sent data, so inside, simply get all client events then serialize and sent to server using ajax.
$('.submitEvent').click(function(){
var clientEvent = JSON.stringify($('#calendar').fullCalendar( 'clientEvents'));
$.ajax({ // ajax call starts
url: url
data: clientEvent,
dataType: 'json',
success: function(data)
{
// success handler
}
});
});
HTML
<input type="button" class="btn btn-primary submitEvent" value="SUBMIT"/>
thanks
|
{
"pile_set_name": "StackExchange"
}
|
Q:
transform Collection to Collection
I trying to implement functionally similar to CollectionUtils transform (Apache Commons Collections)
class CollectionUtils {
public static void transformerModifier(Collection<MyClass> myCollection) {
// How should I implement this method in order that
// output from the line 1 and line 2 will be the same ?
}
public static List<String> transform(Collection<MyClass> myCollection) {
List<String> strCollection = new LinkedList<>();
for (MyClass item : myCollection) {
strCollection.add(item.getName());
}
return strCollection;
}
}
class myClass {
private String name;
private int value;
myClass( String name, int value) {
this.name = name ;
this.value = value;
}
public String toString(){
return new String(name+ ":" + value ) ;
}
}
class MyClassCollection{
private List<myClass> list ;
myClassCollection(List<myClass> list){
this.list = list;
}
List<myClass> collection(){
return list.clone();
}
}
public class TestClass{
public static void main (String[] args) {
List<MyClass> list = new ArrayList<>();
list.add(new myClass("John", 12);
list.add(new myClass("Mike", 16);
list.add(new myClass("Eric", 13);
list.add(new myClass("Mark", 142);
list.add(new myClass("Alex", 112);
MyClassCollection myOjb = new MyClassCollection(list );
CollectionUtils.transformerModifier(myObj.collection() );
List<MyClass> myList = CollectionUtils.transform(myObj.collection());
System.out.println(Arrays.toString(myObj.collection().toArray)); // line 1
System.out.println(Arrays.toString(myList.toArray)); // line 2
}
}
output: [John,Mike,Eric,Mark,Alex] // output after line 1
output: [John,Mike,Eric,Mark,Alex] // should be output after line 2
My question is it possible to implement method transformerModifier in the way that it will change collection of the object myObj so that myObj.collection() return not the List<myClass> but the List of List<String> ( where string is the data from private String name data member of myClass ) ?
My guess is that the solution should be through anonymous class. However, I didn't understand yet how should I implement it.
A:
If you are using Java 8, you could make use of streams and map() to do something like this:
List<MyClass> myClassList = new ArrayList<>();
//add your items to myClassList here
List<String> names = myClassList.stream().map(MyClass::getName).collect(Collectors.toList());
//names will now consist of a List of all the names associated with
//each of the MyClass objects within myClassList in the same order
This solution makes use of Method Reference as well MyClass::getName. This calls the getName method on each object in the stream mapping it to its respective spot in the transformed stream using .map().
Next it uses .collect() to bring it back from a stream to a list using Collectors.toList().
If you are working with a lot of objects within myClassList, this process can be sped up using .parallelStream() instead of .stream(), but if you are not working with a large amount of data, you may see a reduction in performance with .parallelStream(). It all depends on how many objects you expect to be present within the List.
A:
public interface Converter<I, O> {
void tranformer(List list);
O retriever(I obj);
}
_
public static <I, O> void transform(Converter<I, O> converter, List inputList) {
Iterator<I> it = inputList.iterator();
List list = new LinkedList<>();
while (it.hasNext()) {
list.add(converter.retriever(it.next()));
}
converter.tranformer(list);
}
_
public static void main(String[] args) {
List<MyClass> list = new ArrayList<>();
list.add(new myClass("John", 12);
list.add(new myClass("Mike", 16);
list.add(new myClass("Eric", 13);
list.add(new myClass("Mark", 142);
list.add(new myClass("Alex", 112);
MyClassCollection myclasscollection = new MyClassCollection(list);
final List collectionList = myclasscollection.collection();
CollectionUtils.transform(new Converter<myClass, String>() {
@Override
public void tranformer(List list) {
employeeList.clear();
employeeList.addAll(list);
}
@Override
public String retriever(myClass obj) {
return obj.name; // make the data member public or add getter
}
}, collectionList);
collectionList.get(0).toString.toLowerCase();
}
This isn't fully what you need but I bet this isn't bad alternative. Please, notice that could output collection collectionList will be collection of objects ( not String ), however, you can access to methods of the String data type just to right like this collectionList.get(0).toString.toLowerCase(); Hope this help.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Allowing only numbers and one decimal
Guys and gals i have this piece of JavaScript code that only allows for numbers and one decimal period. The problem i'm having is that when i tab over to my textbox controls it highlights the value but i have press backspace to erase then enter a number. That is an extra keystroke that i want to prevent.
Props to the guy who created it found (http://www.coderanch.com/t/114528/HTML-CSS-JavaScript/decimal-point-restriction) and here is the code. I put this on keyUp event.
<script>
// Retrieve last key pressed. Works in IE and Netscape.
// Returns the numeric key code for the key pressed.
function getKey(e)
{
if (window.event)
return window.event.keyCode;
else if (e)
return e.which;
else
return null;
}
function restrictChars(e, obj)
{
var CHAR_AFTER_DP = 2; // number of decimal places
var validList = "0123456789."; // allowed characters in field
var key, keyChar;
key = getKey(e);
if (key == null) return true;
// control keys
// null, backspace, tab, carriage return, escape
if ( key==0 || key==8 || key==9 || key==13 || key==27 )
return true;
// get character
keyChar = String.fromCharCode(key);
// check valid characters
if (validList.indexOf(keyChar) != -1)
{
// check for existing decimal point
var dp = 0;
if( (dp = obj.value.indexOf( ".")) > -1)
{
if( keyChar == ".")
return false; // only one allowed
else
{
// room for more after decimal point?
if( obj.value.length - dp <= CHAR_AFTER_DP)
return true;
}
}
else return true;
}
// not a valid character
return false;
}
</script>
A:
<input type="text" class="decimal" value="" />
And in Js use this
$('.decimal').keyup(function(){
var val = $(this).val();
if(isNaN(val)){
val = val.replace(/[^0-9\.]/g,'');
if(val.split('.').length>2)
val =val.replace(/\.+$/,"");
}
$(this).val(val);
});
Check this fiddle: http://jsfiddle.net/2YW8g/
THis worked for me, i have taken this answer from "Nickalchemist" and take none of its credit.
A:
If you can't use an already stable and well-know library, you can try something like this:
document.write('<input id="inputField" onkeyup="run(this)" />');
function run(field) {
setTimeout(function() {
var regex = /\d*\.?\d?/g;
field.value = regex.exec(field.value);
}, 0);
}
I know it doesn't prevent the wrong char to appear, but it works.
PS: that setTimeout(..., 0) is a trick to execute the function after the value of the field has already been modified.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Rebase against the main branch
There are two branches. The main branch and branch with one feature. But the feature branch is in conflict with the main. People told me, that I should rebase the feature branch against the main.
Does it mean git rebase origin/main (and I am on the feature branch) or git rebase feature_branch (and I am on the main branch)?
It is important that during the git merge PRODUCTION there should be no conflict and it has to be solved by the command rebase. How?
A:
That would mean:
git fetch
git checkout feature
git rebase origin/main
You replay locally feature branch on top of the updated origin/main.
That gives you a chance to resolve any conflict locally, and then push the feature branch (a git push --force since its history has changed): make sure you are the only one working on that branch.
(as aduch mentions in the comments, if there were merges from origin/main to feature before, then a git rebase -p origin/main could be needed in theory. See "How to rebase only the commits after the latest merge?".
But that would also mean that, in that case, a git merge would be preferable to a git rebase, which have the added complexity of preserving past merges)
If you were not the only one working on that branch, then an alternative would be to merge origin/main to feature, solving any conflict there, before pushing feature (regular push).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
View with ViewPager not vertically scrollable in ScrollView
This feels like a no brainer but somehow I'm stuck. The view won't allow me to scroll it. It's as if the height of the fragment inflated in the ViewPager doesn't get calculated. Searching SO suggest I need to write my own ViewPager and override onMeasure(), but I can't believe I would have to go that far for something as simple as this.
Here is my layout, somewhat simplified for convenience. The ViewPager is populated with fragments taking up space way beyond the screen (vertically). Still, nothing on the screen is scrollable. Why is that?
<ScrollView
android:id="@+id/scroll_view"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/header_image_view"
android:layout_width="0dp"
android:layout_height="170dp"
app:layout_constraintTop_toTopOf="parent"/>
<TextView
android:id="@+id/title_text_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@id/header_image_view"/>
<Button
android:id="@+id/resume_training_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@id/title_text_view"/>
<android.support.design.widget.TabLayout
android:id="@+id/lesson_table_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
app:layout_constraintTop_toBottomOf="@id/resume_training_button">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="@+id/view_pager"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@id/lesson_table_layout">
</android.support.v4.view.ViewPager>
</android.support.constraint.ConstraintLayout>
</ScrollView>
Here's an example view. The Lorem ipsum text continues for long, and I'm expecting the whole screen to be scrollable, but it isn't.
Thanks in advance!
A:
I ended up rewriting it quite a bit. It didn't make sense to scroll above the TabLayout so I ended up using a CoordinatorLayout, according to
<CoordinatorLayout> <-- width/height = match_parent
<AppBarLayout> <-- width = match_parent, height = wrap_content
<ImageView/>
<TextView/>
<Button/>
<TabLayout/>
<AppBarLayout/>
<ViewPager/> <-- width/height = match_parent, app:layout_behavior="@string/appbar_scrolling_view_behavior"
<CoordinatorLayout/>
And each fragment inserted in the ViewPager is now wrapped in a NestedScrollView.
Thanks for the other answers. It'll probably help someone else!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Django ValidationError - how to use this properly?
Currently there is code that is doing (from with the form):
# the exception that gets raised if the form is not valid
raise forms.ValidationError("there was an error");
# here is where form.is_valid is called
form.is_valid() == False:
response['msg']=str(form.errors)
response['err']='row not updated.'
json = simplejson.dumps( response ) #this json will get returned from the view.
The problem with this, is that it is sending err message to the client as:
__all__"There was an error."
I want to remove the "all" garbage from the error template that is returned. How can I go about doing this? it seems to get added deep in django form code.
A:
It's because the error is not associated with any field in particular, but it's so called non-field error.
If you're only interested in non-field errors, just simply pass this to the response:
response['msg']=str(form.errors['__all__'])
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Sampling from matrix-variate normal distribution with singular covariances?
The matrix-variate normal distribution can be sampled indirectly by utilizing the Cholesky decomposition of two positive definite covariance matrices. However, if one or both of the covariance matrices are positive semi-definite and not positive definite (for example a block structure due to several pairs of perfectly correlated features and samples) the Cholesky decomposition fails, e.g.
$\Sigma_{A} =
\begin{bmatrix}
1 & 1 & 0 & 0\\
1 & 1 & 0 & 0\\
0 & 0 & 1 & 1\\
0 & 0 & 1 & 1
\end{bmatrix} \quad $or another example:$ \quad \Sigma_{B} =
\begin{bmatrix}
4 & 14 & 0 & 0\\
14 & 49 & 0 & 0\\
0 & 0 & 25 & 20\\
0 & 0 & 20 & 16
\end{bmatrix}$
Where $\Sigma_{B}$ is generated from $R$ (correlation matrix this time) = $\Sigma_{A} $
and $D$ (standard deviations) = $\begin{bmatrix}
2 & 0 & 0 & 0\\
0 & 7 & 0 & 0\\
0 & 0 & 5 & 0\\
0 & 0 & 0 & 4
\end{bmatrix}$ via $RDR$.
Is it possible to adapt the SVD based sampling technique for the multivariate normal case that overcomes this difficulty to the matrix-variate case?
This question is different from this post in that it is not clear if the lower diagonal produced by the SVD based sampling technique will suffice, since it is potentially quite different from one produced by a Cholesky decomposition that might be performed in this case by removing duplicate features and/or samples from the covariance matrices, performing the decomposition, and putting them back in. Also, the mentioned post is not concerned with positive semi-definite matrices.
A:
This sounds more like an issue with singular covariance matrices than with random matrices vs. random vectors. To handle the latter issue, do everything as a random vector, and then in the last step, reshape the vector into a matrix.
To handle the former problem:
If your desired covariance matrix is singular...
Let $\Sigma$ be a singular covariance matrix. Because it's singular, you can't do a Cholesky decomposition. But you can do a singular value decomposition.
[U, S, V] = svd(Sigma)
The singular value decomposition will construct matrices $U$, $S$, and $V$ such that $ \Sigma = U S V'$ and $S$ is diagonal. Furthermore, $U = V$ (because $\Sigma$ is symmetric). The number of positive singular values will be the rank of your covariance matrix.
You can then construct $n$ random vectors of length $k$ with.
X = randn(n, k) * sqrt(S) * U'
Let $\mathbf{z}$ be a standard multivariate normal vector. The basic idea is that:
\begin{align*}
\mathrm{Var}\left(US^{\frac{1}{2}} \mathbf{z} \right) &= US^{\frac{1}{2}} \mathrm{Var}\left( \mathbf{x} \right)S^{\frac{1}{2}}U' \\
&= U S U'\\
&= \Sigma
\end{align*}
Once you get a vector $US^{\frac{1}{2}}\mathbf{z}$ you can simply reshape it to the dimensions of your matrix. (Eg. a 6 by 1 vector could become a 3 by 2 matrix.)
The SVD on a symmetric matrix $C$ is a way to find another matrix $A$ such that $AA' = C$.
Optional step to be a more clever mathematician and more efficient coder
Find the singular values below some tolerance and remove them and their corresponding columns from $S$ and $U$ respectively. This way you can generate less than a $k$ dimensional random vector $\mathbf{z}$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Import Google Scholar publications into LinkedIn publications
I am looking for a program, browser extension or userscript that can import my Google Scholar publications into my LinkedIn publications. The import could be done either on request (e.g. click) or automatically whenever I start the browser / start the computer / etc. Ideally it would allow me to ignore some publications.
Any price, OS, license and browser is fine.
A:
not sure if this exactly solves your problem, but a lot of bio/med researchers seem to be using a chrome extension that allows you to import a publication from a DOI or pubmed ID: https://www.biostars.org/p/155880/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to save several dataframes in a R for loop
What I want to do is save one y dataframe for each file in the loop below.Right now, I only have the last one.
temp = list.files(pattern="*.csv")
myfiles = lapply(temp, read.csv)
for (file in myfiles){
y <- some code
}
y has 26 observations of 2 variables.
Sorry if this is not a working example. My data is too big even if taking samples. Any help is much appreciated.
A:
df <- do.call("rbind",lapply(list.files(pattern = "*.csv"),read.csv, header = TRUE))
Here is an example.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Should you omit information in variable names that are already specified by properties of that class?
For example when you have the class Room in which every room gets (or atleast should get) a different room number, do you ever allow yourself that you name that variables roomNumber instead of just room? Because you already know it's of the Room class, you could omit room in roomNumber, and just leave it number. For consistency sake I want to either include this information already specified by the class or omit it always.
Class Room {
private int roomNumber;
Room(int roomNumber) {
this.roomNumber = roomNumber;
}
}
or
Class Room {
private int number;
Room(int number) {
this.number = number;
}
}
I am thinking about how it would look if you would room.getRoomNumber() or room.getNumber(); and which would make more sense most of the times.
A:
If the Room has other numeric attributes, then make the variables' names more specific. If the room number is the only numeric attribute I think that room.getNumber() is enough.
A:
(Welcome to slowy's philosophical programming class)
getNumber() may sound okay. But how does it look, when the room has ten more attributes? How does it look for someone else? What if you would have a Type Employee with an employeeNumber and a Reservation with a reservationNumber? How does the business talk about it? How would the label of a web-gui be named for this property?
Keep in mind:
1) Most of the time, it's better to name methods and variables in a way, so that it's easier to understand. If you name something, try to name it, so you don't have to comment it. If the variable is longer than your 24" wide screen tft, well, something went horribly wrong hehe. In your case, I would have commented, that getNumber() will return the room number, just to make it perfectly clear. Not necessary otherwise.
2) Consistency: If the business is talking about a room number, name it room number. From the member variables, to methods, to table columns. If possible. It makes everything easier. This includes methods like "readRoomByRoomNumber()" instead of "readRoomByNumber()".
3) Naming of variables: Also declare "Room room = new Room()" and not "Room r = new Room()". So in the end: "room.getRoomNumber" is so much easier to read than "r.getNumber()" ;-)
Hope this helps,
regards,
slowy
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to properly load a picture into a UITableVIew
I'm trying to retrieve a user profile photo like this inside the cellForRowAtIndexPath method:
let profileImage = UIImage(data: NSData(contentsOfURL: NSURL(string:"http://website.com/something/somethingelse-pic/\(self.userArray[indexPath.row]).jpg")!)!)
I'm just wondering if there is a better and faster way to do this because this seem to load pretty slow and laggy.
Any help would be appreciated!!
A:
You can use async to load image from URL
let request: NSURLRequest = NSURLRequest(URL: imgURL)
let mainQueue = NSOperationQueue.mainQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: mainQueue, completionHandler: { (response, data, error) -> Void in
if error == nil {
// Convert the downloaded data in to a UIImage object
let image = UIImage(data: data)
// Store the image in to our cache
self.imageCache[urlString] = image
// Update the cell
dispatch_async(dispatch_get_main_queue(), {
if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) {
cellToUpdate.imageView?.image = image
}
})
}
else {
// println("Error: \(error.localizedDescription)")
}
})
Ref: http://jamesonquave.com/blog/developing-ios-apps-using-swift-part-5-async-image-loading-and-caching/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to program a clean microcontroller?
To be specific, i am interested if there is a way to buy a clean microcontroller (doesn't matter whether it is Atmel or Pic), program it and implement it into your circuit board, without any additional attachments.
PS: Here, additional attachments means something like Arduino, which, apart from microcontroller consists of many other electronics.
I just want to implement plain (without anything) microcontroller into my circuits.
A:
No, you can't run a microcontroller without anything else in the circuit. You almost can, but you really need a bypass cap across the power pins of the micro, physically close to the micro.
Other than that, some micros are capable of running without requiring anything else. Most have a negative-going reset line that needs to be held high for the micro to run. However, some have a built-in pullup resistor on that line, or can be optionally configured to enable a built-in pullup. The micro would also need a internal oscillator, but quite a few have that.
One example of a micro that just needs power, ground, and a bypass cap is the PIC 10F200. The MCLR pin can be configured so that it is a digital input, and the micro always runs when power is applied. This gives you one input pin, and three pins that can be either input or output, depending on what the firmware does.
There are a number of other PICs that can do this too. The limiting factor is you need one that can be configured to not do MCLR or with a internal pullup on MCLR. If you are willing to tie MCLR high, then quite a few more PICs fit your specification. Some will have multiple power and ground pins, so will require additional bypass caps. Not all have internal oscillators, but just about all the newer ones do.
If you explain what you want this micro to accomplish, we can probably suggest some models to look at.
A:
In general you will need something to connect a computer to the microcontroller for programming, usually some kind of programmer.
NXP makes a line of ARM microcontrollers that have a built in USB bootloader. If they are blank they automatically enter a bootloader mode that makes them show up as a mass storage device you drop the firmware onto. If you are going to use USB in your circuit this would mean you don't need anything extra. The parts I've used are LPC1343 and LPC1345, others have the same thing, but check before buying them.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to add "slow effect" to my slide menu when slide out from left?
$(document).ready(function() {
$('.slideout-menu-toggle').on('click', function(event) {
event.preventDefault();
// create menu variables
var slideoutMenu = $('.slideout-menu');
var slideoutMenuWidth = $('.slideout-menu').width();
// toggle open class
slideoutMenu.toggleClass("open");
// slide menu
if (slideoutMenu.hasClass("open")) {
slideoutMenu.animate({
left: "0px"
});
} else {
slideoutMenu.animate({
left: -slideoutMenuWidth
}, 250);
}
});
});
$(document).ready(function() {
$('.slideout-menu li').click(function() {
$(this).children('.mobile-sub-menu').toggle("slow");
});
});
.slideout-menu {
position: absolute;
top: 100px;
left: 0px;
width: 100%;
height: 100%;
background: rgb(248, 248, 248);
z-index: 1;
}
.slideout-menu .slideout-menu-toggle {
position: absolute;
top: 12px;
right: 10px;
display: inline-block;
padding: 6px 9px 5px;
font-family: Arial, sans-serif;
font-weight: bold;
line-height: 1;
background: #222;
color: #999;
text-decoration: none;
vertical-align: top;
}
.slideout-menu .slideout-menu-toggle:hover {
color: #fff;
}
.slideout-menu ul {
list-style: none;
font-weight: 300;
border-top: 1px solid #dddddd;
border-bottom: 1px solid #dddddd;
}
.slideout-menu ul li {
/*border-top: 1px solid #dddddd;*/
border-bottom: 1px solid #dddddd;
}
.slideout-menu ul li a {
position: relative;
display: block;
padding: 10px;
color: #999;
text-decoration: none;
}
.slideout-menu ul li a:hover {
background: #aaaaaa;
color: #fff;
}
.slideout-menu ul li a i {
position: absolute;
top: 15px;
right: 10px;
opacity: .5;
}
.slideout-menu .mobile-sub-menu { display:none; }
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button type="button" class="slideout-menu-toggle" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<div class="slideout-menu">
<ul>
<li><a href="#">MANUALS<i class="fa fa-arrow-right"></i></a>
<ul class="mobile-sub-menu">
<li><a href="#">1</a></li>
<li><a href="#">1</a></li>
<li><a href="#">1</a></li>
</ul>
</li>
<li><a href="#">NEWS</a></li>
<li><a href="#">SPARE PART</a></li>
<li><a href="#">Photo Gallery</a></li>
<li><a href="#">WHERE TO BUY</a></li>
<li><a href="#">SUPPORT</a></li>
<li><a href="#">EDIT BOOK</a></li>
</ul>
</div>
I find some information from internet and add "slow effect" to my mobile-sub-menu when toggle.
Now, I would like to also add this "slow effect" when I click on main items of slideout-menu (which is "MANUALS") when slide out from left.
How can I do that?
A:
Add the duration to the animate. This will add smooth animation effect.
slideoutMenu.animate({
left: "0px"
}, 1000); // 1 second
slideoutMenu.animate({
left: -slideoutMenuWidth
}, 1000); // 1 second
CODE
$(document).ready(function() {
$('.slideout-menu-toggle').on('click', function(event) {
event.preventDefault();
// create menu variables
var slideoutMenu = $('.slideout-menu');
var slideoutMenuWidth = $('.slideout-menu').width();
// toggle open class
slideoutMenu.toggleClass("open");
// slide menu
if (slideoutMenu.hasClass("open")) {
slideoutMenu.animate({
left: "0px"
}, 1000); // 1 second
} else {
slideoutMenu.animate({
left: -slideoutMenuWidth
}, 1000); // 1 second
}
});
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Disable Browser asking for "store credit Card information"
I'm developing some PCI pages and I keep finding the chrome browsers pops:
Do you want to store credit card information
This is not PCI compliant and I want to disable this so that no browser can pop up messages for storing credit card information.
A:
PCI compliance applies to what your site should do, not what the user can do within their own browser. Your site certainly shouldn't store a user's credit card information. However, you aren't any more responsible for your user allowing their browser to store their information than you would be if they, say, wrote the info on a post-it note and stuck it to their monitor. Browser features are browser features, not something you should (or often even can) try to manage.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to set partial transparency for GRASS layer?
I am trying to style layers in a GRASS monitor such that they are partially transparent. I'm guessing that there's a module for that (d.shadedmap seems close), but I haven't found it. I need a solution for partial transparency in both vector and raster layers (including rgb groups). It would be great if you could provide instructions for how to do this with the wxGUI AND the command line, but I'm finding that I can learn most of the command line methods from the wxGUI while using it.
A:
From the wxGui documentation:
A right mouse click on a layer or left clicking the button to the right of the layer opens a dropdown menu with options to remove or rename the layer (g.remove, g.rename), change its display properties (d.rast and d.vect options such as color, symbol, etc.), show its metadata (r.info, v.info) or attributes, if applicable.
In this menu you'll find the option Change opacity level.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why do we need Life Partner?
We all get into relationship. We at times move out of them when the needs (emotional,physical,mental,monetary,etc.) are not met.
We keep searching for that one life partner.
Why do we(human beings) need that one "Life partner"?
A:
The root cause is almost certainly procreation. Our relationship tendencies developed along with our biology. Humans tend to have one child at a time, and human children mature very slowly. This suggests that during most of human history, it would be advantageous for a female to keep a male with her, helping to provide food and protection for herself and her children. The strategy for the male is either to play along, or to breed so quickly as to outweigh the devastating effect of a long maturation without sufficient protection. Others species, many of which breed in greater numbers, have different mating habits.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Stored procedure taking long time to execute in SQL Server 2008
I have a stored procedure like this:
ALTER procedure [dbo].[delivary1]
@dedate nvarchar(100),
@carid nvarchar(100)
AS
BEGIN
declare @transid int
declare @status int
declare @count int,
@currentdate nvarchar(50)
select @currentdate = GETDATE()
SET NOCOUNT ON;
select @count = count(*)
from Transaction_tbl
where TBarcode = @carid
if @count=0
begin
return -1
end
else
begin
select @status = t1.Status
from Transaction_tbl t1
where t1.TBarcode = @carid
if @status = 4
begin
select @transid = t.transactID
from Transaction_tbl t
where t.TBarcode = @carid
update Transaction_tbl
set DelDate = '' + @currentdate + '', Status=5
where TBarcode = @carid
update KHanger_tbl
set Delivered = 1
where transactid = @transid
return 4
end
if @status = 5
begin
return 5
end
if @status=0
begin
return 0
end
if @status=1
begin
return 1
end
if @status = 2
begin
return 2
end
if @status = 3
begin
return 3
end
end
end
My database has more than 10 lack of records. Sometimes this takes a long time to execute..
Is there any way to write this stored procedure any simpler than this way?
Any help is very much appreciated.
Thanks in advance
Execution plan of my stored procedure
A:
Well, lets get serious.
Your end of the SP is redundant, jsut return @status.
The update is badly programming in using string for the date, but that is not relevant forspeed.
The speed is just in the Select. Interesting enough you miss an index which is shown in the screenshot you sent - which tells me you never bothered to even look at it before posting.
Please start considering indices and planning them. In your case you defintiely miss an index.
A:
You do not need to return the value for status, it just doent make any sense,
also add the missing index which suggests you will get around 93% improvement in your performance.
you can write this procedure with an OUTPUT parameter something like this...
ALTER procedure [dbo].[delivary1]
@dedate nvarchar(100),
@carid nvarchar(100),
@status INT OUTPUT
WITH RECOMPILE
AS
BEGIN
SET NOCOUNT ON;
DECLARE @transid int, @count int,@currentdate nvarchar(50)
SET @currentdate = GETDATE();
select @count = count(*) from Transaction_tbl where TBarcode = @carid
if (@count = 0)
begin
SET @status = -1;
end
else
begin
select @status = t1.[Status] from Transaction_tbl t1 where t1.TBarcode = @carid
if (@status = 4)
begin
select @transid = t.transactID
from Transaction_tbl t
where t.TBarcode = @carid
update Transaction_tbl
set DelDate = '' + @currentdate + ''
, [Status] = 5
where TBarcode = @carid
update KHanger_tbl
set Delivered=1
where transactid = @transid
end
end
END
How to add Missing Index
Go to your execution plan Right Click where it is showing Missing Index, and the click on the Missing Index Details
And it will Give you the Index Definition in a new query window that SQL Server thinks will help it to improve the performance of this query. All you need to do now is Just execute the Statement and it will create the index for you.
Index Definition
/*
Missing Index Details from SQLQuery1.sql - ALI-PC.AdventureWorks2008R2 (My Server\UserName (59))
The Query Processor estimates that implementing the following index could improve the query cost by 95.7414%.
*/
/*
USE [AdventureWorks2008R2]
GO
CREATE NONCLUSTERED INDEX [<Name of Missing Index, sysname,>]
ON [Sales].[SalesOrderHeader] ([TerritoryID],[ShipMethodID],[SubTotal],[Freight])
INCLUDE ([SalesOrderNumber],[CustomerID])
GO
*/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Overflow with numpy.exp()
I have to find 3 parameters with the leastsq function of scipy, as the procedure is described here in the part least-square fitting.
Here is my code:
def myFunc(t, Vs, Vi, k):
y = Vs * t - ((Vs - Vi) * (1 - np.exp(-k * t)) / k)
return y
x = np.array(temps, dtype='float64')
y = np.array(fluo, dtype='float64')
Vs, Vi, k = [2.8707e-11, 0.01241, 19765.39043]
def residuals(p, y, x):
Vs, Vi, k = p
err = y - myFunc(x, Vs, Vi, k)
return err
def peval(x, p):
return myFunc(x, p[0], p[1], p[2])
p0 = [2.8707e-11, 0.01241, 19765.39043]
plsq = leastsq(residuals, p0, args=(y, x))
print(plsq[0])
print(np.array([Vs, Vi, k]))
But I get the warning:
RuntimeWarning: overflow encountered in exp
I assume the number produced in exp is too big to fit in a float64. But I really need to make it fit. Is there any option to overcome this issue?
A:
Without being able to look at the input data (contained in your arrays temps and fluo) it's hard to say exactly, but I don't think this is something to worry about*. As scipy.optimize.leastsq works it optimizes a set of equations via the Jacobian and marches down to a local minimum. Along the way, it is possible that some of the values will overflow, these should be handled correctly with the optimizer. The warning comes from the first evaluation of the overflow, it may be happening more than once but it is only shown for the first time.
* Provided that you check your solution and verify that it is physical and gives a reasonable fit. The output from leastsq gives you a covariance of the parameter estimates which you can use to determine how well the fit progressed.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Error when I try to declare bag struct?
bag-implementation.h:
typedef struct node {
struct node *next;
char *element;
int repeats;
} Node;
typedef struct{
size_t size;
Node *head;
}Bag;
Line that errors in bag.c (which includes bag.h which includes bag-implementation.h):
Bag bag_union(Bag bag1, Bag bag2){
Bag union;
return bag1;
}
Error:
bag.c: In function 'bag_union':
bag.c:188:12: error: expected '{' before ';' token
bag.c:188:7: error: two or more data types in declaration specifiers
make: *** [bag.o] Error 1
If I try to compile without creating that bag, then it works fine. What is the issue?
A:
union is a reserved word in C, so you can't have a variable called like this. Simply rename it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Where can I camp when driving Highway 37 in British Columbia, Canada?
I plan on driving to Alaska via the Stewart-Cassiar Highway (Highway 37) in British Columbia, Canada. Where can I legally camp along or near the highway?
A:
The Milepost Guidebook has a list of points of interest along the Stewart-Cassiar Highway, which includes campgrounds.
J 2.5 Cassiar RV Park to west.
J 96.5 Meziadin Lake Provincial Park; camping.
J 97.5 Meziadin Junction. Junction with BC Highway 37A which leads west 38 miles to 5th Avenue, the main street of STEWART, BC (pop. 699). Road continues across international border (must stop at customs) to HYDER, AK (pop. 100); camping, general store. Dining and lodging in Stewart at the King Edward Hotel & Motel. Camping just outside Stewart at Bear River RV Park, turn at Mile 36.9 on Highway 37A. Attractions: Historic buildings in Stewart, Fish Creek bear viewing, Bear Glacier, Salmon Glacier.
J 155 Bell 2 Lodge; food, lodging, camping, propane, gas, diesel and pay phone.
J 227.1 Kinaskan Provincial Park; camping.
J 254.1 Mountain Shadow RV Park & Campground.
J 298.1 Dease Lake Lions Tanzilla River Campground; 15 natural wooded RV sites plus tent sites; picnic tablels, firepits.
J 310 Water’s Edge Campground.
J 374.9 JADE CITY (pop. 50); Cassiar Mountain Jade Store; jade cutting demonstrations, 5-room hotel, free overnight camping (no services).
J 397.2 Boya Lake Provincial Park: campground 1.2 miles east of highway.
I've traveled this highway with my family a couple of times, although it was quite a few years ago so I don't remember all of the details. I remember camping at Boya Lake and seeing loons and owls there, and I definitely recall camping at the RV park near Stewart - they have a tent section of the campground, and it's well worth staying a couple days so you can drive over the border to Hyder and see the bears at Fish Creek and travel up to Salmon Glacier.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
End-user feedback interview for an early stage prototype
Are the following questions appropriate to garner feedback from an early stage prototype? If not, what questions would be more appropriate:
For the individual:
For the business:
A:
The rating scale questions don't seem useful, unless you'll have an opportunity to follow up in more detail. Imagine that that respondents rated the app 1.5/5 on "features." How would you act on that information?
The "With regard to..." questions are very jargony. Imagine how a user would phrase these questions (e.g,. "Do you have suggestions about how to make the app look nicer?", "How could we make the app easier to use?")
A more fundamental issue with those questions is that you're asking the users to do design. Their job is to use the app and tell you what they experienced, not to decide how to act on it. Ask them for specifics about what they enjoyed, what was difficult, and what surprised them. Then use that information to decide how you can make the app a better fit for their needs.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Session variable are not handled properly
I have a AspxGriview on aspx page with id="grdManageFilterRoom". I am binding this grid by fetching some data from database. In case of any changes in Session["grdManageFilterRoom"] variable it is automatically reflected in Session["tmpGrdManageFilterRoom"] variable
I don't know why it's happening and I want to avoid this behavior. Any suggestion would be appreciated.
Session["grdManageFilterRoom"] = NameIdPairs<Int32>.GetRooms(companyCode, companyPersonID);
grdManageFilterRoom.DataSource = Session["grdManageFilterRoom"];
Session["tmpGrdManageFilterRoom"] = Session["grdManageFilterRoom"];
A:
This:
Session["tmpGrdManageFilterRoom"] = Session["grdManageFilterRoom"];
makes both session variables point to same object (I'm guessing that GetRooms method returns reference type), basically it doesn't matter if you are using Session["tmpGrdManageFilterRoom"] or Session["grdManageFilterRoom"] (because it is the same object).
If want to prevent this, then you need to clone those object(s).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to combine partition created by failed Ubuntu installation with that created by a subsequent installation
I tried installing Ubuntu 14.04 (dual boot with windows 7), but the installation failed. I tried again and was successful, but then realised that I still had the partition from the previous attempt. I have tried to use gparted to shrink this partition in order to expand that of the successful installation, but it won't allow me to do so (resize option greyed out). I also tried deleting all the items contained therein - they no longer show in nautilus, but the free space has not increased). How can I combine these two partitions?
A:
Run gparted from a live cd.
Delete the partition you do not want.
Resize the other partition to take up all of the available free
space.
Reinstall grub (unless you have /boot on the first disk partition)
Reboot
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SQL query to get the employee name and their manager name from the same table
Employee table
Employee_id Employee_name Manager_id
-------------------------------------
Emp00001 Ram Emp00005
Emp00002 Sharath Emp00003
Emp00003 Nivas Emp00005
Emp00004 Praveen Emp00002
Emp00005 Maharaj Emp00002
Output
Employee Name Manager Name
------------------------------
Ram Maharaj
Sharath Nivas
Nivas Maharaj
Praveen Sharath
Maharaj Sharath
In the employee table, there are three columns Employee_id, employee_name and manager_id. From the table, how to fetch the employee name and their manager name?
A:
You can self-join the table to get the manager's name from his ID:
SELECT e.employee_name, m.employee_name AS manager_name
FROM employee e
JOIN employee m on e.manager_id = m.employee_id
|
{
"pile_set_name": "StackExchange"
}
|
Q:
parse special json format with python
I want to get GPSLatitude and GPSLongitude value, but I can't use python position because the position is pretty random. I get the value by tag's value, how can I do that?
jsonFlickrApi({ "photo": { "id": "8566959299", "secret": "141af38562", "server": "8233", "farm": 9, "camera": "Apple iPhone 4S",
"exif": [
{ "tagspace": "JFIF", "tagspaceid": 0, "tag": "JFIFVersion", "label": "JFIFVersion",
"raw": { "_content": 1.01 } },
{ "tagspace": "JFIF", "tagspaceid": 0, "tag": "ResolutionUnit", "label": "Resolution Unit",
"raw": { "_content": "inches" } },
{ "tagspace": "JFIF", "tagspaceid": 0, "tag": "XResolution", "label": "X-Resolution",
"raw": { "_content": 72 },
"clean": { "_content": "72 dpi" } },
{ "tagspace": "JFIF", "tagspaceid": 0, "tag": "YResolution", "label": "Y-Resolution",
"raw": { "_content": 72 },
"clean": { "_content": "72 dpi" } },
{ "tagspace": "GPS", "tagspaceid": 0, "tag": "GPSLatitudeRef", "label": "GPS Latitude Ref",
"raw": { "_content": "North" } },
{ "tagspace": "GPS", "tagspaceid": 0, "tag": "GPSLatitude", "label": "GPS Latitude",
"raw": { "_content": "39 deg 56' 44.40\"" },
"clean": { "_content": "39 deg 56' 44.40\" N" } },
{ "tagspace": "GPS", "tagspaceid": 0, "tag": "GPSLongitudeRef", "label": "GPS Longitude Ref",
"raw": { "_content": "East" } },
{ "tagspace": "GPS", "tagspaceid": 0, "tag": "GPSLongitude", "label": "GPS Longitude",
"raw": { "_content": "116 deg 16' 10.20\"" },
"clean": { "_content": "116 deg 16' 10.20\" E" } },
] }, "stat": "ok" })
A:
With the exception of the last comma just before the closing bracket ], the entire object returned by the FlickrAPI is valid json.
Assuming that that comma is merely a copy-paste error (example evidence suggests this is the case), then the builtin json module still won't be usable as is. That's because even though a string like "116 deg 16' 10.20\" E" is valid json, python's json module will complain with a ValueError because the double quote " isn't sufficiently quoted:
>>> import json
>>> json.loads('{"a": "2"}')
{u'a': u'2'}
>>> json.loads('{"a": "2\""}')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/decoder.py", line 381, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting , delimiter: line 1 column 10 (char 9)
The solution is to add another escaping backslash:
>>> json.loads('{"a": "2\\""}')
{u'a': u'2"'}
For your full jsonFlickrApi response, you could add those extra backslashes with the re module:
>>> import re
>>> response = """jsonFlickrApi({ "photo": { "id": "8566959299", "secret": "141af38562", "server": "8233", "farm": 9, "camera": "Apple iPhone 4S",
... "exif": [
... { "tagspace": "JFIF", "tagspaceid": 0, "tag": "JFIFVersion", "label": "JFIFVersion",
... "raw": { "_content": 1.01 } },
... { "tagspace": "JFIF", "tagspaceid": 0, "tag": "ResolutionUnit", "label": "Resolution Unit",
... "raw": { "_content": "inches" } },
... { "tagspace": "JFIF", "tagspaceid": 0, "tag": "XResolution", "label": "X-Resolution",
... "raw": { "_content": 72 },
... "clean": { "_content": "72 dpi" } },
... { "tagspace": "JFIF", "tagspaceid": 0, "tag": "YResolution", "label": "Y-Resolution",
... "raw": { "_content": 72 },
... "clean": { "_content": "72 dpi" } },
... { "tagspace": "GPS", "tagspaceid": 0, "tag": "GPSLatitudeRef", "label": "GPS Latitude Ref",
... "raw": { "_content": "North" } },
... { "tagspace": "GPS", "tagspaceid": 0, "tag": "GPSLatitude", "label": "GPS Latitude",
... "raw": { "_content": "39 deg 56' 44.40\"" },
... "clean": { "_content": "39 deg 56' 44.40\" N" } },
... { "tagspace": "GPS", "tagspaceid": 0, "tag": "GPSLongitudeRef", "label": "GPS Longitude Ref",
... "raw": { "_content": "East" } },
... { "tagspace": "GPS", "tagspaceid": 0, "tag": "GPSLongitude", "label": "GPS Longitude",
... "raw": { "_content": "116 deg 16' 10.20\"" },
... "clean": { "_content": "116 deg 16' 10.20\" E" } }
... ] }, "stat": "ok" })"""
>>> quoted_resp = re.sub('deg ([^"]+)"', r'deg \1\\"', response[14:-1])
That quoted response can then be used in a call to json.loads and you can then easily access the required data in the newly generated dictionary structure:
>>> photodict = json.loads(quoted_resp)
>>> for meta in photodict['photo']['exif']:
... if meta["tagspace"] == "GPS" and meta["tag"] == "GPSLongitude":
... print(meta["clean"]["_content"])
...
116 deg 16' 10.20" E
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PDFBox 2.0.1 hangs rendering pdf page
I have an issue with PDFBox 2.0.1 as its not being able to render a PDF. I wouldn’t really care if PDFBox fails on a couple of files, but the thing is that the entire thread hangs and never returns for several minutes and the memory keeps building up and there doesn't seem to be an end in sight.
The problem seems to be with RenderImageWithDPI, this is how I call it:
PDFRenderer renderer = new PDFRenderer(document);
BufferedImage image = renderer.renderImageWithDPI(0, 96); //Gets stuck here
ImageIO.write(image, "PNG", new File(fileName));
The code gets stuck on that particular line and consumes CPU and memory. In netbeans I see this stack trace whenever I pause execution. Though I am not sure what is happening as I see PDFBox working but seems to have hit some sort of infinite loop.
The PDF in question can be downloaded from: https://drive.google.com/file/d/0B5zMlyl8rHwsY3Y1WjFVZlllajA/view?usp=sharing
Can someone help pls?
A:
Are you on java 8 or java 9? As explained here, start java with this option:
-Dsun.java2d.cmm=sun.java2d.cmm.kcms.KcmsServiceProvider
this is related to JDK8/9 having changed their color management system.
The file is still slow to render (20-30 seconds), because it is very complex.
(Btw rendering didn't hang. It just took very, very long, i.e. several minutes)
New since PDFBox 2.0.9: you mentioned you're creating thumbnails. You can now enable subsampling with PDFRender.setSubsamplingAllowed(true), this will reduce the memory used for images.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Modify the default Filter Field in a Telerik MVC ComboBox
When filtering a Telerik MVC ComboBox the control defaults to filtering from the values in the DataTextField. My ComboBox is bound to Data that has multiple fields that I'm using to display in a table with custom templates. I'm aware that there's no out of the box solution for filtering on multiple fields, but I'm wondering if there's a way to run the filter on a field where I've combined the multiple values.
Here's my comboBox:
@(Html.Kendo().ComboBoxFor(m => m.InputData.PublicationId)
.DataTextField("ID")
.DataValueField("ID")
.BindTo(Model.Publications)
.Filter(FilterType.Contains)
.TemplateId("pubListItemTemplate")
.HeaderTemplateId("pubListHeaderTemplate")
)
My data is structured as follows:
{ ID: "AJ", Description: "American Journal", Combined: "AJ American Journal" }, etc...]
The issue here is that if the user types in "AJ" the filter will find the example above, but if they type in "American" it will not; because the specified DataTextField is filtering on the ID.
I need for it to filter on the field called "Combined", but I still need to use the "ID" as the DataTextField so that the ID is only what is displayed in the combo after they've selected the item.
A:
This was provided to me on the Telerik forum, and I have confirmed that it solves my problem:
@(Html.Kendo().ComboBoxFor(m => m.InputData.PublicationId)
.DataTextField("ID")
.DataValueField("ID")
.Events(events => events.Filter("onPubFilter"))
.BindTo(Model.Publications)
.Filter(FilterType.Contains)
.TemplateId("pubListItemTemplate")
.HeaderTemplateId("pubListHeaderTemplate")
)
<script>
function onPubFilter(ev) {
var filterValue = ev.filter.value;
ev.preventDefault();
this.dataSource.filter({
filters: [
{
field: "Combined",
operator: "contains",
value: filterValue
}
]
});
}
</script>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Rspec use plain methods instead of be_ matchers?
In model I have own? method, can I use it as is in rspec instead of be_own? Without writing custom matchers?
A:
Yes. It is easy:
model.own?.should == true
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it appropriate to make major changes to somebody's question?
Somebody edited a recent question of mine. The change is substantial enough to change the intent of the question. I wanted to ask a different question than what somebody edited my question to say.
Here are some related facts of this matter.
It was done without my consent.
It was not done by a moderator. (And I would not want a moderator to make this change anyway.)
I don't agree with the change.
As best I can tell, my original question complies with the guidelines for what is appropriate to ask in this forum. (i.e. - It is about US legal theory and doctrines regarding free speech and harassment, and the guidelines specifically allow for discussions on "Legal terms and language, doctrines and theory".)
The answers posted after the change clearly don't address what I wanted to ask. Nor do they provide the information I wish.
Even if my post does not comply with guidelines for this forum, I think it sets a bad precedent for somebody else to change it. When somebody changes my post, they are basically saying what question I wanted to ask. They are putting words in my mouth, and trying to say what my own intentions are.
If a question does not comply with the guidelines, isn't it better to say how it does not comply, and allow the author to change it on their own? That allows the author to speak with their own words. Nobody can speak for me with the same authenticity that I can speak for myself.
A:
If a question does not comply with the guidelines, isn't it better to say how it does not comply, and allow the author to change it on their own? That allows the author to speak with their own words. Nobody can speak for me with the same authenticity that I can speak for myself.
Until users have earned the privilege, their edits are peer-reviewed before they are visible to other users. However, in this case, the user had earned that privilege and therefore no peer review occurred.
It was done without my consent.
It was not done by a moderator. (And I would not want a moderator to make this change anyway.)
I don't agree with the change.
From the help center article on editing (emphasis added):
Editing is important for keeping questions and answers clear, relevant, and up-to-date. If you are not comfortable with the idea of your contributions being collaboratively edited by other trusted users, this may not be the site for you.
I also want to correct your terminology in your next point:
As best I can tell, my original question complies with the guidelines for what is appropriate to ask in this forum. (i.e. - It is about US legal theory and doctrines regarding free speech and harassment, and the guidelines specifically allow for discussions on "Legal terms and language, doctrines and theory".)
The answers posted after the change clearly don't address what I wanted to ask. Nor do they provide the information I wish.
Stack Exchange is not a forum. It's a pet peeve for many but for me it goes to the heart of it - we ask and answer questions. Rants are discouraged. The question that you asked doesn't really lend itself to an answer without a significant measure of opinion.
However, nothing that has happened so far prevents you from asking your original question and noting that it was previously asked and edited. This might be the best option for you.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Comparing Strings in Excel Returns Unexpected False
I have two columns of mostly identical strings in excel (including identical case), one is pasted from a CSV file and one is from an XLS file.
If I run EXACT, or just =, or =if(A1=B1,true,false) I always get a negative (false) value. Is this an issue with formats? What can I do to achieve the expected result?
A:
Importing from CSV create sometime some formatting problem, for example extra spaces o other char!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Need simple way to compare a time string ONLY to the current dates time value
Say time string value is "7:00 AM" call it reminder time.
Now all I need to do is compare this time with the current dates time say its "9:00 AM" if reminder time is later than current time - return true else false. This is the format "h:mm a" for date formatters.
Simple right? It should be but I have burned too much time on this. I can get hour and minute values but when the AM/PM is considered it gets harder.
I just want to compare two time values and determine if the first is later or after the second one. The date is always today or current date so I only care about the time part of the date. Of course you have to convert to dates to do the comparison but current date is easy to get however date from "7:00 AM" string does not seem to work right in comparisons.
Anyone have a function to do this?
Thanks.
A:
the approach would be lets date the Date() object from your current time object so you will get
default date + your time = 2000-01-01 00:00:00 +your time (7.00 AM or 9.00 PM)
now we will get the current time from today only, in same format. (Only time)
it will be something like 3.56 PM
now again we will convert this 3.56 PM to Date() with default date as prev. so now we will have two date time object with same Date(2000-01-01) and respective times.
2000-01-01 7:00:00 => this will your 7.00 AM with default date
2000-01-01 15:56:00 => this will be current time with default date
now we will compare two date object.
Check the fiddle Fiddle
func CompareMyTimeInString(myTime:String)->Bool
{
// create the formatter - we are expecting only "hh:mm a" format
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
dateFormatter.locale = Locale.init(identifier: "en_GB")
// default date with my time
var dt_MyTime = dateFormatter.date(from: yourTime)!
// current time in same format as string "hh:mm a"
var currentTimString = dateFormatter.string(from: Date());
print("Current Time is - "+currentTimString);
// current time with default date.
var dt_CurrentTime = dateFormatter.date(from: currentTimString)!
// now just compare two date objects :)
return dt_MyTime > dt_CurrentTime;
}
// then call it like
var yourTime = "7.00 AM"
var isDue = CompareMyTimeInString(myTime:yourTime);
print(isDue);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Run a MySql function over results of join tables?
I have a query where it returns results based on a user inputted categories and products. See below.
SELECT * from locations_categories as lscs
INNER JOIN (SELECT * FROM categories WHERE categories.code IN (?)) as cat
ON lscs.category_id = cat.id
LEFT JOIN locations as loc
ON loc.id = lscs.location_id
LEFT JOIN product_locations as prodloc
ON prodloc.location_id = loc.id
INNER JOIN products as prod
on prod.id = prodloc.product_id
AND prod.id IN (?)
So for example if I was to put in category 1 with product 40 it would return all locations that were in category one and also had product 40.
The issue i'm having now is I have a Haversine(initialLat,InitialLong,FinalLat,finalLong) function. But I have no idea how to only run haversine on the results of the above query.
The initialLat and initialLong are user provided via postman and the finalLat and finalLong come from the results of the above joins.
How could I iterate through the results of the above joins and run them through the haversine function to determine how far the locations are from the user provided location?
EDIT:::
The top two numbers are the user inputted long and lat. The array is the results of the above query. The variables used for the long and lat of the user inputted data is $request->lon and $request->lat, these are what is provided in the haversine functions first two parameters, the second two parameters need to come from each of the two results of the array.
A:
The haversine formula should be put into the list of fields you want to select. Mysql will then run the equation and return the distance for you. For example:
SELECT ( 3959 * acos( cos( radians(?) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(?) ) + sin( radians(?) ) * sin( radians( lat ) ) ) ) AS distance FROM
will give the distance between the passed lat/lng and the locations in the DB.
The google store locator tutorial has good examples of this, https://developers.google.com/maps/solutions/store-locator/clothing-store-locator#finding-locations-with-mysql. (Note it is out of date, mysql_ should no longer be used)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Bitbucket: git push error: pack-objects died of signal 13
I tried to push my local repo to my origin branch on Bitbucket, and kept failing to push it. The error shows like below.
Counting objects: 2309, done.
Delta compression using up to 4 threads.
Connection to bitbucket.org closed by remote host.
fatal: The remote end hung up unexpectedly
Compressing objects: 100% (2295/2295), done.
error: pack-objects died of signal 13
error: failed to push some refs to ....
I already tried
git config http.postBuffer 5242880
and the result showed the same error. I also tried to change my setting from https to ssh, but still there was the same error.
I guess it may be because I push large files to my remote repository. I have not requested any updates for one month, and only done pull requests to update my local repo.
A:
Even though you already raised the http buffer size, this might still be related to the general size of your repo.
This thread mentions:
This repo is well in excess of our size limits. We don't store repositories of this size. We do not offer that as an option to any of our commercial plans, either. 1GiB/2GiB is a firm and inflexible limit for everyone.
As much as we want to offer larger repos, the performance of repos over 750MiB or so is too bad to tolerate. We hope you understand this limitation.
To check this I was asked to run:
git count-objects -Hv
(See "Find size of git repo")
That would explain why switching to ssh does not constitute a workaround in this case.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I add Error message if my me.combo box is not selected for the following code?
Add Error message if my me.combo box is not selected for the following code?
Private Sub Command1_Click()
Dim Recipient As String
Dim RecipientCC As String
Recipient = Me.Combo10.Column(2)
RecipientCC = Me.Combo10.Column(3)
Dim DateText As String
DateText = Format(Date - IIf(Weekday(Date) < 3, 1 + Weekday(Date), 1), "MM-DD-YYYY")
DoCmd.TransferText acExportDelim, , "watchdog", "G:\Common\Auto Finance\WatchDog\watchdog_" & [DateText] & ".csv", True
'send email
Dim olApp As Outlook.Application
Dim olMail As Outlook.MailItem
'get application
On Error Resume Next
Set olApp = GetObject(, "Outlook.Application")
If olApp Is Nothing Then Set olApp = New Outlook.Application
On Error GoTo 0
Set olMail = olApp.CreateItem(olMailItem)
With olMail
.Subject = "Indirect Auto Watchdog File"
.Recipients.Add [Recipient]
.CC = [RecipientCC]
.Attachments.Add "G:\Common\Auto Finance\WatchDog\watchdog_" & [DateText] & ".csv"
.Body = ""
.Display 'This will display the message for you to check and send yourself
'.Send ' This will send the message straight away
End With
MsgBox "Email Sent"
End Sub
A:
why not just add if...else loop?
Private Sub Command1_Click()
if me.combobox.value<>"" then
'do your task here
else
'display error message
end if
End Sub
|
{
"pile_set_name": "StackExchange"
}
|
Q:
"So many weapons and armor!" What is wrong with this sentence? And how would one fix it?
The sentence rings false in my head. Clearly this is because "weapons" is a countable noun, and "armor" is an uncountable noun. So one could fix this sentence by breaking it up into two clauses (e.g. "So many weapons, and so much armor!"), or by replacing a countable noun with an uncountable one (e.g. "So much armor and weaponry!"). But barring those two types of drastic changes, can anything be done to fix this sentence? Is there any way to properly modify a sentence with an uncountable noun and a countable noun appended together?
A:
How to join a countable noun with an uncountable one in one sentence, while expressing that one is "so many" while the other is "so much"?
The easiest solution would be to use the conjunction, and, to connect the two clauses together; however, the OP believes this would drastically change the sentiment of the original sentence. So I would like to suggest a few possible alternatives; my first is to use the adjective more, which can be used with both mass and count nouns.
We have more weapons and armour than we could dream of.
The forge chimneys billowed smoke day and night as the weapon smiths
forged more armour and weapons, fed by a steady stream of ore now
coming from the Midean Mountains and the peaks coldwards of Parmia.
Then they mustered full-size armies under consular commanders only to
have these just as thoroughly trounced by Spartacus, who with each
victory captured more weapons and armour to equip his forces
My second suggestion is to use quantities of or amount of. Quantity can be used for both singular and plural nouns but preferably for inanimate ones. The standard rule says to reserve amount for nouns that can be measured in bulk and are uncountable. But I found instances where this "rule" was not always followed.
Vast quantities of armour and weapons were also obtained, including
hundreds of two-handed and heavy swords...
...18,300 lb of silver in bullion and in coin, a large number of silver vases and
quantities of copper and iron, besides a vast amount of munitions,
armour and weapons
But while the central armouries produced a considerable amount of
weapons and armour
A tremendous amount of armour and weapons had been sent into the
region to strengthen the military that were doing battle against the
invading army.
However, on most occasions armies went into battle with large
quantities of traditional weapons and armour.
... where staggering quantities of armour and weapons were buried, probably
representing hundreds of warriors either killed or captured.
A:
There's always the simpler fix: since one is a countable and the other is not, qualify them separately:
So many weapons and so much armor!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Media wont display on recyclerview android studio
I have this problem now, I want to display all my images from the gallery to the thumbnail view in recyclerview in android studio. but the problems is that; there is no images display and i look for a possible solution yet nothing solves my problem.
Main activity:
package com.example.swiftpinx.Activity;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.CursorLoader;
import androidx.loader.content.Loader;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.example.swiftpinx.Adapters.GalleryImageAdapter;
import com.example.swiftpinx.R;
public class UploadProfilePhotoActivity extends AppCompatActivity implements View.OnClickListener,
LoaderManager.LoaderCallbacks<Cursor> {
/*
Set up's
*/
private static final String TAG = "UploadProfilePhotoActiv";
private final static int READ_EXTERNAL_STORAGE_CODE = 0;
private final static int MEDIASTORE_LOADER_ID = 0;
private GalleryImageAdapter gallery;
Intent intent;
/*
Pallete
*/
RecyclerView rvGalleryImages;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_profile_photo);
rvGalleryImages = (RecyclerView) findViewById(R.id.rvGalleryImages);
rvGalleryImages.setLayoutManager(new GridLayoutManager(this, 3));
gallery = new GalleryImageAdapter(this);
rvGalleryImages.setAdapter(gallery);
checkExternalReadStoragePermission();
}
@Override
public void onClick(View v) {
}
@NonNull
@Override
public Loader<Cursor> onCreateLoader(int id, @Nullable Bundle args) {
String[] projection = {
MediaStore.Files.FileColumns._ID,
MediaStore.Files.FileColumns.DATE_ADDED,
MediaStore.Files.FileColumns.MEDIA_TYPE
};
String selection = MediaStore.Files.FileColumns.MEDIA_TYPE + "="
+ MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE + " OR "
+ MediaStore.Files.FileColumns.MEDIA_TYPE + "="
+ MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO;
return new CursorLoader(
this,
MediaStore.Files.getContentUri("external"),
projection,
selection,
null,
MediaStore.Files.FileColumns.DATE_ADDED + " DESC"
);
}
@Override
public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor data) {
gallery.changeCursor(data);
}
@Override
public void onLoaderReset(@NonNull Loader<Cursor> loader) {
gallery.changeCursor(null);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch(requestCode) {
case READ_EXTERNAL_STORAGE_CODE:
if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Call cursor loader
Log.i(TAG, "onRequestPermissionsResult: permission granted.");
LoaderManager.getInstance(this).initLoader(MEDIASTORE_LOADER_ID, null, this);
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void checkExternalReadStoragePermission() {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
// Start cursor loader
Log.i(TAG, "checkExternalReadStoragePermission: Granted");
LoaderManager.getInstance(this).initLoader(MEDIASTORE_LOADER_ID, null, this);
} else {
if(shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)) {
// put reasons why we need to access storage
Toast.makeText(this, "App needs to view thumbnails.", Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[] { Manifest.permission.READ_EXTERNAL_STORAGE }, READ_EXTERNAL_STORAGE_CODE);
}
} else {
// Start cursor loader
Log.i(TAG, "checkExternalReadStoragePermission: Granted");
LoaderManager.getInstance(this).initLoader(MEDIASTORE_LOADER_ID, null, this);
}
}
}
RecyclerView class:
package com.example.swiftpinx.Adapters;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.swiftpinx.R;
public class GalleryImageAdapter extends RecyclerView.Adapter<GalleryImageAdapter.ViewHolder> {
private Cursor mediaCursor;
private Context context;
public GalleryImageAdapter(Context context) {
this.context = context;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.layout_gallery_upload_images, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Bitmap bitmap = getBitmapFromMediaStorage(position);
if(bitmap != null) {
holder.ivImage.setImageBitmap(bitmap);
}
}
@Override
public int getItemCount() {
return (mediaCursor == null) ? 0 : mediaCursor.getCount();
}
private Cursor swapCursor(Cursor cursor) {
if(mediaCursor == null) {
return null;
}
Cursor oldCursor = mediaCursor;
this.mediaCursor = cursor;
if(cursor != null) {
this.notifyDataSetChanged();
}
return oldCursor;
}
public void changeCursor(Cursor cursor) {
Cursor oldCursor = swapCursor(cursor);
if(oldCursor != null) {
oldCursor.close();
}
}
private Bitmap getBitmapFromMediaStorage(int position) {
int idIndex = mediaCursor.getColumnIndex(MediaStore.Files.FileColumns._ID);
int mediaTypeIndex = mediaCursor.getColumnIndex(MediaStore.Files.FileColumns.MEDIA_TYPE);
mediaCursor.moveToPosition(position);
switch(mediaCursor.getInt(mediaTypeIndex)) {
case MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE:
return MediaStore.Images.Thumbnails.getThumbnail(
this.context.getContentResolver(),
mediaCursor.getLong(idIndex),
MediaStore.Images.Thumbnails.MICRO_KIND,
null
);
case MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO:
return MediaStore.Video.Thumbnails.getThumbnail(
this.context.getContentResolver(),
mediaCursor.getLong(idIndex),
MediaStore.Video.Thumbnails.MICRO_KIND,
null
);
default:
return null;
}
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView ivImage;
public ViewHolder(@NonNull View itemView) {
super(itemView);
ivImage = (ImageView) itemView.findViewById(R.id.ivImage);
}
}
}
Layout image handler xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/ivImage"
android:layout_width="128dp"
android:layout_height="128dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Layout recyclerview xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorAccent"
tools:context=".Activity.UploadProfilePhotoActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="20dp"
android:orientation="vertical">
<androidx.cardview.widget.CardView
android:layout_width="200dp"
android:layout_height="200dp"
android:elevation="0dp"
app:cardBackgroundColor="@color/colorAccent"
android:layout_gravity="center_horizontal"
app:cardCornerRadius="100dp">
<ImageView
android:id="@+id/ivImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:srcCompat="@mipmap/ic_man_foreground"
tools:ignore="VectorDrawableCompat"
android:scaleType="centerCrop"/>
</androidx.cardview.widget.CardView>
<TextView
android:id="@+id/errorImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:layout_gravity="center_horizontal"
android:textColor="@color/colorDanger"
android:layout_marginTop="5dp"
android:layout_marginBottom="15dp"/>
<Button
android:id="@+id/btnUpload"
android:layout_width="250dp"
android:layout_height="45dp"
android:layout_gravity="center_horizontal"
android:background="@color/colorPrimaryDark"
android:textColor="@color/colorAccent"
android:text="upload" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" >
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rvGalleryImages"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
A:
So the solution here on the swapCursor method I set the condition if mediaCursor will be null then i return it to null, which is wrong.
so from this:
private Cursor swapCursor(Cursor cursor) {
if(mediaCursor == null) {
return null;
}
Cursor oldCursor = mediaCursor;
this.mediaCursor = cursor;
if(cursor != null) {
this.notifyDataSetChanged();
}
return oldCursor;
}
I change it to this:
private Cursor swapCursor(Cursor cursor) {
if(mediaCursor == cursor) {
return null;
}
Cursor oldCursor = mediaCursor;
this.mediaCursor = cursor;
if(cursor != null) {
this.notifyDataSetChanged();
}
return oldCursor;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
extra solution for \blank in xsim necessary?
I was wondering if/why it is necessary to have the extra solution for the \blank exercises, as the question already contains all the informations.
One reason for the question is, that it is extra work to copy and paste the stuff into the solution and this extra step could produce mistakes...
Another reason is, that I would love to have the possibility to use the solution/exercise in two different grades.
Grade 1: only the missing words (for an answer-only-sheet), now to be written as:
\begin{solution}
\blank{a}, \blank{b}
\end{solution}
Output:
Solution 1
a,b
Grade 2 (perhaps rather a variation of the exercise than the solution): the whole text with filled blanks, now to be written as:
\begin{solution}
\blank{a} and \blank{b} are the first letters of the alphabet.
\end{solution}
Output:
Solution 1
a and b are the first letters of the alphabet.
So that I can use the filled blanks in the whole text (grade 2) for the trainers workbook where the students have the empty blanks AND additionally use the condensed solution (grade 1) for a combined only-answer-sheet of all the solutions of all exercises at the end of the workbook.
Perhaps there could be a possibility of a \printcollection[print=exercise*]{foo} that prints the exercises, but with the blanks in the filled-style.
Here a MWE, showing the possible outcome, that compiles as long as the trainer boole is false.
\documentclass{article}
\usepackage{xsim}
\usepackage{etoolbox}
\newcounter{sections}
\newbool{trainer}
%\booltrue{trainer} % if trainer version, activate
\DeclareExerciseCollection{foo}
\DeclareExerciseCollection{ba}
\begin{document}
\section{A}
\collectexercises{foo}
\begin{exercise}
The \blank{a} is the first letter of the alphabet.
\end{exercise}
\begin{solution}
The \blank{a} is the first letter of the alphabet.
\end{solution}
\begin{exercise}
The \blank{b} is the second letter of the alphabet.
\end{exercise}
\begin{solution}
The \blank{b} is the second letter of the alphabet.
\end{solution}
\collectexercisesstop{foo}
\ifbool{trainer}
{\printcollection[print=solution]{foo}} %that is how it should look in the trainers workbook, but I don't want the whole text in the collection of all solutions
{\printcollection{foo}}
\section{B}
\collectexercises{ba}
\begin{exercise}
The \blank{z} is the last letter of the alphabet.
\end{exercise}
\begin{solution}
\blank{z}
\end{solution}
\collectexercisesstop{ba}
\ifbool{trainer}
{\printcollection[print=exercises*]{ba}} %that is what I would like for a kind of command that it prints the filled exercise like in section A if you put the whole text in the solution - perhaps it is rather a \printcollection*[print=exercises]
{\printcollection{ba}}
\section{Answersheet} % solution to number 3 shows how all solutions should look like in the answers-only-sheet
\setcounter{sections}{1}
\whileboolexpr
{ test {\ifnumless{\value{sections}}{\value{section}+1}} }
{
\printsolutions[section=\value{sections},headings-template=per-section]
\stepcounter{sections}
}
\end{document}
A:
If I understand the question correctly the following should be a way to go. The code below implements a blank/fill option (which will be added to the next release of xsim):
\documentclass{article}
\usepackage{xsim}
\ExplSyntaxOn
\bool_new:N \l__xsim_fill_blank_bool
\keys_define:nn {xsim/blank}
{
fill .bool_set:N = \l__xsim_fill_blank_bool ,
fill .initial:n = false
}
\cs_set_protected:Npn \xsim_blank:n #1
{
\box_clear:N \l__xsim_blank_box
\mode_if_math:TF
{ \hbox_set:Nn \l__xsim_blank_box { $ \m@th \mathpalette{}{#1} $ } }
{ \hbox_set:Nn \l__xsim_blank_box {#1} }
\bool_if:nTF
{ \xsim_if_inside_solution_p: || \l__xsim_fill_blank_bool }
{ \xsim_write_cloze_filled:n {#1} }
{
\bool_if:NTF \l__xsim_blank_width_bool
{ \__xsim_blank_skip:V \l__xsim_blank_dim }
{ \__xsim_blank_skip:n { \box_wd:N \l__xsim_blank_box } }
}
}
\ExplSyntaxOff
\begin{document}
\begin{exercise}
This is \blank{a} and \blank{b}.
\end{exercise}
\xsimsetup{blank/fill=true}
\printexercise{exercise}{1}
\end{document}
This should work with collections as well.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
history object with central Routes file
I have seen many examples over the net on how to use history object with React Router. However, I havent stumbled upon a case where the example shows a central routes file as shown below:
routes.js
const RouteList = () => (
<main>
<Switch>
<Route path="/" exact component={HomePage} />
<Route component={Error} />
</Switch>
</main>
);
export default RouteList;
App.js
render() {
return (
<div>
<Header />
<RouteList />
<Footer />
</div>
);
}
history.js
import { createBrowserHistory } from 'history';
export default createBrowserHistory();
Can someone shed some light how i can use history with my centralized routes? Or if there is another similar thread please let me know thank you so much.
A:
The custom history object need to be provided as a prop to the Router Provider component. In your case you can Specify a Router Provider in App.js or RouteList depending on whether Header and Footer also need Router props or not.
import browserHistory from './history.js';
...
render() {
return (
<Router history={browserHistory}>
<div>
<Header />
<RouteList />
<Footer />
</div>
</Router>
);
}
Also in your history.js file, import createBrowserHistory like
import createBrowserHistory from 'history/createBrowserHistory';
|
{
"pile_set_name": "StackExchange"
}
|
Q:
VS Code stage changes shortcut
What is the VS Code stage changes shortcut?
I mean is it possible to stage a selected file without clicking the plus button in the version control tab?
Maybe there is no shortcut an it is somehow possible to setup one?
A:
git.Stage and git.StageAll. They have no keybinding assigned by default. You can assign a custom one in your keyboard shortcut settings. CMDK+CMDS
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Limiting simultaneous authorisations for a user/consumer combination in OAuth 2.0
I'm building a service which will act as an OAuth 2.0 provider. I want to be able to limit the number of simultaneous authorisations that a user has for a specific consumer.
For example, each user of a consumer application should only be able to have, say, three simultaneous authorisations for that consumer, and thus only be able to use three clients simultaneously. When they try and authorise a fourth time it should prompt the user to remove the authorisation for an existing client before they can continue.
In my limited experience of OAuth, the token for a consumer application is always the same for a user and consumer combination, and so there's no way of revoking access to specific clients - only consumers.
Is there any provision in OAuth 2.0 for making a client identifier part of that combination, and thus part of the token? I'm specifically interested in OAuth 2.0 because of the User-Agent flow.
Or am I barking up the wrong tree entirely, and should I be looking at laying different system on top of OAuth?
A:
It seems like you could generate authorization-specific access tokens and include metadata about which client/authorization instance each refers to either on the token itself (encoded form of -1, etc.) or within your app (where each access token is unique). In fact, doing so could probably be considered an improvement over most provider implementations as individual clients could be recognized more easily (for abuse, etc.).
Tokens needn't take on any particular format, so you're free to overload them with as much or as little semantic information as you want and adapt your UI and UX to match.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
cells in collection view are not visible
Here is the code of the collection view:
- (void)viewDidLoad
{
[super viewDidLoad];
...
[_teamsCollection registerClass:[MWTeamCollectionCell class] forCellWithReuseIdentifier:@"Cell"];
}
#pragma mark data source and delegate methods of collection view
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 10;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"Cell";
MWTeamCollectionCell *cell = [_teamsCollection dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = (MWTeamCollectionCell*)[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.teamName.text = @"team name";
return cell;
}
When I debug the line return cell;, I get proper log, but I do not see the cells.
(gdb) po cell
<MWTeamCollectionCell: 0x72aff80; baseClass = UICollectionViewCell; frame = (0 0; 50 50); layer = <CALayer: 0x72b0090>>
(gdb) po cell
<MWTeamCollectionCell: 0x72b08e0; baseClass = UICollectionViewCell; frame = (67.5 0; 50 50); layer = <CALayer: 0x72b0970>>
(gdb) po cell
<MWTeamCollectionCell: 0x8aad380; baseClass = UICollectionViewCell; frame = (135 0; 50 50); layer = <CALayer: 0x8a72d20>>
A:
Don't need to register class like UITabeView, try this:
[yourCollection registerClass:[MWTeamCollectionCell class] forCellWithReuseIdentifier:@"CellName"];
And then
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
MWTeamCollectionCell *cell = [yourCollection dequeueReusableCellWithReuseIdentifier:@"CellName" forIndexPath:indexPath];
//Setting some thing here
return cell;
}
That's enough, remember MWTeamCollectionCell:UICollectionViewCell and customize in (id)init in MWTeamCollectionCell.m(init your teamName label)
And UICollectionView work only with iOS6, if you try iOS5,nothing display
|
{
"pile_set_name": "StackExchange"
}
|
Q:
atom-typescript - Why are these Typescript config options not recognised?
Why am I getting the errors shown in the screenshot below?
Atom says my tsconfig.json 'project file contains invalid options' for allowJs, buildOnSave, and compileOnSave.
But these settings should be allowed: https://github.com/TypeStrong/atom-typescript/blob/master/docs/tsconfig.md
A:
compileOnSave and buildOnSave do not go under CompilerOptions. Like so:
{
"compileOnSave": true,
"buildOnSave": false,
"compilerOptions": {
"module": "system",
"noImplicitAny": true,
"preserveConstEnums": true,
"removeComments": true,
"sourceMap": true,
"target": "es5"
},
"exclude": [
"node_modules",
"wwwroot/lib",
"typings/main",
"typings/main.d.ts"
]
}
It appears that allowJs is not supported but it will be soon. Here is a branch on GitHub, showing that they've already added it, they just haven't merged it yet.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Programmed device causes issues between computer and ISP
I'm using a Digispark, which is basically an attiny85 packaged with a few other things, as an ISP to program attiny85's. The Digispark is loaded with Littlewire and recognized as an USBtinySPI device on the computer. The target attiny85 to be programmed is stacked on top of the Digispark. All pins are connected 1-to-1, 2-to-2, etc. Programming is done from the Arduino IDE. The tutorial I followed can be found here...
http://digistump.com/wiki/digispark/tutorials/programming
The Digispark uses port 3 (USB-) and port 4 (USB+) to communicate with the computer. There are series resistors and shunt zener diodes on both USB connections. The Digispark schematic can be seen here...
https://s3.amazonaws.com/digispark/DigisparkSchematicFinal.pdf
I have been happily programming attiny85's with this setup, but recently hit a snag. On the target chip, if port 3 or 4 produce an output, the computer will no longer recognize the programmer. The computer will immediately connect to the programmer once the target chip is removed from it's socket. The target chip must be messing up communication between the computer and the programmer.
Curious if I was missing something, I compared my setup with Sparkfun's Tiny AVR Programmer. It seems like a more robust programmer. I thought it might have extra components or something, but it's almost identical. It uses an attiny84 with pins directly connected to an attiny85.
After lots of random guesses, I added series 2.2kohm resistors on ports 3 and 4 between the target attiny85 and the programmer. This solves the problem, but seems like a workaround.
Am I missing something? It seems like a programmer should be able to work without worrying about what the pins on the target device are doing. I assumed poorly, that was the purpose behind the RESET pin. Is there a better solution?
A:
With the Tiny AVR programmer, the D+ and D- lines are connected to there own input pins on the ATtiny84, see below:
This means that the pins from the target chip do not interfere with the function of these.
Whereas the digistump board has the outputs of the USB connected to pin 3 and 4, these pins are also connected to pin 3 and 4 of the target, as you know,
This means that as soon as you have your outputs active on 3 and 4 these interrupt the function of the USB lines.
By adding the 2.2k you are increasing the resistance before the Zener regulator circuit(thus decreasing the effect of the voltage from the target on these lines) and allowing the main tiny to have 'control' over the bus lines.
This is actual done on the SPI buses as well when a ISP is programming a target, while the target has other SPI chips on the bus, you add series resistors on the SPI bus, as seen below:
The R is usually between 1k - 4k7ohm. So you method is not a workaround, but normal procedure.
Another method to use instead of the resistor would be to cut the traces on the target board for pins 3 and 4, thus preventing it from going back onto the USB line. This is as I see no need to have control over the USB lines from the target.
Am I missing something? It seems like a programmer should be able to work without worrying about what the pins on the target device are doing. I assumed poorly, that was the purpose behind the RESET pin. Is there a better solution?
The programmer only toggles reset when programming, and once the target is flashed with your firmware that uses the same lines as USB and the PC then does not recognize the programmer because of this, the programmer won't be able to issue a RESET to the target, as
the PC can't issue it,
the programmer won't know to do that on its own.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Access $scope in other function
How can i access my $scope.key out side this function?
.controller('CatsCtrl', function($scope, $state, $http) {
var query = firebase.database().ref().orderByKey();
query.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
$scope.key = childSnapshot.key;
// I need this value
$scope.childData = childSnapshot.val();
$scope.data = $scope.childData.Category;
console.log($scope.key);
});
});
console.log($scope.key);
// returns undefined
var ref = firebase.database().ref($scope.key);
ref.once("value")
.then(function(snapshot) {
console.log(snapshot.val());
var name = snapshot.child("Category").val();
console.log(name);
});
})
I've tried it with $scope.apply but this did not work.
A:
Incase you need the childSnapshot.key in your second call, you should access it in the promise success callback:
query.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
$scope.childData = childSnapshot.val();
$scope.data = $scope.childData.Category;
var ref = firebase.database().ref(childSnapshot.key);
ref.once("value")
.then(function(snapshot) {
console.log(snapshot.val());
var name = snapshot.child("Category").val();
console.log(name);
});
});
});
Note that this will run for each iteration since the childSnaphot object is in the forEach callback
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Get all the nodes in the system
I've found node_load_multiple() which allows me to get all the nodes, but I need to specify some parameters, e.g. the type of node that I'd like to fetch.
I'd like to get all the nodes in the system without the criteria. How can I do that?
A:
The easiest way would be to use entity_load()
$nodes = entity_load('node');
If you don't provide the second argument ($ids) it will load up all entities of the given type:
$ids: An array of entity IDs, or FALSE to load all entities.
Just for the sake of completeness node_load_multiple() doesn't require the $conditions parameter so you could also grab all of the node ids from the database
$nids = db_query('SELECT nid FROM {node}')->fetchCol();
And then use $nids to load the nodes:
$nodes = node_load_multiple($nids);
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.