text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Sending Email Goes Back to Home Screen
So, I have this code to create an email Intent so my users can send support mail.
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
i.putExtra(Intent.EXTRA_SUBJECT, "The subject");
i.putExtra(Intent.EXTRA_TEXT, "The body");
startActivity(Intent.createChooser(i, "Send email"));
With that code, it opens up a dialog where I will choose which app will I use to send email. When I press the Back button, it returns to Home screen and also if I tap to somewhere else to close the dialog. And when I choose an app, Gmail for example, it opens up Gmail (I can now send email), but when I press send it also goes back to Home screen and also if I press the Back button.
Now, my question is how to return to the previous Activity press I press Back button and if I want to cancel sending mail? Also for the dialog when I want to cancel it.
A:
Try this for Email, filters way better:
Intent feedback = new Intent(Intent.ACTION_VIEW);
Uri data = Uri.parse("mailto:?subject=" + "SUBJECT"
+ "&body=" + "BODY" + "&to="
+ "EMAILADRESS");
feedback.setData(data);
startActivity(feedback);
This did a great job for me
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it necessary to follow same package name as it was for so file while using .so file in new Android project
I had created one project using native c++ support. In this project I am passing int value from activity to c++ code and native code returns whether this is prime number or not. This works perfectly, Now I want to create .so file to use in another project. I had google many post but not got answer how to get different .so file for all devices. So I had rename .apk file to .zip and extract it. After that I got one .so file.
Now I want to use this .so file in another project. therefore I had created new project with different name but package name is same. I had created one directory inside src/main and named it as jniLib in this lib I had copied my .so file directory. In my MainActivity I load so file as static {
System.loadLibrary("native-lib");
}
and call my native method private native String isPrimeNumber(int number);. Here everything is perfect. Now I can get result without having actual c++ code.
Now Again I created new project and follow above steps which was followed by creating second project, but difference is that now I had changed package name of my application. when I run application my application got crashed with error as
FATAL EXCEPTION: main
Process: com.app.androidkt.differentpackage, PID: 16970
java.lang.UnsatisfiedLinkError: No implementation found for java.lang.String com.app.androidkt.differentpackage.MainActivity.isPrimeNumber(int) (tried Java_com_app_androidkt_differentpackage_MainActivity_isPrimeNumber and Java_com_app_androidkt_differentpackage_MainActivity_isPrimeNumber__I)
at com.app.androidkt.differentpackage.MainActivity.isPrimeNumber(Native Method)
at com.app.androidkt.differentpackage.MainActivity.access$000(MainActivity.java:10)
at com.app.androidkt.differentpackage.MainActivity$1.onClick(MainActivity.java:38)
at android.view.View.performClick(View.java:5268)
at android.view.View$PerformClick.run(View.java:21550)
at android.os.Handler.handleCallback(Handler.java:822)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5811)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:681)
So my question are - 1) Is it necessary to use same package name to use .so file in our application as that of .so file.
2) How I can get different .so file directory - currently for time being I had extracted it from apk.
3) To use of .so file is to hide the native code only or there is any other purpose also there?
Thanks in advance.
A:
Your application package name may be anything, but the Java class that consumes native methods implemented in libnative-lib.so must be exactly the same as intended by the authors of this libnative-lib.so file.
The easiest workaround for your setup is to move your com.app.androidkt.differentpackage.MainActivity class to the com.app.androidkt.samplendk package. Android Studio will help you with this refactoring. Note that now you must declare the full path for MainActivity in your AndroidManifest.xml.
Alternatively, you can create a small com.app.androidkt.samplendk.MainActivity
class:
package com.app.androidkt.oldpackage;
public class MainActivity {
static {
System.loadLibrary("native-lib");
}
public native String isPrimeNumber(int number);
}
and add few lines to your MainActivity.java:
package com.app.androidkt.differentpackage;
public class MainActivity extends AppCompatActivity {
private com.app.androidkt.oldpackage.MainActivity pmSolver;
private String isPrimeNumber(int number) {
return pmSolver.isPrimeNumber(number);
}
…
}
If you don't know the exact package name used for this libnative-lib.so, you can find it by parsing its ELF headers: you will see an exported function named similar to Java_com_app_androidkt_ samplendk_MainActivity_isPrimeNumber.
Nitpicker's corner: it is possible to build a JNI library that will hide its designated class name(s), but it is hard to reliably prevent reverse engineering these names; it is also possible to build a JNI library that will seamlessly connect to different packages.
| {
"pile_set_name": "StackExchange"
} |
Q:
GCC, what does -W1 means
I have a legacy Makefile which is using the -W1 argument,
I didn't find any reference to that, I thought it might be a typo, that the '1' is supposed to be 'l'. However, it works...
So, can anyone explain why this line works ?
@$(CC) $(CFLAGS) -shared -W1,-soname,$(LIBNAME) -o $(OUTDIR)/$(LIBNAME) $(OBJS)
$(CC) is GCC, and the files compiled are C files.
When I tried to compile CPP files using this command, only then I get
cc1plus: error: unrecognized command line option "-W1,-soname...
A:
It looks like a typo, and that should be -Wl instead.
It's sometimes hard to differ between lower-case L (l) and the digit 1 in some fonts.
| {
"pile_set_name": "StackExchange"
} |
Q:
Create a primary link for the user edit page
What is the proper way to create a link under "Primary Links" that will take the logged in user to their own user edit page?
A:
I use the me aliases module to do this: it provides an alias, user/me, that you can add to menus and elsewhere. It also provides mappings for things like user/me/edit.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to split a string into list of characters and then concatenate by each character
Is it possible to split a Python string every nth character and then concatenate the subsequent characters?
For example, suppose I have a string containing 'Coffee'.
How can I split and get these variations:
C
Co
Cof
Coff
Coffe
Coffee
A:
Alternatively, in Python 3.2+, itertools.accumulate().
>>> list(itertools.accumulate("Coffee"))
['C', 'Co', 'Cof', 'Coff', 'Coffe', 'Coffee']
It's worth noting that this is probably not a particularly efficient method as it (internally) will use a lot of string concatenations, I provide it as a matter of interest, rather than being the best possible way.
A:
You can use a for loop:
>>> s = 'Coffee'
>>> for i in range(len(s)):
... print s[:i+1]
C
Co
Cof
Coff
Coffe
Coffee
or a list comprehension:
>>> [s[:i+1] for i in range(len(s))]
['C', 'Co', 'Cof', 'Coff', 'Coffe', 'Coffee']
| {
"pile_set_name": "StackExchange"
} |
Q:
Are innermost reductions perpetual in untyped $\lambda$-calculus?
Background
In the untyped lambda calculus, a term may contain many redexes, and
different choices about which one to reduce may produce wildly
different results (e.g. $(\lambda x.y)((\lambda x.xx)\lambda x.xx)$
which in one step ($\beta$-)reduces either to $y$ or to itself).
Different (sequences of) choices of where to reduce are called
reduction strategies. A term $t$ is said to be normalising if
there exists a reduction strategy which brings $t$ to normal form.
A term $t$ is said to be strongly normalising if every reduction
strategy brings $t$ to normal form. (I'm not worried about which, but
confluence guarantees there can't be more than one possibility.)
A reduction strategy is said to be normalising (and is in some sense
best possible) if whenever $t$ has a normal form, then that's where
we'll end up. The leftmost-outermost strategy is normalising.
At the other end of the spectrum, a reduction strategy is said to be
perpetual (and is in some sense worst possible) if whenever there
is an infinite reduction sequence from a term $t$, then the strategy
finds such a sequence - in other words, we could possibly fail to
normalise, then we will.
I know of the perpetual reduction strategies $F_\infty$ and $F_{bk}$
given respectively by:
\begin{array}{ll}
F_{bk}(C[(\lambda x.s)t]) = C[s[t/x]] & \text{if $t$ is strongly normalising}\\\\
F_{bk}(C[(\lambda x.s)t]) = C[(\lambda x.s)F_{bk}(t)] &\text{otherwise}
\end{array}
and
\begin{array}{ll}
F_\infty(C[(\lambda x.s)t]) = C[s[t/x]] &\text{if $x$ occurs in $s$, or if $t$ is on normal form}\\\\
F_\infty(C[(\lambda x.s)t]) = C[(\lambda x.s)F_\infty(t)] &\text{otherwise}
\end{array}
(In both cases, the indicated $\beta$-redex is the leftmost one in
the term $C[(\lambda x.s)t]$ - and on normal forms, reduction
strategies are necessarily identity.) The strategy $F_\infty$ is even
maximal - if it normalises a term, then it has used a longest
possible reduction sequence to do so. (See e.g. 13.4 in Barendregt's
book.)
Consider now the leftmost-innermost reduction strategy. Informally,
it will only reduce a $\beta$-redex which contains no other redexes.
More formally, it is defined by
\begin{array}{ll}
L(t) = t
&\text{if $t$ on normal form}\\\\
L(\lambda x.s) = \lambda x. L(s)
&\text{for $s$ not on normal form}\\\\
L(st) = L(s)t
&\text{for $s$ not on normal form}\\\\
L(st) = s L(t)
&\text{if $s$, but not $t$ is on normal form}\\\\
L((\lambda x. s)t) = s[t/x]
&\text{if $s$, $t$ both on normal form}
\end{array}
The natural intuition for leftmost-innermost reduction is that it will
do all the work - no redex can be lost, and so it ought to be
perpetual. Since the corresponding strategy is perpetual for
(untyped) combinatory logic (innermost reductions are perpetual for
all orthogonal TRWs), this doesn't feel like completely unfettered
blue-eyed optimism...
Is leftmost-innermost reduction a perpetual strategy for the untyped $\lambda$-calculus?
If the answer turns out to be 'no', a pointer to a counterexample
would be very interesting too.
A:
Over at cstheory.stackexchange.com, Radu GRIGore provided the following very nice counterexample:
Let $t$ be the term $t=(\lambda x. (\lambda y.z) (x x))$. Then the term $tt$ normalises under $L$ (in fact, $L(tt) = (\lambda x.z)t$), but it is clearly not strongly normalising, since $F_\infty(tt) = (\lambda y.z)(tt)$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Bootstrap progress bar issue in react component
Except Bootstrap Progress Bar All Bootstrap components working in React Component
class Demo extends Component {
render() {
return (
<div>
<div className="profile_record">
<h5 className="progress-label"><strong>PROFILE COMPLETENESS</strong></h5>
<div className="progress">
<div className="progress-bar" role="progressbar" style={{width: "25%"}} aria-valuenow="25" aria-valuemin="0" aria-valuemax="100">25%</div>
</div>
</div>
</div>
)
}
}
A:
Well it looks like its working as expected, you set tit to:
aria-valuenow="25"
Are you sure you included the proper bootstrap css and 'js' files?
class Demo extends React.Component {
render() {
return (
<div>
<div className="profile_record">
<h5 className="progress-label"><strong>PROFILE COMPLETENESS</strong></h5>
<div className="progress">
<div className="progress-bar" role="progressbar" style={{width: "25%"}} aria-valuenow="25" aria-valuemin="0" aria-valuemax="100">25%</div>
</div>
</div>
</div>
)
}
}
ReactDOM.render(<Demo />, document.getElementById('root'));
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
| {
"pile_set_name": "StackExchange"
} |
Q:
How should an activity query a service the activity didn't create/bind itself?
There's previous questions similar to this, for example here:
How to have Android Service communicate with Activity
But in the accepted answer to that question, the answer relies on the fact the activity is creating the service. However my question in that case is what to do if the activity does not create the service?
People will say follow the unaccepted answer in that same question (the one with lots of upvotes), which is for the service to broadcast to the Activity.
BUT my question is, what if the activity wants to know the current value of something in the service at the point the activity is created, rather than wait until the service broadcasts when that value changes?
A:
what if the activity wants to know the current value of something in the service at the point the activity is created, rather than wait until the service broadcasts when that value changes?
Use an event bus.
For example, greenrobot's EventBus supports sticky events. When your activity registers for the sticky event, it is immediately handed the last event of that type that had been sent out, plus future ones.
Or, Square's Otto supports the @Producer annotation. When your activity registers for an event supported by a @Producer, it immediately gets the value that the @Producer produces, plus future events.
| {
"pile_set_name": "StackExchange"
} |
Q:
Applescript - System events - Set default location for "open file" popup window
Im using system events to control a program that does not have a applescript library.
I am therefor using system events to control it.
I have gotten the program to open a pop up window for it Open File interface and I would like to get it to default to a certain location. Is this possible.
So Far I have :
tell application "App Name"
activate
end tell
tell application "System Events"
tell process "App Name"
tell menu bar 1
tell menu bar item "File"
tell menu "File"
tell menu item "Import"
tell menu "Import"
click menu item "XML..."
delay 4
end tell
end tell
end tell
end tell
end tell
end tell
end tell
The pop up window defaults to its own last visited location. I would like it to default to a given file path like /Users/userabc/Documents/abcd.XML
Thanks
A:
If you have the "posix path" of a location and the dialog box open, you can do the following. Note that the location can be a folder or a file path. If it's a file path then that file will be selected and you would then just have to "keystroke return" to close the dialog box and open that file. Good luck.
set theLocation to path to home folder
set posixLocation to POSIX path of theLocation
tell application "System Events"
keystroke "g" using {command down, shift down}
delay 0.5
keystroke posixLocation
delay 0.5
keystroke return
end tell
| {
"pile_set_name": "StackExchange"
} |
Q:
Best practice using Schema.SObjectType
Wants to know please,
1) Why using the Schema.SObjectType is better than using a SOQL?
2) If using the Schema.SObjectType inside a for loop is a bad Idea...
for example:
Id devRecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Development').getRecordTypeId();
I checked and saw that this doesn't affect the SOQL governor Limit - So I guess this is ok to use it inside a for loop?
A:
Calling Schema class again and again in loop is not a best practice. It doesn't consume soul limits but can cause
cpu time limit exceed exception
. So what I normally do is get schema describe result of any object outside loop and then inside loop get which ever value you want to get from that object.
Like for your case I will do
Map<String, Schema.RecordTypeInfo> recordtypeMap = Schema.SObjectType.Account.getRecordTypeInfosByName();
and in loop use recordtypeMap.get('recordtype').getRecordTypeId();
In this way I am calling schema class only once and using it at multiple places.
| {
"pile_set_name": "StackExchange"
} |
Q:
Counting the number of vowels in a string
I am writing a function that returns the number of vowels for a given string, here is the code:
int isVowel(string sequence)
{
int numberOfVowels = 0; //Initialize number of vowels to zero
string vowels = "aeiouAEIOU"; //Possible vowels, including capitals
for (int i = 0; i <= sequence.length(); i++)
{
for (int j = 0; j <= vowels.length(); j++)
{
if (sequence[i] == vowels[j])
{
numberOfVowels += 1;
}
}
}
return numberOfVowels;
}
This returns answers that are off by one. For example, input of "a" returns 2, input of "aa" returns 3, etc.
A:
i <= sequence.length()
<= is almost never correct in any for loop since C++ uses 0-based indices. Instead, you should do
i < sequence.length()
| {
"pile_set_name": "StackExchange"
} |
Q:
How to fill data in a JTable with database?
I want to display a JTable that display the data from a DataBase table as it is.
Up till now, I have used JTable that displays data from Object [ ][ ].
I know one way to display the data is to first convert the database table into Object [ ][ ] but Is there any other which is easy yet more powerful and flexible.
A:
I would recommend taking the following approach:
Create a Row class to represent a row read from your ResultSet. This could be a simple wrapper around an Object[].
Create a List<Row> collection, and subclass AbstractTableModel to be backed by this collection.
Use a SwingWorker to populate your List<Row> by reading from the underlying ResultSet on a background thread (i.e. within the doInBackground() method). Call SwingWorker's publish method to publish Rows back to the Event Dispatch thread (e.g. every 100 rows).
When the SwingWorker's process method is called with the latest chunk of Rows read, add them to your List<Row> and fire appropriate TableEvents to cause the display to update.
Also, use the ResultSetMetaData to determine the Class of each column within the TableModel definition. This will cause them to be rendered correctly (which won't be the case if you simply use a 2D Object[][] array).
The advantage of this approach is that the UI will not lock up when processing large ResultSets, and that the display will update incrementally as results are processed.
EDIT
Added example code below:
/**
* Simple wrapper around Object[] representing a row from the ResultSet.
*/
private class Row {
private final Object[] values;
public Row(Object[] values) {
this.values = values;
}
public int getSize() {
return values.length;
}
public Object getValue(int i) {
return values[i];
}
}
// TableModel implementation that will be populated by SwingWorker.
public class ResultSetTableModel extends AbstractTableModel {
private final ResultSetMetaData rsmd;
private final List<Row> rows;
public ResultSetTableModel(ResultSetMetaData rsmd) {
this.rsmd = rsmd;
this.rows = new ArrayList<Row>();
}
public int getRowCount() {
return rows.size();
}
public int getColumnCount() {
return rsmd.getColumnCount();
}
public Object getValue(int row, int column) {
return rows.get(row).getValue(column);
}
public String getColumnName(int col) {
return rsmd.getColumnName(col - 1); // ResultSetMetaData columns indexed from 1, not 0.
}
public Class<?> getColumnClass(int col) {
// TODO: Convert SQL type (int) returned by ResultSetMetaData.getType(col) to Java Class.
}
}
// SwingWorker implementation
new SwingWorker<Void, Row>() {
public Void doInBackground() {
// TODO: Process ResultSet and create Rows. Call publish() for every N rows created.
}
protected void process(Row... chunks) {
// TODO: Add to ResultSetTableModel List and fire TableEvent.
}
}.execute();
A:
Another powerful and flexible way to display database data in a JTable is to load your query's resulting data into a CachedRowSet, then connect it to the JTable with TableModel adapter.
Query ---> Database data ---> RowSet
RowSet <--> TableModel adapter <--> JTable
This book by George Reese gives the source code for his class RowSetModel to adapt a RowSet as a TableModel. Worked for me out-of-the-box. My only change was a better name for the class: RowSetTableModel.
A RowSet is a subinterface of ResultSet, added in Java 1.4. So a RowSet is a ResultSet.
A CachedRowSet implementation does the work for you, instead of you creating a Row class, a List of Row objects, and ResultSetMetaData as discussed in other answers on this page.
Sun/Oracle provides a reference implementation of CachedRowSet. Other vendors or JDBC drivers may provide implementations as well.
RowSet tutorial
A:
Depending on what you've done already and what you're willing to do, I've been using Netbeans with its Beans Binding support for a database-driven app very successfully. You bind your JTable to a database and it automatically builds the JPA queries.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to automatically extract borders from an old map?
I am new to QGIS and I am wondering whether there is a plugin which automatically recognises the borders on a map and converts the areas into polygons?
Edit: I am using QGIS 2.14.1. It is a picture of an old map with specific borders which don't exist anymore:
I was wondering whether there is a plugin that can automatically detect all of the borders so that each area is then transformed into a polygon.
So far I have only found plugins like autotrace and QGIS' advanced trace digitizing option where I would have to do it manually for each area.
A:
I suppose this is an old map that you scanned and want to convert the polygonal borders into vectors. What you're looking for are raster to vector converters. I'm not sure if QGIS has a plugin to do that, or maybe GRASS. There are some standalone tools to do that, have tried them in the past and even tried an ArcGIS feature, but all to a somewhat limited success. I can't give names cause I don't remember them, but I'm sure a quick Google search will yield some results. AutoDesk Raster Design, which works on top of AutoCAD can do that but in a semi-automatic way.
What all these tools do is detect black pixels on a white background and trace along the line. So a key deciding factor for a good result is to have a clean raster. In order for all these tools to work, you will have to remove speckles and unwanted lines from your image before running it through any of these tools. I can also see there are dashed lines in your map, and these can create issues because of the blanks. So it goes down to how much time you're willing to put on either cleaning the raster first, cleaning the vectors later on, or maybe a balance of both.
The nice thing about Raster Design is that it traces along the line automatically until it reaches an intersection, where it stops and waits for an input from the user on which way to go. It also has a setting that will allow it to jump the blanks, and you can control how big the blank has to be before the tracer stops. Of course, the downside is that it's not open source.
| {
"pile_set_name": "StackExchange"
} |
Q:
IE9 Support for HTML5 Canvas tag
I am trying to test out the canvas tag, I started with this code:
<html>
<canvas id="example" width="200" height="200">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
</html>
In IE8 I get the message:
This text is displayed if your browser does not support HTML5 Canvas.
I then installed IE9 but get the same error. Does IE9 support HTML5 canvas or not?
Edit
The problem was that I was missing the doctype tag
<!DOCTYPE html>
A:
IE9 does support canvas. Here is an exmaple.
If canvas does not work in your browser, press F12 (open developer tools), and make sure, that IE is not in compatibility mode.
A:
Extending the answer from gor, make sure that you have added following metadata.
<meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
This will force IE to use the latest mode as possible and users don't need to change the compatibility mode from developer tools.
A:
As far as I'm aware HTML 5 Canvas support is under development for IE9, unless it is already in the RC.. Perhaps not the best website to find out you could browse to html5test with IE9 to see if it supports certain HTML 5 tags or not. As an alternative you can browse to caniuse which should also give you alot of info regarding the HTML5 support of browsers .
| {
"pile_set_name": "StackExchange"
} |
Q:
Change R character encoding efficiently without memory copying (Encoding function)
I frequently import huge Excel files and use therefore the packages openxlsx and readxl (xlsx::read.xlsx[2] is too slow) on Windows 7.
Those packages do not have the option to specify an encoding so that I have to change the encoding marker of the string columns from "unknown" (native = Windows codepage 1252) to UTF-8 which is the standard encoding of Excel's XLSX files.
What is the most efficient way to change R's encoding marker of "strings" (character vectors) without causing the original strings to be copied?
R has Encoding() and enc2utf8 to change the encoding marker and I use it only to fix the wrong encoding marker without changing the original bytes of the strings.
Even though Encoding() should not change the bytes of the string itself (= not convert the string like iconv) the string is copied once or more:
> x <- "fa\xE7ile"
> x
[1] "fa\xe7ile"
> charToRaw(x)
[1] 66 61 e7 69 6c 65
> tracemem(x)
[1] "<0x47030f8>"
> Encoding(x)
[1] "unknown"
> Encoding(x) <- "latin1"
tracemem[0x47030f8 -> 0x4463118]:
tracemem[0x4463118 -> 0x44630e8]: Encoding<-
> x
[1] "façile"
> charToRaw(x)
[1] 66 61 e7 69 6c 65
> enc2utf8(x)
tracemem[0x44630e8 -> 0x4706e38]:
[1] "façile"
> charToRaw(x)
[1] 66 61 e7 69 6c 65
PS: The help of enc2utf8 claims "They are primitive functions, designed to do minimal copying." but still does copy the string once.
A:
You can avoid one of the copies by calling the assignment version of the function directly,
`Encoding<-`(x,"latin1")
My speculation is that the remaining copy is unavoidable, as it appears that all character (the more common name for strings in R) objects are created with their NAMED attribute set to 2. You can check this via,
x <- "a"
.Internal(inspect(x))
in a clean R session. (And not in RStudio, I believe RStudio artificially messes with the NAMED attribute in ways that may be misleading.) If I were to really speculate, I'd guess that this is somehow related to R's use of a global hash table for all character vectors, which allows for lots of performance improvements for character vectors generally, but maybe a consequence is some extra copying in some circumstances.
Further reading on these sorts of copying issues can be found here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Problems baking my blog using JBake 2.5.1
When I am trying to "bake" my JBake project using jbake -b I keep getting the following error.
➜ git:(master) ✗ jbake -b
JBake v2.5.1 (2017-01-31 23:24:52PM) [http://jbake.org]
18:28:33.646 WARN c.o.o.c.d.r.ODatabaseRecordAbstract$2 - Current implementation of storage does not support sbtree collections
An unexpected error occurred: Cannot create database
Is there a way to tell JBake to be a bit more verbose? Is anyone familiar with that kind of error?
I installed JBake using sdkman.
A:
I'm assuming your using Java 9, if so then you're experiencing this issue which is due to the version of OrientDB bundled with JBake 2.5.1, should be fixed with JBake 2.6.0 which bundles a later version and is due out soon.
| {
"pile_set_name": "StackExchange"
} |
Q:
javascript - can't access property of an object using its key?
in Google Earth Editor, we've created an object using the reduceRegion() function:
var meanValue2015 = ndvi2015.reduceRegion({
reducer: ee.Reducer.mean(),
geometry: justEC15.geometry(),
crs: 'EPSG:4326',
scale: 30,
});
My issue is that meanValue2015 appears to be an object - I input
print(meanValue2015);
print(typeof(meanValue2015));
print(Object.keys(meanValue2015));
and get "Object (1 property) - NDVI: 0.3177...", "Object", and then "[ ]" respectively? And then
print(meanValue2015.NDVI);
print(meanValue2015['NDVI']);
is undefined? Is there something obvious I'm doing wrong here?
A:
meanValue2015 is a Earth Engine object: a Dictionary. So..
var meanValue2015 = ndvi2015.reduceRegion({
reducer: ee.Reducer.mean(),
geometry: justEC15.geometry(),
crs: 'EPSG:4326',
scale: 30,
});
var realValue = ee.Number(meanValue2015.get("ndvi"));
print("real value (object):", realValue)
// realValue is a EE object, so you have to use it as is..
// this would be easy, but it is wrong..
var newValueWrong = realValue + 1
// this is the right way..
var newValueRight = realValue.add(ee.Number(1))
print("wrong:", newValueWrong)
print("right:", newValueRight)
// there is another way, but it is not recommendable because you'd
// be wasting EE computing capacity (Google's gift! don't waste it)
var localValue = realValue.getInfo() + 1
print("value in the local scope (try to avoid)", localValue)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to find $m$ if $(x^2 + x + 1) | ((x + 1)^m - x^m - 1)$
How to find $m$ if $(x^2 + x + 1) | ((x + 1)^m - x^m - 1)$
I tryed to use eyler theorem, but nothing happens. Sorry for bad english.
A:
If $w=\frac{-1+\sqrt{-3}}{2}$ then $w,\overline w$ are the roots of $x^2+x+1=0$.
Also, $(1+w)^2=w$ and $(1+\overline w)^2=\overline w$, and thus $(1+w)^6=(1+\overline w)^6=1$.
You will get that $x^2+x+1$ is a factor of $(x+1)^m-x^m-1$ exactly when $m\equiv \pm 1\pmod{6}$.
This is because $(1+w)^m-w^m-1=(1+w)^m-(1+w)^{2m}-1$ so $z=(1+w)^{m}$ must be a root of $z-z^2-1$ - that is, $z=\frac{1\pm \sqrt{-3}}{2}=1+w,1+\overline w$.
More directly, since $1+x\equiv -x^2\pmod {x^2+x+1}$, we have:
$$(1+x)^m-x^m-1\equiv (-1)^mx^{2m}-x^m-1\pmod{x^2+x+1}$$
Since $x^3\equiv 1\pmod{x^2+x+1}$, we get:
$$(-1)^mx^{2m} - x^m - 1\equiv \begin{cases}(-1)^m-2&m\equiv 0\pmod{3}\\
(-1)^mx^2-x-1&m\equiv 1\pmod{3}\\
(-1)^mx-x^2-1&m\equiv 2\pmod{3}
\end{cases}$$
We see that the divisibility condition is be true, if and only if $m$ is odd and not divisible by $3$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Memory Mapped files and atomic writes of single blocks
If I read and write a single file using normal IO APIs, writes are guaranteed to be atomic on a per-block basis. That is, if my write only modifies a single block, the operating system guarantees that either the whole block is written, or nothing at all.
How do I achieve the same effect on a memory mapped file?
Memory mapped files are simply byte arrays, so if I modify the byte array, the operating system has no way of knowing when I consider a write "done", so it might (even if that is unlikely) swap out the memory just in the middle of my block-writing operation, and in effect I write half a block.
I'd need some sort of a "enter/leave critical section", or some method of "pinning" the page of a file into memory while I'm writing to it. Does something like that exist? If so, is that portable across common POSIX systems & Windows?
A:
The technique of keeping a journal seems to be the only way. I don't know how this works with multiple apps writing to the same file. The Cassandra project has a good article on how to get performance with a journal. The key thing is to make sure of, is that the journal only records positive actions (my first approach was to write the pre-image of each write to the journal allowing you to rollback, but it got overly complicated).
So basically your memory-mapped file has a transactionId in the header, if your header fits into one block you know it won't get corrupted, though many people seem to write it twice with a checksum: [header[cksum]] [header[cksum]]. If the first checksum fails, use the second.
The journal looks something like this:
[beginTxn[txnid]] [offset, length, data...] [commitTxn[txnid]]
You just keep appending journal records until it gets too big, then roll it over at some point. When you startup your program you check to see if the transaction id for the file is at the last transaction id of the journal -- if not you play back all the transactions in the journal to sync up.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is there a 25 character tag limit?
So I tried to post a question and there was no tag, so I tried to make it myself.
This is the question.
And this is the tag I tried to create,
League-of-extraordinary-gentlemen
Is there a reason for the character length on a tag?
A:
There are various reasons to have character limits for tags, and more than a few downsides.
Upsides
Aesthetics
This is a major reason. Let’s say you raised the tag character limit to 50 characters.
Then you could have tags like blahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh . As you can see, this already takes up nearly half a line. So while four 25-character tag names (a rather uncommon use-case) can more-or-less fit comfortably on a line, two 50-character tag names (probably a more common situation) take up the same space. Many lines of tags can look pretty ugly. And anything over about 100 characters is simply right out the window, since it would have to be split over two lines.
Readability
There is also a problem with readability. Tag text is in a smaller font, and displayed on a gray background, which makes it a lot harder to read even for short tags. Tags that are fifty characters long could be atrocious.
On a related note, this might also increase the likelihood of spelling errors in tag names, as well as decreasing the likelihood that anyone would spot them.
Specificity
On programming sites, as hinted at in this post, long tags often tend to be the sorts of things that can (or even should) be broken into smaller pieces, which is to say, one that is too specific. For example, instead of excel-spreadsheets-in-windows-10, try using excel, spreadsheets, windows-10 (this is not actually SO’s usage guidance, but rather an example).
Such concerns are basically why there is a 25-character tag limit.
Downsides
In fairness, though, there are some serious downsides as well, which bear consideration. Some are also more specific to our site and a few others, rather than SO and the other programming sites, where this size constraint likely originated.
Naturality
In many cases, we simply need longer tags, since they arise naturally from what the site considers. The specificity concern does not hold, since miss-peregrines-home-for-peculiar-children (which does not exist, since it is too long) is not in any sense more specific than aftermath, nor could it meaningfully be broken into miss-peregrine, home-for-peculiar and children.
Search
The general solution to the problems mentioned previously has been to use a smaller but still meaningful subset of words. Frequently, however, this defeats one of the primary purposes of a tag, searchability. The problem is even worse on certain sites, such as Anime, where anime, manga, and light novel names tend to be quite long.
Aesthetics
The only solutions at this time are to choose a smaller set of related words, or use an abbreviation. Neither one of these is ideal. The second might work better with some series that have a commonly accepted abbreviation, but is downright ugly with others. Does anyone really want to see mphfpc instead of miss-peregrines-home-for-peculiar-children?
| {
"pile_set_name": "StackExchange"
} |
Q:
Select max of each group with its associated values
I have a large table formatted like so:
+-----+-------+-------+
| id | count | group |
+-----+-------+-------+
| 123 | 37 | a |
+-----+-------+-------+
| 121 | 26 | a |
+-----+-------+-------+
| 442 | 33 | a |
+-----+-------+-------+
| 923 | 55 | b |
+-----+-------+-------+
| 783 | 12 | b |
+-----+-------+-------+
My goal output would select the max count as well as the id associated with the max count for each group. Is there an array function that can do this? This array function gets me the max count, but it's not always distinct so i'm unsure how to grab the id as well:
{=MAX(IF(C:C=C1,B:B))}
So this would check the group in the 3rd (C) column and return the max count in the 2nd (B) column, but how can i grab the first (A) column as well?
A:
Perhaps this is what you want. In the example below
F2: =MAXIFS(count,group,E2)
G2: =INDEX($A:$A,MAX((group=E2)*(count=F2)*ROW(id)))
and the formula in G2 is an array formula which must be confirmed by holding down ctrl + shift while hitting Enter
Of course, if you don't have MAXIFS in your version of Excel, and you don't like to use the ctrl + shift + Enter sequence, you can use these formulas instead:
F2: =AGGREGATE(14,4,(group=E2)*count,1)
G2: =INDEX($A:$A,AGGREGATE(14,4,(count=F2)*(group=E2)*ROW(id),1))
| {
"pile_set_name": "StackExchange"
} |
Q:
mongodb geoSpatial query doesn't work
I'm trying to fetch records within a specific radius in km/miles.
mongodb 2d index:
db.collection.ensureIndex({locaction:"2d"})
a record in the collection has the indexed key:
"location" : { "longitude" : 34.791592164168, "latitude" : 32.0516908 0405 }
Calling collection's getIndexes() from shell gives me this:
...{
"v" : 1,
"key" : {
"location" : "2d"
},
"ns" : "events.events",
"name" : "location_2d"
}...
despite all the above, trying to fetch records with this command fails:
> db.events.find({location:{ $near :{ longitude:34,latitude:32},$maxDistance:10 / 3963.192}})
anyone can point out what prevent this from working?
A:
AFAIK, $near takes an array of the two target values, so you can try giving your values in array: -
db.events.find({location:{ $near : [34, 32],$maxDistance:10 / 3963.192}})
| {
"pile_set_name": "StackExchange"
} |
Q:
how to setup wordpress to allow multiple domains for same blog
I want to setup a single wordpress install to allow users to visit using 2 domains:
For example:
foo.com
bar.foo.com
I can do this for the most part, but whatever domain is configured in the wp-admin screen, it will redirect to that whenever any of the links are clicked.
For example, if I set it up to foo.com and I come in using bar.foo.com and click an article link, it takes me to foo.com and the article link. I want the user to stay on the domain they came in.
A:
Well, I tried rewriting above and it didnt work so well, but this seemed to work pretty well:
Go to plugins folder and create a file with this in it:
<?php
/*
Plugin Name: Disable Canonical URL Redirection
Description: Disables the "Canonical URL Redirect" features of WordPress 2.3 and above.
Version: 1.0
Author: Mark Jaquith
Author URI: http://markjaquith.com/
*/
remove_filter('template_redirect', 'redirect_canonical');
?>
Enable the plugin, then wala, it works!
| {
"pile_set_name": "StackExchange"
} |
Q:
MySql: Create datetime from year and month
I have the following query:
SELECT count(*) as 'count'
FROM myTable
WHERE myDateTime >= DATE1 AND myDateTime < DATE2
-myDateTime is of type datetime (2013-01-30 08:48:13) in myTable.
-DATE1 and DATE2 should be created as datetime also so I could compare them, like this:
-DATE1 should to be created from year (eg 2013) and month (eg 01) parameters, and the day should always be 01 (the first day of the month)
-DATE2 should be same as DATE1 with an added month. (if DATE1 is 2013-01-01 00:00:00 then DATE2 should be 2013-02-01 00:00:00)
A:
You can create the date as a number and then convert it to a date:
where myDateTime >= date(@year * 10000 + @month * 100 + 1) and
myDateTime < date_add(date(@year * 10000 + @month * 100 + 1), interval 1 month)
| {
"pile_set_name": "StackExchange"
} |
Q:
Symfony external library - Payone
Has anybody ever used Symfony in conjunction with payone(payone.de)?
I got the SDK and it has the folders js, locale and php.
My problem: I don't really know how to include/use them in my project(inexperienced in Symfony) because I don't know where I should place it and how to include it. I read about the auto loader but since the SDK doesn't follow the standards needed(concerning folder structure) I guess it's not the way to go.
A:
You can autoload all classes with the psr-0 too if the classes are following the PEAR-style non-namespaced convention.
To manage the vendor download via composer, you can define a package in your composer.json directly.
{
"repositories": [
{
"type": "package",
"package": {
"name": "payone/php-sdk",
"version": "1.0.0",
"dist": {
"url": "http://github.com/PAYONE/PHP-SDK/archive/master.zip",
"type": "zip"
},
"autoload": {
"psr-0": { "Payone_": "php/" }
}
}
}
],
"require": {
"payone/php-sdk": "1.0.*"
}
}
Note: This repository type has a few limitations and should be avoided whenever possible:
Composer will not update the package unless you change the version field.
| {
"pile_set_name": "StackExchange"
} |
Q:
Residues of $\frac{1}{1-az} e^{-\frac{i t}{2}\left(z+z^{-1}\right)}$
I have been fighting with a contour integral with the following integrand
\begin{align*}
f(z)=\frac{1}{1-az} e^{-\frac{i t}{2}\left(z+z^{-1}\right)}
\end{align*}
for $a,t>0$ real constants. I think this has a simple pole at $z=a^{-1}$ and two essential essential singularities at $z=0$ and $z=\infty$. I find the residue for the simple pole to be
\begin{align*}
\text{Res}\left(f(z),z=a^{-1}\right) = -\frac{1}{a} e^{-\frac{i t}{2}\left(a+a^{-1}\right)}
\end{align*}
For the essential singularity at $z=0$, I use the Laurent series
\begin{align*}
e^{-\frac{i t}{2}\left(z+z^{-1}\right)} = \sum\limits_{n\in\mathbb{Z}} z^n I_{n}(-it) = \sum\limits_{n=0}^{\infty} \left(z^n +\frac{1}{z^n}\right) I_{n}(-it) - I_{0}(-it)
\end{align*}
Where in the second equality I used $I_{-n}(t)=I_{n}(t)$ and subtracted the double counting. Similarly, around $z=0$ I use
\begin{align*}
(1-az)^{-1} = \sum\limits_{n=0}^{\infty} a^n z^n
\end{align*}
And so,
\begin{align*}
\frac{1}{1-az} e^{-\frac{i t}{2}\left(z+z^{-1}\right)} = \sum\limits_{n=0}^{\infty} \sum\limits_{k=0}^{\infty}\left(z^{2n-k}+z^{-k}\right) a^{n-k}I_{n}(-it) -I_{0}(-it)\sum\limits_{n=0}^{\infty}a^n z^n
\end{align*}
And the term with power $z^{-1}$ comes from $k=1$,
\begin{align*}
\text{Res}\left(f(z),z=0\right) = \sum\limits_{n=0}^{\infty} a^{n-1}I_{n}(-it) = \sum\limits_{n=0}^{\infty} a^{n-1}I_{n}(-it)
\end{align*}
Is this sensible? I am unsure about the convergence and about the product of the series. In the neighbourhood of $\infty$, the Laurent series of the exponential remains the same (symmetry under $z\to z^{-1}$), while $(1-ax)^{-1} = -\sum (a z)^{-(n+1)}$?
A:
You are correct. In a punctured neighbourhood of $z=0$ we have
$$ f(z)=\frac{1}{1-az}e^{\frac{it}{2}\left(z+\frac{1}{z}\right)}=\sum_{l\geq 0}a^l z^l \sum_{m\geq 0}\frac{1}{m!}\left(\frac{it}{2}\right)^m z^m \sum_{n\geq 0}\frac{1}{n!}\left(\frac{it}{2}\right)^n \frac{1}{z^n}$$
hence
$$ \text{Res}\left(f(z),z=0\right) = \sum_{l\geq 0}a^l\sum_{m\geq 0}\frac{1}{m!}\left(\frac{it}{2}\right)^m\frac{1}{(m+l+1)!}\left(\frac{it}{2}\right)^{l+m+1}$$
can be written as
$$ \sum_{l\geq 0}a^l i^{l+1} J_{l+1}(t) $$
with $J_{l+1}$ being a Bessel function of the first kind. $J_{l+1}(t)$ is rapidly decreasing to zero as $l\to +\infty$, hence the previous series is absolutely convergent for any $a$. The residue at infinity can be computed in a similar way, by expanding $\frac{1}{1-az}$ as mentioned.
| {
"pile_set_name": "StackExchange"
} |
Q:
django model setting up, using foreignkey of foreignkey
so I'm doing a small project to learn django,and I'm so confused about setting up db.
I have 3 Video Categories:
Chelsea, Barcelona, and RealMadrid.
Under that 3 videos there are seasons:
Chelsea - season1 season2 .....season n
same for Barcelona and RealMadrid
Under the season, there are videos
this is how I set it up so far but confused
class Team(models.Model):
name = models.CharField(max_length=255)
class Season(models.Model):
name = models.CharField(max_length=255)
team = models.ForeignKey(Team)
class Content(models.Model):
name = models.CharField(max_length=255)
season = models.ForeignKey(Season)
So the content of the foreignkey of foreignkey. Is this the valid way?and how do I get team name from the content?
A:
You must retrieve a content object in any way, e.g. like this:
content = Content.objects.get(id=0)
then you can refer to the team name by:
cotent_name = content.season.team.name
Also, if you want to filter the contents by the team name, you could do:
barca_contents = Content.objects.filter(season__team__name="Barcelona")
That would return a QuerySet with all the contents of the team Barcelona.
| {
"pile_set_name": "StackExchange"
} |
Q:
Javascript Basic: Search and Highlight
I want to highlight a word within a div when page will be loaded. My code is
<script type="text/javascript">
function highlight(container,what,spanClass) {
var content = container.innerHTML,
pattern = new RegExp('(>[^<.]*)(' + what + ')([^<.]*)','g'),
replaceWith = '$1<span ' + ( spanClass ? 'class="' + spanClass + '"' : '' ) + '">$2</span>$3',
highlighted = content.replace(pattern,replaceWith);
return (container.innerHTML = highlighted) !== content;
}
</script>
</head>
<body onload="highlight(document.getElementById('hello'),'florida','highlight');">
<div id="hello"> Florida florida orlando orlando</div>
Florida Texus florida
</body>
</html>
And nothing is happening in FF/Chrome/IE. I need your advice to fix this.
A:
That's because this code you use only works if there are some HTML tags around your elements.
It will work in a more general case, for example if you change your div to
<div id="hello"><p> Florida florida orlando orlanodo</p></div>
To make it work with your HTML you may use a simpler regex :
new RegExp('(' + what + ')','g')
and a different replacement :
replaceWith = '<span ' + ( spanClass ? 'class="' + spanClass + '"' : '' ) + '">$1</span>'
You could also have just changed your regex to make the groups optional :
pattern = new RegExp('(>[^<.]*)?(' + what + ')([^<.]*)?','g'),
Demonstration
| {
"pile_set_name": "StackExchange"
} |
Q:
Pglogical replication sets not working as expected
I am trying to setup up pglogical replication. I have a table which has around 4 rows in the provider server.
=========
employee_id | visitor_email | vistor_id | date | message
-------------+-----------------------+-----------+---------------------+--------------------------
1 | [email protected] | 1 | 2016-08-24 00:00:00 | This is the first test.
2 | [email protected] | 2 | 2016-08-24 00:00:00 | This is the second test.
3 | [email protected] | 3 | 2016-08-24 00:00:00 | This is the third test.
4 | [email protected] | 4 | 2016-08-24 00:00:00 | This is the fourth test.
===============================
After creating the above mentioned table. I have created a replication set in the provider . Then I configured the subscriber node and the subscription. Ideally, I should see the 4 rows from the provider table in my subscriber, but I am only seeing the table structure in subscriber, not the data. If I add a new row in the provider table as follows
INSERT INTO employees (employee_id, visitor_email, date, message) VALUES (5, '[email protected]', current_date, 'This is the fifth test.');
Now, I am able to see the last added row in my subscriber table. All the other 4 rows which were added in the beginning are still missing. What am I doing wrong here?
Does it mean that only the data which was created after the creation of replication_sets will be considered? How to add the whole content of a table to a replication set.?
Any help would be much appreciated.?
Regards,
Muhammed Roshan
A:
You can issue the resynchronise_table command to pull everything across. All subsequent inserts will be ok as you've found.
Use this function to do so:
pglogical.alter_subscription_resynchronize_table(subscription_name name, relation regclass)
Also you could have passed "synchronize_data" during your initial sync:
For more information see 2.3 in the following document:
https://2ndquadrant.com/en/resources/pglogical/pglogical-docs/
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does viewDidLoad wait before updating the UI?
I'm just trying to get my head around the Objective-C event model on iPhone, and by the looks of things I have fundamentally misunderstood something here.
For the purpose of experimentation, in a view controller's -viewDidLoad method, I am setting a UILabel's text, then sleeping for two seconds, and then changing the label's text again.
My expectations are as follows: the label will first read, "First Text", then two seconds later it will be updated to read, "Second Text." Of course, this isn't quite how it happens. Instead, the view isn't visible at all for two seconds, and finally when it becomes visible its label reads, "Second Text."
Could somebody please explain to me what is going on? I'm interested to find out how you guys would achieve what I'm going for here.
Cheers.
UPDATE 1: Here's the viewDidLoad method:
- (void)viewDidLoad {
[super viewDidLoad];
label.text = @"First Label";
sleep(2);
label.text = @"Second Label";
}
UPDATE 2: I made a silly mistake here, so please ignore this update.
UPDATE 3: I have now added the following to my viewDidAppear method:
- (void)viewDidAppear: (BOOL)animated {
[super viewDidAppear: animated];
label.text = @"First Label";
sleep(2);
label.text = @"Second Label";
}
Unfortunately I'm having exactly the same problem.
UPDATE 4: Following gerry3 and Felix's suggestions, I have now implemented a performSelector, and boom! Works a treat!! I'm going to have to give it to gerry3 though as he certainly put the most amount of effort into helping me out. Thanks for all your contributions!
A:
I guess the reason is that viewDidLoad runs on the mainThread as do all UIKit interactions. The UI can only be updated on the mainThread hence if you block the viewDidLoad with sleep(2) you are putting the mainThread to sleep and halt all userinterface updates on that thread.
Use NSTimer if you want to update the UI after a certain amount of time, rather than using sleep(2). Or use performSelector:withDelay: on self to perform a method later without blocking the mainThread.
Same holds true for viewDidAppear and viewWillAppear. Both run on the mainThread.
A:
Put your code that modifies the view in viewDidAppear:.
The view is not yet visible when viewDidLoad and viewWillAppear: are called.
UPDATE
Just to be clear, I agree with the others that the correct way to do this is with a delayed method call or timer.
UPDATE 2
Here is the code that I am suggesting:
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSLog(@"View will appear!");
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSLog(@"View did appear!");
label.text = @"First Label";
sleep(2);
label.text = @"Second Label";
}
And the "correct" way:
- (void)viewDidLoad {
[super viewDidLoad];
label.text = @"First Label";
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSLog(@"View will appear!");
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSLog(@"View did appear!");
[self performSelector:@selector(changeLabelText) withObject:nil afterDelay:2.0f];
}
- (void)changeLabelText {
label.text = @"Second Label";
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does this Boost.Spirit x3 rule parse correctly with angle brackets, but incorrectly with quotes?
The program below tries to parse C++ header include strings, such as "my/file.hpp" and <my/file.hpp>. For reasons I don't understand, my code fails to parse the " headers. Is this a bug in Spirit, or am I missing something obvious?
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/home/x3.hpp>
#include <iostream>
#include <string>
#include <cassert>
using namespace boost::spirit::x3;
int main() {
auto header_name_brackets = '<' >> *(~char_('>')) >> '>';
auto header_name_quotes = '"' >> *(~char_('>')) >> '"';
{
auto s = std::string{"<my/file.hpp>"};
std::string parsed;
assert(phrase_parse(s.begin(), s.end(), header_name_brackets, space, parsed));
}
{
auto s = std::string{"\"my/file.hpp\""};
std::string parsed;
// this assert fails, but I don't know why.
assert(phrase_parse(s.begin(), s.end(), header_name_quotes, space, parsed));
}
}
A:
Since you already have more answers than you can accept (:)) here's my $0.02:
template <typename Prefix, typename Postfix>
static auto quoted_(Prefix const& prefix, Postfix const& postfix) {
using namespace boost::spirit::x3;
return rule<struct _, std::string, true> {} = omit[prefix] >> *(char_ - postfix) >> omit[postfix];
}
Now you can write
auto header_name_brackets = quoted_('<', '>');
auto header_name_quotes = quoted_('"');
The second assumes the obvious convenience overload.
Another bug
In fact I think there's a bug that skips whitespace inside the delimiters. Fix it by adding lexeme[]:
template <typename Prefix, typename Postfix>
static auto quoted_(Prefix const& prefix, Postfix const& postfix) {
using namespace boost::spirit::x3;
return rule<struct _, std::string, true> {} = lexeme [
omit[prefix] >> *(char_ - postfix) >> omit[postfix]
];
}
See full demo:
Live On Coliru
#include <boost/spirit/home/x3.hpp>
#include <iostream>
#include <cassert>
template <typename Prefix, typename Postfix>
static auto quoted_(Prefix const& prefix, Postfix const& postfix) {
using namespace boost::spirit::x3;
return rule<struct _, std::string, true> {} = lexeme [
omit[prefix] >> *(char_ - postfix) >> omit[postfix]
];
}
template <typename Prefix>
static auto quoted_(Prefix const& prefix) { return quoted_(prefix, prefix); }
int main() {
using boost::spirit::x3::space;
auto header_name_brackets = quoted_('<', '>');
auto header_name_quotes = quoted_('"');
{
auto s = std::string{"<my/file.hpp>"};
std::string parsed;
assert(phrase_parse(s.begin(), s.end(), header_name_brackets, space, parsed));
}
{
auto s = std::string{"\"my/file.hpp\""};
std::string parsed;
assert(phrase_parse(s.begin(), s.end(), header_name_quotes, space, parsed));
}
std::cout << "Bye\n";
}
A:
This works for me:
#include <boost/spirit/home/x3.hpp>
#include <iostream>
#include <string>
#include <cassert>
using namespace boost::spirit::x3;
int main() {
auto header_name_brackets = '<' >> *(~char_('>')) >> '>';
auto header_name_quotes = '"' >> *(~char_('"')) >> '"';
{
auto s = std::string{"<my/file.hpp>"};
std::string parsed;
assert(phrase_parse(s.begin(), s.end(), header_name_brackets, space, parsed));
}
{
auto s = std::string{"\"my/file.hpp\""};
std::string parsed;
// this assert fails, but I don't know why.
assert(phrase_parse(s.begin(), s.end(), header_name_quotes, space, parsed));
}
}
Note that you need to match all chars except " in the second case, just as you did with > in the first.
| {
"pile_set_name": "StackExchange"
} |
Q:
chrome/firefox- how to run a javascript command
I am using a gwt based ui design framework (called GXT). In the docs for this framework, it is mentioned that running "javascript:isc.showConsole()" when the app is running, will open the developer console in browser.
However when I run this in Chrome it instead does a google search for the command- in firefox it simply does not work.
How do I execute this javascript in firefox or chrome--
javascript:isc.showConsole()
A:
Bookmarklets cannot be executed in the location bar/omnibox any more.
You have to bookmark the javascript: link before it can be executed.
A better solution is using the built-in Developer tools, in which code can be pasted and executed in the current page:
Firefox: Ctrl Shift K - See Using the web console.
Chrome: Ctrl Shift J - See Developer tools.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does the Onclick event not work on my ion col?
My onclick event does not work on a ion-col, it keeps saying, whatever method i call "is not defined at html element.onclick" my code snippet looks as follows
<ion-row style="width:100%; height:6%; border: 1px solid #36B729; position:absolute; top:51.5%;">
<!-- Wall Tab -->
<ion-col id="WallTab" style="height:100%; border: 1px solid #36B729" align="center" onClick="TabManagement(this.id)">
<font id="WallTab" style="color: #36B729; font-size: 70%;">Wall</font>
</ion-col>
<!-- Happy Customers Tab -->
<ion-col id="HappyCustomersTab" style="height:100%; border: 1px solid #36B729" align="center" onClick="TabManagement(this.id)">
<font id="HappyCustomersTab" style="color: white; font-size: 70%;">Happy Customers</font>
</ion-col>
<!-- Reports Tab -->
<ion-col id="UnhappyCustomersTab" style="height:100%; border: 1px solid #36B729" align="center" onClick="GoBack();">
<font id="UnhappyCustomersTab" style="color: white; font-size: 70%;">Unhappy Customers</font>
</ion-col>
</ion-row>
My ts file looks as follows
public class profile{
TabManagement(){
code...
}
}
A:
You should use just (click)="GoBack()"
And try use (click)="TabManagement(id)" without this
| {
"pile_set_name": "StackExchange"
} |
Q:
I am not able to get the gridview populated with textview in Android Fragment
i am not able to populate the imageview textview inside gridview using fragments.
It is showing blank intead of gridview populating in my project can please anyone see the code below and let me know what i have to change
And the populating the image and text is from the mysql database dynamically
public class StoreHomeFragment extends Fragment {
final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.store_home, container, false);
final GridView gridView1 = (GridView)rootView.findViewById(R.id.store_home_gridview);
gridView1.setAdapter(new ImageAdapter(rootView.getContext(), MyArrList));
return rootView;
}
//Activity is created
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String url = "http://192.168.1.132/Android/App/good.php"; //url where i am using select query and retrieving it from database
try {
JSONArray data = new JSONArray(getJSONUrl(url));
HashMap<String, String> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);//retrieving from db
map = new HashMap<String, String>();
map.put("name", c.getString("name"));
map.put("artist", c.getString("artist"));
map.put("price", c.getString("price"));
map.put("image", c.getString("image"));
MyArrList.add(map);
}
//gridView1.setAdapter(new ImageAdapter(this,MyArrList));
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//I have used imageAdapter
class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageView imageView;
private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();
public ImageAdapter(Context c,ArrayList<HashMap<String, String>> list)
{
context = c;
MyArr = list;
}
public int getCount() {
return MyArr.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.store_home_gridview_row, null);
}
TextView tv_title = (TextView) convertView.findViewById(R.id.textview_name);
tv_title.setText("Title:"+MyArr.get(position).get("name"));
TextView tv_artist = (TextView) convertView.findViewById(R.id.textview_artist);
tv_artist.setText("Artist:"+MyArr.get(position).get("artist"));
TextView tv_duration = (TextView) convertView.findViewById(R.id.textview_price);
tv_duration.setText("Price:"+MyArr.get(position).get("price"));
String abc = (MyArr.get(position).get("image"));
String abcd = "http://192.168.1.132/images/products/"+abc;
imageView = (ImageView) convertView.findViewById(R.id.imageView1);
try
{
URL url3 = null;
try {
url3 = new URL(abcd);
} catch (Exception e) {
e.printStackTrace();
}
Bitmap bmp = BitmapFactory.decodeStream(url3.openConnection().getInputStream()); //image is populated
imageView.setImageBitmap(bmp);
}
catch(Exception par)
{
imageView.setImageResource(android.R.drawable.ic_menu_report_image);
}
return convertView;
}
}
/*** Get JSON Code from URL ***/
public String getJSONUrl(String url) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try
{
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
System.out.println ( "status Code : " + statusCode );
if (statusCode == 200)
{
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null)
{
str.append(line);
}
}
else
{
Log.e("Log", "Failed to download file..");
}
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println ( "str : " + str.toString() );
return str.toString();
}
}
A:
Follow the steps Hope this helps you
1) Remove these lines from onCreateView() method
final GridView gridView1 = (GridView)rootView.findViewById(R.id.store_home_gridview);
gridView1.setAdapter(new ImageAdapter(rootView.getContext(), MyArrList));
2)Modify onActivityCreated() as follow
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
String url = "http://192.168.1.132/Android/App/good.php";
try {
JSONArray data = new JSONArray(getJSONUrl(url));
HashMap<String, String> map;
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("name", c.getString("name"));
map.put("artist", c.getString("artist"));
map.put("price", c.getString("price"));
map.put("image", c.getString("image"));
MyArrList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
final GridView gridView1 = (GridView) rootView.findViewById(R.id.store_home_gridview);
gridView1.setAdapter(new ImageAdapter(getActivity(), MyArrList));
}
}.execute();
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Train classifier on balanced dataset and apply on imbalanced dataset?
I have a labelled training dataset DS1 with 1000 entries. The targets (True/False) are nearly balanced. With sklearn, I have tried several algorithms, of which the GradientBoostingClassifier works best with F-Score ~0.83.
Now, I have to apply the trained classifier on an unlabelled dataset DS2 with ~ 5 million entries (and same features). However, for DS2, the target distribution is expected to be highly unbalanced.
Is this a problem? Will the model reproduce the trained target distribution from DS1 when applied on DS2?
If yes, would another algorithm be more robust?
A:
Is this a problem?
No. not at all.
Will the model reproduce the trained target distribution from DS1 when
applied on DS2?
No, not necessarily. If
Balanced set DS1 is a good representative of imbalanced (target) set DS2, and
Classes are well-separated (pointed out by @BenReiniger), which holds easier in higher dimensions,
then model will generate labels with a ratio close to imbalanced DS2 not balanced DS1. Here is a visual example (drawn by myself):
As you see, in the good training set, predictions resemble the real-world ratio, even though model is trained on a balanced set, of course, if classifier does a good job of finding the decision boundaries.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I check if a string contains no characters?
I know this is a similar post to How to check if text is "empty" (spaces, tabs, newlines) in Python?
, however I'm still having troubles.
I don't understand how to use it, I'm trying to check if a variable, which contains a string, consists of only spaces, tabs and newlines. How would I use issppace() as I'm confused with it always being False?.
Help would be much appreciated.
A:
You can use:
if string_to_check.strip():
print("Contains characters")
else:
print("Contains no characters")
| {
"pile_set_name": "StackExchange"
} |
Q:
BIOS clock still slow after battery change
Recently I discovered that my system clock was slowing down. I got a new CMOS battery and replaced the one already on the motherboard. Both of the batteries seemed to have good voltage with a tongue test. However, two days after I re-synchronized the clock over the internet, I have lost 9 minutes and 15 seconds.
Does anyone know what could be causing the problem? I read in another question that the Real Time Clock crystal might be at fault, does that seem to be the case here?
Custom built machine with a Gigabyte GA-770TA-UD3 motherboard and a AMD Phenom 955 BE @3.2GHz running Windows 7.
A:
I use an HP/Apollo system for work which is designed so that the clock runs slowly, but a modern PC motherboard shouldn't do this.
You could use an NTP server to synchronise the clock to a time standard, but it should be able to keep better time (than you're seeing) without it.
I would agree with the theory which says it's the RTC crystal. What you're seeing may be an indication it's about to fail completely.
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding an IEnumerable to a RouteValueDictionary - is this possible?
I'm using ASP.Net MVC 2, and I've got a slight problem. I need to produce an url from a list of values.
Using the following code:
RouteValueDictionary dic = new RouteValueDictionary();
dic.Add("mylist", new [] { 1, 2, 3 });
return helper.Action(dic["action"] as string, dic["controller"] as string, dic);
I get the url /whatever/System.Int32[] which obviously is not what I am after.
What is the ASP.Net MVC 2 preferred way of generating such an URL? I know the modelbinder can handle lists, but how to generate it?
A quick note on how it is done in MVC 3 would also be appreciated (if the method differs).
A:
See if this prior response helps you (mvc 3 would be the same - its the same routing engine as part of asp.net 4)
ASP.NET MVC - Pass array object as a route value within Html.ActionLink(...)
| {
"pile_set_name": "StackExchange"
} |
Q:
reshape (converting to character)
i have a the following matrix
data=structure(list(Metric = c("x", "y"), Result1 = c(9,
18), Result2 = c(7, 14
), Delta = c(-170, -401)), .Names = c("Metric",
"Result_1", "Result_2", "Delta"), row.names = c(NA,
-2L), class = "data.frame")
I would like to transform it in 1 row and to double the number of columns
I tried the following (as.vector(t(data))). However when I do that it transofrms everything to character and i loose data information
Any help?
A:
We can split the data frame and then use bind_cols from the dplyr package. Although I am not sure this is your expected output as you did not provide any examples, just description.
dplyr::bind_cols(split(data, data$Metric))
Metric Result_1 Result_2 Delta Metric1 Result_11 Result_21 Delta1
1 x 9 7 -170 y 18 14 -401
| {
"pile_set_name": "StackExchange"
} |
Q:
cutting the text field to 100 characters in javascript
I have an array(foo) of objects, each of which has a field called "text" and some of them are very long texts; so I wnat to have a limit of 100 charachters for text; would you do the same approach for cutting to 100 characters in javascript? I belive there is better ways of doing that...Or if it is already clean could you please confirm me? Thanks
results = foo.map(function(obj){
if(obj['text'] && obj['text'].length >100){
obj['text'] = obj['text'].substr(0,97)+"...";
}
return obj;
})
A:
Use ellipsis instead of deleting the text.
Have a look at CSS text-overflow in a table cell? for your problem
create a class as
.myellipsis {
text-overflow:ellipsis;
}
Applying this class would replace overflown text with a "..."
| {
"pile_set_name": "StackExchange"
} |
Q:
VBA - Excel: Mention a Range equal to one given with less one row
So I have a given function which is recieves a range (which is always size (X,1) - meaning it is a column) as argument, something like:
Function myfunction (byref myrange as Range) as Double
...
myfunction = stuff
End Function.
Somewhere within that function I need to refer to "myrange of size (X-1,1)".
This is I want to call function that should receive as argument the same range of myrange but instead of being say, B10:B15 I want to pass it B10:B14
And I have no idea how to do it...
Can you help me?
Thanks,
Rui
A:
Use the Resize method:
Function myfunction (ByVal myrange as Range) as Double
Set myrange = myrange.Resize(rng.Rows.Count - 1)
Important note: I've changed your prototype to ByVal as I'm modifying myrange.
| {
"pile_set_name": "StackExchange"
} |
Q:
OpenERP How to use a domain filter on many2one field?
I am new to OpenERP (v7) and am writing a module that extends the res.partner class and added the following two fields :
_columns = {
'member_ids': fields.one2many('res.partner', 'church_id', 'Members', domain=[('active','=',True)]),
'church_id': fields.many2one('res.partner', 'Church', domain="[('is_company','=',True)]")
}
What I would like to do, is that when the user opens the church_id view, it shows only partners that are churches. For now, it displays all companies as I am not able to set correctly the domain. A church is a company that has the category id (res.partner.category) corresponding to the church category. I tried to solve my problem using a functional field, but I am only getting some errors. The following function returns correctly a dictionary containing the current user id and the list of the church ids :
# Returns : {'user_id': [church_id1, church_id2, ...]}
def _get_church_ids(self, cr, uid, ids, field_name, arg, context=None):
sql_req = """
SELECT R.partner_id
FROM res_partner_res_partner_category_rel R
LEFT JOIN res_partner_category C ON ( R.category_id = C.id)
WHERE C.active = TRUE AND UPPER(C.name) = 'CHURCH'
"""
cr.execute(sql_req)
sql_res = cr.fetchall()
return dict.fromkeys(ids, sql_res)
Corresponding field and view :
'church_ids': fields.function(_get_church_ids, type="one2many", relation='res.partner', method=True)
<field name="church_ids" invisible="1"/>
I tried the following domains on the view church_id, and I always get the same error :
Uncaught Error: Expected "]", got "(name)"
<field name="church_id" attrs="{'invisible': [('is_company','=',True)]} domain="[('id','in',[church for church in church_ids[id]])]"/>
<field name="church_id" attrs="{'invisible': [('is_company','=',True)]} domain="[('id','in',[church[0] for church in church_ids)]"/>
Any suggestions on how to do this ? I spent already some days trying to figure it out but with no luck. I also tried to do it with a related field but I couldn't understand how to achieve it... Many thanks for your help !
A:
Someone suggested me that the church_id field should be related to a church table, but I just wanted to indicate if a partner record is a church or not. Therefore, I could just create a field called 'is_church' as a boolean, then use a domain to filter for any partner records where the is_church value is set to true like this
domain = "[('is_church','=',True)]"
I can get rid of the church_id field because it's not related to a church table.
In the .py file:
_columns{
'is_church': fields.boolean('Is a Church', domain="[('is_church', '=', True)]")
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Device to authenticate a HTTP request
I'm trying to authenticate a HTTP request using a token sent by an Android application, but I have no idea how to do this.
To get this token I must to send an user a password, to my ruby application that returns the token, but I want to know how to verify all requests from my android application using this token.
I know the "before_filter" on ruby, but I think that it could have problems with my first authentication, because I have to login with the user and password just once, but every time with the token.
If you can indicate any links or some pieces of code ...
Thanks in advance.
A:
After successful log-in you should save Token in Constants and should send this token with each HTTP request.Server will verify user with access token and return result.
| {
"pile_set_name": "StackExchange"
} |
Q:
Where can I download the source code of support library v7 of android?
I'd like to download the source code of both support library v4 and v7
but it seems like that in SDK Manager only the source code of Android itself can be found.
So where to download the support library source code? A zip file is better
======
Found source code of v4, but not v7
A:
You can find it in the support repository.
A:
You already have it, if you downloaded the support package through the SDK manager. Navigate to your sdk folder:
<sdk>/extras/android/support/v4/src
<sdk>/extras/android/support/v7/src
<sdk>/extras/android/support/v13/src
A:
The (Java) source for all the support libraries is nowadays in the same folder as the standard Android source code, that is, in <android-sdk>\sources\android-XX\. In particular, the <android-sdk>\sources\android-XX\android\support contains the full android.support package source code, which comprises all the support libraries.
For example:
FragmentManager, part of the "base" Support Library, is in <android-sdk>\sources\android-21\android\support\v4\app\FragmentManager.java.
ActionBarActivity, part of the v7 appcompat library, is in <android-sdk>\sources\android-21\android\support\v7\app\ActionBarActivity.java.
Same for cardview, mediarouter, &c.
| {
"pile_set_name": "StackExchange"
} |
Q:
Filter list of dictionaries with higher key value remove duplicate dictionaries
I have list of dictionaries like:
sel_list = [{'a': 8}, {'a': 4}, {'a': 4}, {'b': 8}, {'b': 9}]
I want to remove duplicate dictionaries and if more than one dictionaries have same key but different values then choose that dictionary with higher value.
Like :
sel_list = [{'a': 8}, {'b': 9}]
I have tried:
[i for n, i in enumerate(sel_list) if i not in sel_list[n + 1:]]
its results in:
[{'a': 8}, {'a': 4}, {'b': 8}, {'b': 9}]
What I can do to achieve my results?
A:
We can do this by constructing a dictionary that "folds" the values by picking the maximum each time. Like:
dummy = object()
maximums = {}
for subd in sel_list:
for k, v in subd.items():
cur = maximums.get(k, dummy)
if cur is dummy or v > cur:
maximums[k] = v
result = [{k: v} for k, v in maximums.items()]
We thus iterate over the key-value pairs of the dictionaries in the list, and each time update the maximums dictionary in case the key does not yet exists, or the current value is less.
After this iteration step, we produce a list of dictionaries with the maximum key-value pairs.
This approach works on all types that can be ordered (numbers, strings, etc.), and the keys should be hashable, but this assumption holds since in the list of dictionaries, the keys are already hashed.
Furthermore it works rather robust in the sense that it will ignore empty dictionaries, and will process a dictionary with multiple key-value pairs as well, by seeing these as independent key-value pairs.
You can also decide to work with maximums directly: a dictionary that contains all the keys in your original list, and associates these with the maximum value seen in the list.
| {
"pile_set_name": "StackExchange"
} |
Q:
Handling singularities in squircle parametric equations
In order to plot a squircle using its parametric equations:
The equations can be found in page 9 of this
this article:
Fong, Chamberlain. "Squircular Calculations." arXiv preprint arXiv:1604.02174 (2016).
Unfortunately the following singularities are not handled by those equations:
For t = 0, t = pi/2, t = pi, t = 3pi/2, and t=2*pi
Here is the code to plot these equations in Python
"""Plot squircle shape using its parametric equations"""
import numpy as np
from numpy import pi, sqrt, cos, sin, sign
import matplotlib.pyplot as plt
# FG stands for Fernandez-Guasti who introduced the algebric equations.
def FG_param(r, s, t):
x = np.ones_like(t)
y = np.ones_like(t)
for i, _t in enumerate(t):
if np.isclose(_t, 0.0):
x[i] = r
y[i] = 0.0
elif np.isclose(_t, pi/2.0):
x[i] = 0.0
y[i] = r
elif np.isclose(_t, pi):
x[i] = -r
y[i] = 0.0
elif np.isclose(_t, 3*pi/2.0):
x[i] = 0.0
y[i] = -r
elif np.isclose(_t, 2*pi):
x[i] = r
y[i] = 0.0
else:
x[i] = r*sign(cos(t[i]))/(s*sqrt(2)*np.abs(sin(t[i])))*sqrt(1 - sqrt(1-s**2*sin(2*t[i])**2))
y[i] = r*sign(sin(t[i]))/(s*sqrt(2)*np.abs(cos(t[i])))*sqrt(1 - sqrt(1-s**2*sin(2*t[i])**2))
return x, y
s = 0.7
r = 1.0
NTHETA = 90
t = np.linspace(0, 2*pi, NTHETA)
x, y = FG_param(r, s, t)
plt.gca().set_aspect('equal')
plt.scatter(x, y, s=5)
plt.show()
The function FG_param looks very clumsy. I appreciate any help to make it more compact and neat.
Thank you
A:
Here's a different solution. The singularities occur when sin(_t) or cos(_t) is zero. So check for those conditions.
def FG_param(r, s, t):
x = np.ones_like(t)
y = np.ones_like(t)
for i, _t in enumerate(t):
sin_t = sin(_t)
cos_t = cos(_t)
if np.isclose(sin_t, 0.0):
x[i] = -r if np.isclose(_t, pi) else r
y[i] = 0.0
elif np.isclose(cos_t, 0.0):
x[i] = 0.0
y[i] = r if _t < pi else -r
else:
radical = sqrt(1 - sqrt(1 - s**2 * sin(2*_t)**2))
x[i] = r*sign(cos_t) / (s*sqrt(2)*np.abs(sin_t)) * radical
y[i] = r*sign(sin_t) / (s*sqrt(2)*np.abs(cos_t)) * radical
return x, y
| {
"pile_set_name": "StackExchange"
} |
Q:
Do I keep Flare in my Opening Hand Against Mages
I am playing a Midrange Hunter with one copy of Flare in the Un'goro Meta.
The mages in the Un'goro meta seemingly all have Ice block, and possibly Ice Barrier in their deck.
If I were to keep Flare, it would hard counter an Ice block, allowing me to kill the mage one turn, and possibly two turns earlier.
However, keeping a Flare means I have a dead card in my hand until many turns later, possibly until the last turn of the game. This could delay my killing the mage a turn or more also.
Should I keep flare in my opening hand against Mages?
A:
The biggest success factor (in terms of deck composition) is in the versatility of your deck. You never know what class you'll play against. Ideally, you want a single deck to be able to stand up to different playstyles from different opponents.
That's not to say that each deck, including your own, doesn't have its own weakness to certain other decks. But the key is to try and minimize the amount of decks that you are weak to.
Mages have notoriously tough secrets to get through (they are the class with the most expensive secrets after all). Comparatively, Paladin secrets are a bit annoying but hardly ever a big game changer. Not saying Paladin secrets can't be good (I'm a devout Paladin player), but a random paladin secret will give you less bang compared to a random mage secret (ignoring the different mana cost).
Ice Block, as you mentioned, can turn the tide of a game quickly (or, more accurately, stem the tide of a game that has turned against the mage). Especially if you are playing an aggro deck, every turn counts. If a mage can guarantee stalling you for one more turn, that gives them the freedom to counter your plays without fearing defeat the next turn.
Assuming turn 10+; a mage that played Ice block can spend their next 17 mana (7 from the turn where they play IB, 10 from the next turn) wiping your advantage off the board. There aren't many boards that can stand up to the equivalent power of a (flamestrike)+(fireball)+(fireball)+(flame cannon). The mage might of course play different cards, but these cards will presumably have a roughly similar bang for buck.
If they play any freezing spell during their 17 mana blowout, this can add another 10 mana per stalled turn.
However, I don't expect a mage to expect a Flare. This means you can catch a cocky mage (who plays balls to the wall because IB is protecting them) and surprise kill them.
It's perfectly acceptable to use the same card differently when playing against a different opponent. This can be based on enemy class (most common) or enemy deck type.
As a mid/control paladin, I keep a Noble Sacrifice in my hand against druids and warriors, but I tend to play it early against a rogue or hunter.
Ice block is a really annoying secret. You can influence the outcome of most secrets (Mirror entity = play a tiny minion; Noble sacrifice = attack with the lowest attack minion first), but Ice block is pretty hard to influence (except for making sure your opponent has the lowest health possible before triggering IB).
I wouldn't suggest keeping Flare in your opening hand if you intend to use it lategame. But I do think it's a valid idea to only want to play the Flare against a seemingly unavoidable Ice Block late in the game.
| {
"pile_set_name": "StackExchange"
} |
Q:
Reducing the Hardcoded if statement to be more Dynamic
i have a radio button which could be selected on an infinite amount of rows as it adds a new row everytime the first one is completed, the user then selects which one they want to be the primary number which set it as a value "1" or "2" etc..
my issue is if the user where to enter more than 8 phone numbers my code would be obsolete i was wondering what the best way to do this was :
if ($Details['MakePrimary'] == 1){
$Customer->Code = $Details['phoneNumber'][0]['Code'];
$Customer->Number = $Details['phoneNumber'][0]['mainNumber'];
} else if ($Details['MakePrimary'] == 2){
$Customer->Code = $Details['phoneNumber'][1]['Code'];
$Customer->Number = $Details['phoneNumber'][1]['mainNumber'];
} else if ($paymentDetails['MakePrimary'] == 3){
$Customer->StdCode = $Details['phoneNumber'][2]['Code'];
$Customer->Number = $Details['phoneNumber'][2]['mainNumber'];
} else if ($Details['MakePrimary'] == 4){
$Customer->Code = $Details['phoneNumber'][3]['Code'];
$Customer->Number = $Details['phoneNumber'][3]['mainNumber'];
} else if ($paymentDetails['MakePrimary'] == 5){
$Customer->Code = $Details['phoneNumber'][4]['Code'];
$Customer->Number = $Details['phoneNumber'][4]['mainNumber'];
} else if ($Details['MakePrimary'] == 6){
$Customer->Code = $Details['phoneNumber'][5]['Code'];
$Customer->Number = $Details['phoneNumber'][5]['mainNumber'];
} else if ($Details['MakePrimary'] == 7){
$Customer->Code = $Details['phoneNumber'][6]['Code'];
$Customer->Number = $Details['phoneNumber'][6]['mainNumber'];
} else if ($Details['MakePrimary'] == 8){
$Customer->Code = $Details['phoneNumber'][7]['Code'];
$Customer->Number = $Details['phoneNumber'][7]['mainNumber'];
} else {
$Customer->Code = $Details['phoneNumber'][8]['Code'];
$Customer->Number = $Details['phoneNumber'][8]['mainNumber'];
}
A:
You should try this :
$index = $paymentDetails['MakePrimary'] - 1;
$voipCustomer->StdCode = $paymentDetails['phoneNumber'][$index]['stdCode'];
$voipCustomer->Number = $paymentDetails['phoneNumber'][$index]['mainNumber'];
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set the activity name as a variable in os_activity_initiate?
Here when I tried setting the "test_activity" string as a variable I am getting some errors.
os_activity_initiate("test_activity", OS_ACTIVITY_FLAG_DEFAULT, ^(void) {
});
How to set the activity name as a variable here? something like given below.
os_activity_initiate(activity_name, OS_ACTIVITY_FLAG_DEFAULT, ^(void) {
});
I could see the following function "_os_activity_initiate", but it is mentioned that "Do not use directly because your description will not be preserved" not sure what does it means? Any idea? Please help.
A:
Unfortunately this is not possible - os_activity_initiate() requires the first argument to be a static string. You cannot use a variable here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Powershell: Passing variable into scriptblock within function
So take this code:
function populate([string] $group)
{
$listbox.items.clear()
Get-ADGroup -filter {cn -like "*$group*"} |
foreach {$listbox.items.add($_.DistinguishedName)}
}
$go.Add_Click(
{
populate -group $text.text
})
I'm trying to take the variable $group and pass it to {cn -like "*$group*"} but I can't get it to work. Does anybody have any ideas?
Thanks
A:
Try this:
$pattern = "*$group*"
Get-ADGroup -filter {cn -like $pattern} ...
| {
"pile_set_name": "StackExchange"
} |
Q:
Error signing an MSI package, what's going on?
I just obtained a code signing certificate from DigiCert. I've got the Microsoft Authenticode one. I was surprised they didn't ask me for a private key (I think it was generated in the browser). After exporting it from Firefox to a P12-file, I tried signing my app with it and it failed:
C:\Users\pupeno\>"C:\Program Files (x86)\Windows Kits\10\bin\x86\signtool.exe" sign /v /f key_and_cert.p12 app.msi
SignTool Error: An unexpected internal error has occurred.
Error information: "Error: Store::ImportCertObject() failed." (-2146885630/0x80092002)
Any ideas what's going on?
A:
DigiCert support help me through this problem and they were amazing. I'm not sure I found the actual solution to that command line issue, but there's a workaround.
Using the DigiCert SSL Utility I imported the cert and since it was the only private key/cert I had on my system, removing it from the command line picked it automatically.
The working command line ended up being like this:
"C:\Program Files (x86)\Windows Kits\10\bin\x86\signtool.exe" sign /tr http://timestamp.digicert.com /td sha256 /fd sha256 /a "app.msi"
| {
"pile_set_name": "StackExchange"
} |
Q:
Probability - An assortment of 20 parts
An assortment of 20 parts is considered to be good if it has not more than 2
defective parts, it is considered bad if it contains at least 4 defective parts. Buyer and seller of the assortment agree to test 4 randomly picked out parts. Only when all 4 are good, the purchase will take place. In this procedure the seller bears the risk of not selling a good assortment, the buyer to buy a bad assortment. Who carries the greater risk?
So I have two problems here:
1) If at least 1 part is defective, the purchase won't take place (The Seller has the risk of not selling a good assortment)
2) If all 4 are good, the purchase will take place (But the buyer has the risk of buying a bad assortment)
My Idea for 1) (at least 1 part is defective)
$$P(X\ge 1)=1-P(X=0)=1-\begin{pmatrix}
1 \\
0
\end{pmatrix}* \begin{pmatrix}
19 \\
4
\end{pmatrix}/ \begin{pmatrix}
20 \\
4
\end{pmatrix}=1-4/5=0,2$$
My idea for 2) (All 4 parts are good)
$$
P(B)= \begin{pmatrix}
4 \\
0
\end{pmatrix}* \begin{pmatrix}
16 \\
4
\end{pmatrix}/ \begin{pmatrix}
20 \\
4
\end{pmatrix} =364/969=0,3756
$$
So the Buyer has a higher risk than the seller. However I think I made a mistake somewhere.
Thanks in advance!
A:
1. Seller's Risk (worst case): You want the probability of getting at least one defective part from a 'good' batch. That is a batch that contains 3 (or fewer) defective parts. The risk of a wrong decision is greatest if there are three defective parts, so use that. [It seems you are using one defective part to represent a good batch.]
$$P(X \ge 1) = 1 - P(X = 0) = 1 - \frac{{3\choose 0}{17 \choose 4}}{20 \choose 4} = 0.5088. $$
This is a hypergeometric distribution. The computation in R statistical software is:
1 - dhyper(0, 3, 17, 4)
## 0.5087719
1 - choose(17,4)/choose(20,4)
## 0.5087719
2. Buyer's Risk (worst case): You want the probability of getting no defective parts from a 'bad' batch.
That is a batch that contains 4 (or more) defective parts. The risk is greatest if there are four defective parts, so we use that.
$$P(Y = 0) = \frac{{4 \choose 0}{16 \choose 4}}{20 \choose 4} = 0.3756.$$
dhyper(0, 4, 16, 4)
## 0.375645
choose(16, 4)/choose(20,4)
## 0.375645
Here is a plot that shows the two hypergeometric distributions.
The Seller's Risk is the sum of the heights of the blue bars to the
right of the vertical dotted line. Buyer's risk the height of the maroon
bar to the left of the vertical line.
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery exclude child element from click event
I'm trying to exclude click event on <div> tag:
Here is my html:
<div class="event" style="height:150px;width:150px;border:1px solid #dddddd;padding:10px">
<div class="number">10</div>
<div class="wrap"><a style="display:block;color:#FF0000">Event Name</a></div>
</div>
here is javascript:
$(document).on('click', '.event', function(e) {
if($(e.target).not('.wrap')){
console.log('Hello');
}
});
But for some reason it does not work for me. I don't want click event to fire when clicking on .wrap or <a> element.
Here is jsbin as well: https://jsbin.com/ziyukuyefo/edit?html,js,output
A:
There are 2 issues in your code
- not() returns a jQuery object so your condition will always be truthy
- Since you have a anchor element in wrap e.target may refer to that not the wrap element itself
You can check using closest() to see whether there is an element matching the selector in the ancestor tree
$(document).on('click', '.event', function(e) {
if (!$(e.target).closest('.wrap').length) {
snippet.log('clicked');
}
});
.wrap {
background-color: lightgrey;
}
.wrap a {
border: 1px solid red;
}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="event" style="height:150px;width:150px;border:1px solid #dddddd;padding:10px">
<div class="number">10</div>
<div class="wrap"><a style="display:block;color:#FF0000">Event Name</a>
</div>
</div>
Another option is to stop the event propagation, which may not be appropriate in all the scenarios
| {
"pile_set_name": "StackExchange"
} |
Q:
javascript Button Doing Nothing onclick
First of all, I am not very good at javascript. Well what I am trying to do is create a sort of wheel spinning program where, on a button click, you will either get extra spins, nothing, or it will send me an email with a secret code and I will reply in the email how much they will win. Hopefully you understand what I mean and know why its not working.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, user-scalable=no">
<title>Spin the Wheel!</title>
</head>
<body>
<button name="generate" type="button" onClick="gennum()">Spin!</button>
<script>
function gennum() {
var result=Math.floor(Math.random()*101)
check()
}
function check() {
if (result > 0 && result < 11) {
alert("You win 1 free spin! Spin again!")
}
else if (result > 10 && result < 16) {
alert("You win 2 free spins! Spin again twice!")
}
else if (result > 15 && result < 26) {
alert("Sorry, you won nothing. Please try again tommorow.")
}
else if (result > 25 && result < 36) {
var link = "mailto:[email protected]"
+ "&subject=" + escape("Spinner")
+ "&body=" + escape(document.getElementById('7L6XPaY8').value)
;
window.location.href = link;
}
else if (result > 35 && result < 45) {
var link = "mailto:[email protected]"
+ "&subject=" + escape("Spinner")
+ "&body=" + escape(document.getElementById('NmE6B5uF').value)
;
window.location.href = link;
}
else if (result > 44 && result < 52) {
var link = "mailto:[email protected]"
+ "&subject=" + escape("Spinner")
+ "&body=" + escape(document.getElementById('ZpLb9TRC').value)
;
window.location.href = link;
}
else if (result > 51 && result < 59) {
var link = "mailto:[email protected]"
+ "&subject=" + escape("Spinner")
+ "&body=" + escape(document.getElementById('JQa6fGHH').value)
;
window.location.href = link;
}
else if (result > 58 && result < 64) {
var link = "mailto:[email protected]"
+ "&subject=" + escape("Spinner")
+ "&body=" + escape(document.getElementById('rKjPGXak').value)
;
window.location.href = link;
}
else if (result > 63 && result < 69) {
var link = "mailto:[email protected]"
+ "&subject=" + escape("Spinner")
+ "&body=" + escape(document.getElementById('5QQyCJaD').value)
;
window.location.href = link;
}
else if (result > 68 && result < 71) {
var link = "mailto:[email protected]"
+ "&subject=" + escape("Spinner")
+ "&body=" + escape(document.getElementById('474zbnkE').value)
;
window.location.href = link;
}
else if (result > 70 && result < 74) {
var link = "mailto:[email protected]"
+ "&subject=" + escape("Spinner")
+ "&body=" + escape(document.getElementById('QUjY2NSN').value)
;
window.location.href = link;
}
else if (result > 73 && result < 76) {
var link = "mailto:[email protected]"
+ "&subject=" + escape("Spinner")
+ "&body=" + escape(document.getElementById('FNVYSHu5').value)
;
window.location.href = link;
}
else if (result > 75 && result < 100) {
alert("Sorry, you won nothing. Please try again tommorow.")
}
else if (result = 100) {
var link = "mailto:[email protected]"
+ "&subject=" + escape("Spinner")
+ "&body=" + escape(document.getElementById('uZ63V4me').value)
;
window.location.href = link;
}
}
</script>
</body>
</html>
That is all of the code. If you know why it is not working, reply please.
A:
You have to pass result to the function otherwise it's out of scope:
function gennum() {
var result=Math.floor(Math.random()*101)
check(result)
}
function check(result) {
...
}
In your case result is defined inside gennum and check has no access to it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Show that the ring $R$ of entire functions does not form a Unique Factorization Domain
Show that the ring $R$ of entire functions does not form a Unique Factorization Domain (U.F.D)
My try:
I will first check whether $R$ forms an Integral Domain then check whether it is Factorization Domain and ultimately a U.F.D.
I.D.
Let $f,g\in R$ be such that $f.g=0$ To check whether $f\equiv0 ;g\equiv 0$ .If I assume that neither $f=0$ or $g=0$ then let $f(x_1)\neq 0;g(x_2)\neq 0$ for some $x_1,x_2\in \mathbb C$.Now since zeros of an analytic function are isolated there will exist open balls $B_1,B_2$ such that $f\neq 0 ,g\neq 0$ on $B_1,B_2$
How to conclude from here that $fg\neq 0$ because it may happen that $B_1\cap B_2=\emptyset $?
How to conclude whether $R$ is UFD or not?
A:
As you note, there is an open set where $f \neq 0.$ On that set, $g\equiv 0,$ and therefore $g \equiv 0$ everywhere. For UFD, you need to know what the irreducibles are. In fact, they are clearly linear polynomials (prove), and since for a UFD factorization you need a FINITE number of factors, functions such as $\sin z$ are NOT uniquely factorizable into irreducibles.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to obtain standard errors of regression coefficients when using `netlm()` in `sna` package?
I run a network regression with netlm() in sna package. All results looks fine. However, I can't find a standard error for each of the coefficients. There are no standard errors in returned model object; summary() also does not export them. Is there any way to get them?
IV0 <- list(SEX, GRADE, YEAR)
M0 <- netlm(K1M, IV0, nullhyp = "qapspp", reps = 2000)
summary.default(M0) ## check structure of returned model object
# Length Class Mode
# coefficients 4 -none- numeric
# fitted.values 812 -none- numeric
# residuals 812 -none- numeric
# qr 4 qr list
# rank 1 -none- numeric
# n 1 -none- numeric
# df.residual 1 -none- numeric
# tstat 4 -none- numeric
# dist 8000 -none- numeric
# pleeq 4 -none- numeric
# pgreq 4 -none- numeric
# pgreqabs 4 -none- numeric
# nullhyp 1 -none- character
# names 4 -none- character
# intercept 1 -none- logical
M0 ## print model object
# OLS Network Model
# Residuals:
# 0% 25% 50% 75% 100%
# -0.3669251 -0.3376203 -0.3066127 0.6623797 0.7340360
# Coefficients:
# Estimate Pr(<=b) Pr(>=b) Pr(>=|b|)
# (intercept) 0.271072656 0.966 0.034 0.0605
# x1 0.009641084 0.602 0.398 0.8360
# x2 -0.031007609 0.169 0.831 0.3440
# x3 0.029304737 0.774 0.226 0.4660
# Residual standard error: 0.47 on 808 degrees of freedom
# Multiple R-squared: 0.002094 Adjusted R-squared: -0.001611
# F-statistic: 0.5651 on 3 and 808 degrees of freedom, p-value: 0.6382
summary(M0) ## print model summary
# Test Diagnostics:
# Null Hypothesis: qapspp
# Replications: 2000
# Coefficient Distribution Summary:
# (intercept) x1 x2 x3
#Min -3.15189 -4.84538 -3.08131 -2.75036
#1stQ -0.65506 -0.99759 -0.65075 -0.68183
#Median 0.01805 -0.09364 0.06947 -0.01831
#Mean 0.02510 -0.03473 0.03247 -0.01179
#3rdQ 0.69636 0.90936 0.72701 0.63639
#Max 3.29170 5.71549 2.71428 2.90498
A:
sna::netlm() does compute those standard errors in order to yield t-score as returned in $tstat, but it does not explicitly return those values. However, it can't be more straightforward to obtain them.
Recall that:
t-score = coefficient / standard.error
Since coefficients and t-score are reported, you can invert this formula to get standard.error:
standard.error = coefficient / t-score
So given your model M0, standard errors for coefficients are just:
with(M0, coefficients / tstat)
My initial answer is to compute those standard errors from the $qr object:
std_coef <- function (model) {
sigma2 <- sum(model$residuals ^ 2) / model$df.residual
Rinv <- backsolve(model$qr$qr, diag(model$rank))
sqrt(rowSums(Rinv ^ 2) * sigma2)
}
std_coef(M0)
This function is designed for lmObject returned by lm(). But since netlm() is based on lm() and also returns the $qr object, we can use it for netlm(), too.
However, as soon as I realize that netlm() returns t-score, I update my answer using that shortcut.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set an item to top when I do Scroll in ListView?
I have a ListView and I would like to do that when I am scrolling and an determinate item goes out of display, it set to top.
Is to do for a ListView of events. I would like the date always was visible.
thanks!
A:
You mean about StickListView?
https://github.com/emilsjolander/StickyListHeaders
| {
"pile_set_name": "StackExchange"
} |
Q:
CDbCommand failed error in MySQL after insert
I have a MySQL database for Group and Member.When I am going to insert any record in Group model, everything is fine here but when I am going to insert any data in Member model it is showing error like this
CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`tbl_groupapp`.`tbl_member`, CONSTRAINT `FK_member_group` FOREIGN KEY (`group_id`) REFERENCES `tbl_group` (`id`) ON DELETE CASCADE). The SQL statement executed was: INSERT INTO `tbl_member` (`firstname`, `lastname`, `gender`, `membersince`) VALUES (:yp0, :yp1, :yp2, :yp3)
I don't know why it is happening here.Here is my database schema
--
-- Table structure for table `tbl_group`
--
CREATE TABLE IF NOT EXISTS `tbl_group` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(80) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=53 ;
--
-- Dumping data for table `tbl_group`
--
INSERT INTO `tbl_group` (`id`, `name`) VALUES
(37, 'Test Group'),
(38, 'bdbsdsb'),
(39, 'ruieryei'),
(40, 'dbshdbs'),
(41, 'dbshdbs'),
(42, 'dbshdbs'),
(43, 'dbshdbs'),
(44, 'dbshdbs'),
(45, 'dbshdbs'),
(46, 'dbshdbs'),
(47, 'dbshdbs'),
(48, 'dbshdbs'),
(49, 'dbshdbs'),
(50, 'group name'),
(51, 'group name'),
(52, 'dbshdbs');
-- --------------------------------------------------------
--
-- Table structure for table `tbl_member`
--
CREATE TABLE IF NOT EXISTS `tbl_member` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`group_id` int(11) NOT NULL,
`firstname` varchar(80) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`lastname` varchar(80) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`gender` varchar(10) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`membersince` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_member_group` (`group_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=52 ;
--
-- Dumping data for table `tbl_member`
--
INSERT INTO `tbl_member` (`id`, `group_id`, `firstname`, `lastname`, `gender`, `membersince`) VALUES
(31, 37, 'First Name', 'Second Name', 'male', '2012-02-22 00:00:00'),
(32, 38, 'dsadsmadnas', 'jieo/uwoe', 'female', '2012-02-16 00:00:00'),
(33, 39, 'rerhejrgejh', 'nmbfdnfb,d', 'male', '2012-02-23 00:00:00'),
(34, 40, 'test group', 'test group', '', '0000-00-00 00:00:00'),
(35, 41, 'test group1', 'test group2', '', '0000-00-00 00:00:00'),
(36, 42, 'test group1', 'test group2', '', '0000-00-00 00:00:00'),
(37, 43, 'test group', 'test group2', '', '0000-00-00 00:00:00'),
(38, 44, 'test group1', 'test group2', '', '0000-00-00 00:00:00'),
(39, 45, 'test group', 'test group2', '', '0000-00-00 00:00:00'),
(40, 46, 'test group', 'test group2', '', '0000-00-00 00:00:00'),
(41, 47, 'test group1', 'test group2', 'male', '0000-00-00 00:00:00'),
(42, 48, 'test group1', 'test group2', 'm', '0000-00-00 00:00:00'),
(43, 49, 'test group1', 'test group2', 'Male', '0000-00-00 00:00:00'),
(44, 50, 'firstname ', 'secondname', 'Male', '0000-00-00 00:00:00'),
(45, 51, 'test group', 'test group', 'Male', '2012-02-28 00:00:00'),
(46, 52, 'test group', 'test group2', 'Male', '2012-02-15 00:00:00');
-- --------------------------------------------------------
--
-- Constraints for table `tbl_member`
--
ALTER TABLE `tbl_member`
ADD CONSTRAINT `FK_member_group` FOREIGN KEY (`group_id`) REFERENCES `tbl_group` (`id`) ON DELETE CASCADE;
Any help and suggestions will be highly appreciable.
Here is the form file for Member
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'member-form',
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'group_id'); ?>
<?php echo $form->textField($model,'group_id'); ?>
<?php echo $form->error($model,'group_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'firstname'); ?>
<?php echo $form->textField($model,'firstname',array('size'=>60,'maxlength'=>80)); ?>
<?php echo $form->error($model,'firstname'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'lastname'); ?>
<?php echo $form->textField($model,'lastname',array('size'=>60,'maxlength'=>80)); ?>
<?php echo $form->error($model,'lastname'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'gender'); ?>
<?php echo $form->textField($model,'gender',array('size'=>10,'maxlength'=>10)); ?>
<?php echo $form->error($model,'gender'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'membersince'); ?>
<?php echo $form->textField($model,'membersince'); ?>
<?php echo $form->error($model,'membersince'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
Controllere Code For Member
<?php
class MemberController extends Controller
{
/**
* @var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='//layouts/column2';
/**
* @return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),
'users'=>array('@'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* @param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new Member;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Member']))
{
$model->attributes=$_POST['Member'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Member']))
{
$model->attributes=$_POST['Member'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* @param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
if(Yii::app()->request->isPostRequest)
{
// we only allow deletion via POST request
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
else
throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('Member');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new Member('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Member']))
$model->attributes=$_GET['Member'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* @param integer the ID of the model to be loaded
*/
public function loadModel($id)
{
$model=Member::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* @param CModel the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='member-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
A:
Looks like you have missed inserting the foreign key group id into the table which is seen from error you are getting, as in, this:
The SQL statement executed was: INSERT INTO tbl_member (firstname, lastname, gender, membersince) VALUES (:yp0, :yp1, :yp2, :yp3)
Basically you have to insert the group_id also, so add group_id input field also to your form for member model.
Lemme know if you need more help.
| {
"pile_set_name": "StackExchange"
} |
Q:
Primary Fermentation - Mold or Yeast by product?
Anyone seen this before? Very light bread mold look only on the surface of primary fermentation. All equipment StarSan’d before use. I’ve been home brewing for many years and never had this happen so, no clue if this batch is ruined. Safe to drink? Also, brewed this 3 weeks ago.
A:
Seems like pieces of a pellicle from bacterial infection. Sanitize everything with bleach, rinse properly with water and then starsan.
| {
"pile_set_name": "StackExchange"
} |
Q:
Error - Keyword not found where expected
I am trying to create a table using following code in oracle 10g and each time I am getting the following error:
ORA-00923: FROM keyword not found where expected
The query is as follows:
Create table Tab2 nologging as
select /*+parallel(a,6)*/ Tab1col1, Tab1col2,
MAX(case when tab1Col5 = '21-aug-2015' then Tab1Col3 end) 21AUGBALANCE,
MAX(case when tab1Col5 = '22-aug-2015' then Tab1Col3 end) 22AUGBALANCE,
MAX(case when tab1Col5 = '23-aug-2015' then Tab1Col3 end) 23AUGBALANCE
from Tab1 a
GROUP BY msisdn, sdp_node
order by msisdn, sdp_node
Table 1 has 5 columns namely tab1Col1, tab1Col2, Tab1Col3, Tab1Col4 and Tab1Col5.
I need to create Tab2 from Tab1 which also has 5 columns 1,2,3,4,5. But what is the error in this code?
A:
try
Create table Tab2 nologging as
select /*+parallel(a,6)*/ Tab1col1, Tab1col2,
MAX(case when tab1Col5 = '21-aug-2015' then Tab1Col3 end) "21AUGBALANCE",
MAX(case when tab1Col5 = '22-aug-2015' then Tab1Col3 end) "22AUGBALANCE",
MAX(case when tab1Col5 = '23-aug-2015' then Tab1Col3 end) "23AUGBALANCE"
from Tab1 a
GROUP BY msisdn, sdp_node
order by msisdn, sdp_node
oracle supports column names starting with numbers, but you have to quote them if you want a column name STARTING with a number.
alternatively, pick different names (e.g. BALANCE21AUG)
| {
"pile_set_name": "StackExchange"
} |
Q:
Synchronizing code with two subversion repositories
A bit of background first:
I am using "base" code from a remote SVN repository, not under my control. The code is not tagged (yet), so I always need to keep up with the trunk.
For a number of reasons (the most important being that our local extensions to the code are of a "niche" nature, and intended to solve a specific problem with the project in which the code is used) I can't use the remote repository to do version control of any modifications I make locally.
I have a local SVN repository in which I am currently doing the "local" versioning.
The problem I'm faced with: I can't figure out if there's a good way to have the code simultaneously synchronized with both repositories. That is, I would like to keep the "remote" version information (so that I can merge in future changes), but I would also like to have "local" version information at the same time (i.e., within the same directory structure).
At the moment I am doing this using two different directories, both containing identical code, but each containing different versioning information. Obviously this is quite a bit of overhead, especially since the code in the two directories needs to be synchronized independently.
Is there a way to do this in subversion? Or do you have suggestions about alternative ways of approaching this?
A:
I did this using git svn, with my development done in a git repository. The remote development is done in subversion. I made a git svn clone of the subversion repository, which I push to a real git repository. A cronjob runs "git svn rebase && git push" every now and again to create a git mirror of the subversion repo.
In order to merge the subversion changes, I have 2 remotes in my local git copy - the "local development" origin and the "from subversion mirror" origin. Whenever I feel the need, I can merge changes from the subversion mirror into our development tree. Local changes are not affected, they live apart and don't mess up the svn mirror.
I used gitosis to set up and administer the git repositories. The steps would be something like this (from memory, may be wrong):
# set up the mirror
git svn clone -s $SVN
git remote add origin git@$MACHINE:svnmirror.git
git push
# + cron job to do git svn rebase && git push every N hours/minutes
# set up the local working copy for development
git clone git://$MACHINE/svnmirror.git
# that's an anonymous, read only clone
# no push to the svn mirror for developers - only cronjob user can push there
git remote add newproject git@$MACHINE:myproject.git
git push newproject
# now do the real deal
git clone git://$MACHINE/myproject.git
# hack hack hack
git push # origin master not needed
git remote add svnmirror git://$MACHINE/svnmirror.git
git merge svnmirror/master
git push
A:
You can have your local repository where you commit your changes, as you already have done. Further you would do a periodic merge from the base repository in order to merge the changes done in the base trunk into your local repository.
The only difficult thing is that you need to keep track of the revisions from which you've already merged from the base repository.
This could look like this:
svn merge -r X:Y baseRepositoryURL // merge from base repo
svn commit // commit the changes to local repo
svn merge -r Y:Z baseRepositoryURL // merge from base repo
svn commit // commit the changes to local repo
Where X is the revision of your initial checkout, Y is the head revision a the time of the first merge and Z is the head revision a the time of the second merge. You see the pattern. Furthermore it is important that you are in the base directory of your local checkout when issueing the commands.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why use divs over tables for a TABLE?
This question at face value is a duplicate of: Divs vs tables for tabular data
BUT I don't think there is a good explanation of WHY someone will ignore what we agree on as standard practice.
It is 2017, tables were inappropriately used for layouting so people say don't use tables, but the exception we know is for visualizing tabular data!
Why is react-table made with divs instead of table/tr/td/th ? https://github.com/react-tools/react-table Certainly some, if not all, 43 contributors know that it shouldn't be divs.
Finally, isn't there an accessibility argument to be made in favor of using the right definition for the job? Wouldn't a screen reader understand that something is a table b/c it uses the term?
A:
Nowadays, tabular data can be formatted nicely with divs and flex box css model. Not 100% as with table, but very close. Additionally, table elements (especially tr) can be styled with css to achieve responsive behavior for mobiles and tablets. At least in most modern web browsers.
So I'd use tables when you need to keep 'rubber' columns (proportionally stretching table heading and table body columns) and use divs when you can make columns with already known width and when semantics is not that important.
| {
"pile_set_name": "StackExchange"
} |
Q:
Midi library for Python on Mac
I'm looking for a python midi library (preferably python3) which will allow me to produce midi commands so that I can control midi instruments on my mac.
I'm also interested in open sound control capabilities but this is less important.
Thanks,
Barry
A:
PyGame is a good starting point.
| {
"pile_set_name": "StackExchange"
} |
Q:
can't find the function/method on PHP files
Possible Duplicate:
How to find out where a function is defined?
I am working on a php project which I have to do some styling and I've been trying to search for string using Sublime Text's "find in files". The text is a function name used like:
echo advspecial();
but it seems "advspecial" doesnt exist. I tried renaming advspecial just to test if its a function then I get an error "Call to undefined function"
My question is, why can't I find it in the files? Could it be inside a mySQL database?
A:
If you are running this locally, try viewing the page and seeing if the error appears. If it shows an error then the function is probably defined in a file that you forgot or from a remote source.
If there is no error, then the function exists somewhere in your project, and Sublime is probably just experiencing a glitch.
There is no way that the function could be defined inside of a database.
| {
"pile_set_name": "StackExchange"
} |
Q:
raspberry pi hangs after 2-3 days of continous use
I am using latest the Raspbian Wheezy release with kernel 3.10. I am running four Python programs 24 hours/day on the Raspberry Pi. Three programs out of four are like background services, which consume at the maximum 2.4% CPU and around 1.2% memory each. The fourth Python code is a pygame application that is displayed on a 1920x1080 screen, which consumes about 50% CPU and 2.4% memory. Thus in total when I am running all 4 programs total memory used is 90 MB and 60% CPU is in use all the time.
The problem is that Raspberry Pi suddenly hangs (no response the keyboard nor mouse, and I'm also not able to ping) after 2-3 days and thus we have to reboot it forcefully. What could be the reason for it to hang? There is no problem of a memory leak since even after 2-3 days the total memory usage and CPU usage is unchanged.
A:
What do you mean by "hang"? I had problems with my headless pi that every 2-3 days I could not connect to it. It was working ok but I could not ping nor ssh to it.
Turned out to be a problem with the power management in the wifi dongle:
http://www.raspberrypi.org/phpBB3/viewtopic.php?t=51543&p=397663
Once I turned of the power management features as described in the link it worked continuously again
| {
"pile_set_name": "StackExchange"
} |
Q:
USB as a host Data Transfer problems for SCSI READ command
I am implementing USB as a host using OHCI. And using SCSI to read a mass storage device.
All my control transfers run successfully. I have done all the initialization using Control Transfers however I am facing problem with Data Transfers.
I am having troubles in successfully implementing the READ command in SCSI, be it READ(6), READ(10), etc.
The following is a snapshot of the Command Block Wrapper(CBW)-
The highlighted portion is the SCSI command.
As You can see I have requested 512 bytes- which is the size of 1 LBA for my mass storage device.
The following is what comes in the 512 byte buffer from the device-
FYI- The buffer was initialized to 0xff
These 512 bytes are not present anywhere on my mass storage device. I opened the mass storage device on HXD and checked the bytes to see that the block I received doesnt exist on my mass storage!
And the Command Status Wrapper (CSW) I got was as follows-
Last byte in CSW is 0x01 which means the command failed.
I have 3 questions
1- What could be the reason why this READ is failing? Am I supposed to run any other SCSI command before this for any reason?
2- I request for 512 bytes and I even get that but the bytes 8-11 in CSW which show residue still show a certain value a which happens to be greater than 512 (as this is little endian format). How is this possible?
3- What could the 512 bytes I receive from the device possibly be?
Any helps with this I have been stuck here for a looong time now and I dont have a USB analyzer.
Pseudo code for Data Transfers-
Set the Endpoint Descriptor (ED) 1 (Indication the OUT Endpoint)
Set the Transfer Descriptor (TD) 1 (Send SCSI command)
Set the BulkHead ED to ED 1
Start the descriptor processing
and then
stop it
Set the Endpoint Descriptor (ED) 1 (Indication the IN Endpoint)
Set the Transfer Descriptor (TD) 1 (Read the 512 bytes)
Set the Transfer Descriptor (TD) 2 (Read the 13 CSW bytes)
Set the BulkHead ED to ED 1
Start the descriptor processing
and then
stop it
A:
These 512 bytes are not present anywhere on my mass storage device.
No, this looks very much like a valid sector 0 to me.
What you probalbly miss ist that Windows does not allow a non-admin user to look at this sector at all. HXD thus shows you the first sector of the partition, which is not sector 0. You would see this only with admin priviliges and when opening the corresponding physical disk.
I request for 512 bytes and I even get that but the bytes 8-11 in CSW which show residue still show a certain value a which happens to be greater than 512
No, you request 256*512 bytes. The byte order for those SCSI length fields is AFAIK big endian.
| {
"pile_set_name": "StackExchange"
} |
Q:
Toolbar when extending Activity
I need to extend Activity and not ActionBarActivity or AppCompatActivity in order to use a third party library.
In all the app I've been using AppCompatActivity in order to easily add a Toolbar in it, but apparently I cannot do the same if I extend Activity. I'd be also happy just to have an ActionBar: it's not the same, but it's better than nothing. Still, I don't know how to do it :-/
Do you have any advice for me? I know it's a silly question probably but I just don't know how to make this work...
A:
First of all check the library you are using. It can be outdated.
With the new 22.1+ appcompat you can use the AppCompatDelegate to extend AppCompat's support to any Activity.
You can check this official link to AppCompatPreferenceActivity, where you can find an example of this technique.
You have :
to add the Toolbar to your Activity:
Something like this:
<android.support.v7.widget.Toolbar
android:id="@+id/mytoolbar"
android:background="?attr/colorPrimary"/>
to use a AppCompat Theme without ActionBar.
something like this:
<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
<item name="colorPrimary">@color/myColor</item>
....
</style>
Add AppCompatDelegate to your Activity
Something like:
public class MainActivity extends Activity implements AppCompatCallback {
private AppCompatDelegate delegate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//create the delegate
delegate = AppCompatDelegate.create(this, this);
//call the onCreate() of the AppCompatDelegate
delegate.onCreate(savedInstanceState);
//use the delegate to inflate the layout
delegate.setContentView(R.layout.activity_main);
//add the Toolbar
Toolbar toolbar= (Toolbar) findViewById(R.id.mytoolbar);
delegate.setSupportActionBar(toolbar);
}
//.....
}
Check the official example to wrap other methods of your Activity to have a full compatibility with AppCompatActivity.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is the Empty Base Class Optimization now a mandatory optimization (at least for standard-layout classes)?
According to C++11 9.1/7 (draft n3376), a standard-layout class is a class that:
has no non-static data members of type non-standard-layout class (or array of such types) or reference,
has no virtual functions (10.3) and no virtual base classes (10.1),
has the same access control (Clause11) for all non-static data members,
has no non-standard-layout base classes,
either has no non-static data members in the most derived class and at most one base class with non-static data members, or has no base classes with non-static data members, and
has no base classes of the same type as the first non-static data member.
it follows that an empty class is a standard-layout class; and that another class with an empty class as a base is also a standard-layout class provided the first non-static data member of such class is not of the same type as the base.
Furthermore, 9.2/19 states that:
A pointer to a standard-layout struct object, suitably converted using a reinterpret_cast, points to its initial member (or if that member is a bit-field, then to the unit in which it resides) and vice versa. [ Note: There might therefore be unnamed padding within a standard-layout struct object, but not at its beginning, as necessary to achieve appropriate alignment. —end note]
This seems to imply that the Empty Base Class Optimization is now a mandatory optimization, at least for standard-layout classes. My point is that if the empty base optimization isn't mandated, then the layout of a standard-layout class would not be standard but rather depend on whether the implementation implements or not said optimization. Is my reasoning correct, or am I missing something?
A:
Yes, you're correct, that was pointed out in the "PODs revisited" proposals: http://www.open-std.org/jtc1/sc22/WG21/docs/papers/2007/n2342.htm#ABI
The Embarcadero compiler docs also state it: http://docwiki.embarcadero.com/RADStudio/en/Is_standard_layout
Another key point is [class.mem]/16
Two standard-layout struct (Clause 9) types are layout-compatible if they have the same number of non-static data members and corresponding non-static data members (in declaration order) have layout-compatible types (3.9).
Note that only data members affect layout compatibility, not base classes, so these two standard layout classes are layout-compatible:
struct empty { };
struct stdlayout1 : empty { int i; };
struct stdlayout2 { int j; };
| {
"pile_set_name": "StackExchange"
} |
Q:
c# regex.ismatch using a variable
I have the following code which works fine but i need to replace the site address with a variable...
string url = HttpContext.Current.Request.Url.AbsoluteUri; // Get the URL
bool match = Regex.IsMatch(url, @"(^|\s)http://www.mywebsite.co.uk/index.aspx(\s|$)");
I have tried the following but it doesn't work, any ideas???
string url = HttpContext.Current.Request.Url.AbsoluteUri; // Get the URL
string myurl = "http://www.mywebsite.co.uk/index.aspx";
bool match = Regex.IsMatch(url, @"(^|\s)"+myurl+"(\s|$)");
A:
You are missing a @:
bool match = Regex.IsMatch(url, @"(^|\s)" + myurl + @"(\s|$)");
The reason that you need the extra @ is because the @ applies only to the string literal immediately following it. It does not apply to the entire rest of the line.
You should also consider escaping your URL:
bool match = Regex.IsMatch(url, @"(^|\s)" + Regex.Escape(myurl) + @"(\s|$)");
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I update an android sqlite database column value to null using ContentValues?
For example, I want to do the following on a database update.
Is there a constant I can use instead of null, which won't compile if I use it like:
ContentValues args = new ContentValues();
args.put(KEY_RISK_AMOUNT, null); // what constant do I use instead of null?
A:
Use ContentValues.putNull(java.lang.String):
ContentValues args = new ContentValues();
args.putNull(KEY_RISK_AMOUNT);
| {
"pile_set_name": "StackExchange"
} |
Q:
How do i find the download link for the newest version of (asp).net core for raspbian?
I know there's https://dotnet.microsoft.com/download for most Linux versions, but I wasn't able to get any of them running on my Raspberry. I was lucky to find a blog with the direct link for wget.
I'm not asking for current links, I'm asking for how i can get the current stable version for future releases, or even better where i find links for every version available.
A:
Look at the real download page: https://dotnet.microsoft.com/download/dotnet-core/3.0
You can find links to ".NET Core binaries" under the "Linux" section for each release on that page.
These are not stable links - each time there is a release, you will have to look and and find the link to the latest release (a new row in the table) manually.
You should use the "ARM64" or "ARM32" links depending on what your Raspberry Pi version is.
These binaries are "portable", meaning they should work irrespective of what distro you are using (as long as it's a recent-enough distro).
| {
"pile_set_name": "StackExchange"
} |
Q:
Dynamic properties in Java from xml
I'm fiddling around with an idea but can't get a grip on it.
I have an xml file with 100+ properties defining the runtime environment of a somewhat large program. These are exposed as variables through a class . At the moment, for each option in the xml file, there is a variable in the class plus public getter and private setter.
Each time we need a new option, we have to define it in the xml file and create the variable plus methods in the RuntimenEnvironment class.
Now, what I would like to do is something like this: I want to rewrite the class in such a way, that it exposes new options from the xml file as vars without having to touch the class.
My xml file uses this structure:
<option>
<name>theName</name>
<type>eg int</type>
<value>20</value>
<constant>THE_NAME</constant>
</option>
Can I write code in java that dynamically creates the vars at runtime and exposes them through a method without actually writing the method?
Is this possible?
Thanks in advance,
Chris
A:
Couple of options I could think of are:
If the name is unique a map can be populated with name as the key.
If you are interested only in options then a list of Options can be
populated from the XML.
Below is the sample code implemented with SAX parser
Handler Class
public class OptionsParser extends DefaultHandler {
private final StringBuilder valueBuffer = new StringBuilder();
private final Map<String, Option> resultAsMap = new HashMap<String, Option>();
private final List<Option> options = new ArrayList<Option>();
//variable to store the values from xml temporarily
private Option temp;
public List<Option> getOptions() {
return options;
}
public Map<String, Option> getResultAsMap() {
return resultAsMap;
}
@Override
public void startElement(final String uri, final String localName, final String qName,
final Attributes attributes) throws SAXException {
if("option".equalsIgnoreCase(qName)) {
temp = new Option();
}
}
@Override
public void endElement(final String uri, final String localName, final String qName)
throws SAXException {
//read the value into a string to set them to option object
final String value = valueBuffer.toString().trim();
switch (qName) {
case "name":
temp.setName(value);
// set the value into map and name of the option is the key
resultAsMap.put(value, temp);
break;
case "type":
temp.setType(value);
break;
case "value":
temp.setValue(value);
break;
case "constant":
temp.setConstant(value);
break;
case "option":
// this is the end of option tag add it to the list
options.add(temp);
temp = null;
break;
default:
break;
}
//reset the buffer after every iteration
valueBuffer.setLength(0);
}
@Override
public void characters(final char[] ch, final int start, final int length)
throws SAXException {
//read the value into a buffer
valueBuffer.append(ch, start, length);
}
}
Option POJO
public class Option {
private String name;
private String type;
private String value;
private String constant;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getConstant() {
return constant;
}
public void setConstant(String constant) {
this.constant = constant;
}
}
Input XML
<options>
<option>
<name>option1</name>
<type>int</type>
<value>20</value>
<constant>const1</constant>
</option>
<option>
<name>option2</name>
<type>string</type>
<value>testValue</value>
<constant>const2</constant>
</option>
</options>
Sample Main class
public class ParseXML {
public static void main(String[] args) {
final OptionsParser handler = new OptionsParser();
try {
SAXParserFactory.newInstance().newSAXParser()
.parse("C:/luna/sample/inputs/options.xml", handler);
} catch (SAXException | IOException | ParserConfigurationException e) {
System.err.println("Somethig went wrong while parsing the input file the exception is -- " + e.getMessage() + " -- ");
}
Map<String, Option> result = handler.getResultAsMap();
Collection<Option> values = result.values();
for (Option option : values) {
System.out.println(option.getName());
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the best way to store different types of data with a Promise.all?
population: {[id: number]} = {}
places: {[id: string]} = {}
const promises = ['/api/population',
'/api/data/Country',
'/api/data/State',
'/api/data/County']
.map(api => fetch(api)
/api/population should be stored in variable population.
Country, State and County should be stored in places.
I would like to store the data in its corresponding variable, what is the best way to do this using Promise.all(). How can I do this with foreach?
A:
Promise.all resolves with an array of its results wherein each result corresponds positionally to the input promise which resolved with it.
The most convenient way to assign the results to distinct identifiers is to use JavaScript's array destructuring syntax.
With async/await
const [populations, countries, states, counties] = await Promise.all([
'/api/population',
'/api/data/Country',
'/api/data/State',
'/api/data/County'
].map(api => fetch(api)));
With .then
Promise.all([
'/api/population',
'/api/data/Country',
'/api/data/State',
'/api/data/County'
].map(api => fetch(api)))
.then(([populations, countries, states, counties]) => { });
To assign to identifiers that have already been declared, you can write
[populations, countries, states, counties] = await Promise.all([
'/api/population',
'/api/data/Country',
'/api/data/State',
'/api/data/County'
].map(api => fetch(api)));
| {
"pile_set_name": "StackExchange"
} |
Q:
NgIf if property is not undefined?
There is a structure directive ngIf:
<tr *ngIf="p.taxbalance">
</tr>
Problem is that there is no property taxbalance in object p.
ERROR TypeError: Cannot read property 'taxbalance' of undefined
I tried to use this signature:
<tr *ngIf="p?.taxbalance"></tr>
But it does not work too
A:
Try $any() type cast function
you can use the $any() cast function to cast the expression to the any type
<tr *ngIf="$any(p).taxbalance"></tr>
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does my ajax call fail when an almost identical one succeeds?
I have this HTML
<a href="/noJavascript" id="rejoinGroups">Rejoin</a>
<a href="/noJavascript" class="removeGroup" id="Testing">Remove</a>
and I am binding the links to a function using unobstrusive javascript like so:
$(function SetUp()
{
var el = document.getElementById('rejoinGroups');
el.onclick = rejoinGroups;
var removeElements = document.getElementsByClassName('removeGroup');
for (var i = 0; i < removeElements.length; i++) {
removeElements[i].onclick = function() {
removeGroup(this.id);
}
}
});
There may be many 'Remove' link generated hence why I am binding it differently, (but currently I have only one), and am passing the id as the function parameter.
These are the functions I am biding to. I have deliberately made them identical for testing as the first one (with the groupName parameter) doesn't work, but the second one does and I don't understand why. Once this issue is fixed I'll actually use the groupName parameter. The second returns a 200 code and the first immediately gives an 'Error0' message, then goes to the /noJavascript page. I can only assume it's something to do with the parameter, but it seems to be set correctly, so I'm not sure what it is. What am I missing?
function removeGroup(groupName){
$.ajax({
url: '/tasks/aTask',
type: 'POST',
data: {userId:38},
success: function(data, textStatus, jqXHR)
{
alert(jqXHR.status);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("Error" + jqXHR.status);
}
});
return false;
}
function rejoinGroups(){
$.ajax({
url: '/tasks/aTask',
type: 'POST',
data: {userId:38},
success: function(data, textStatus, jqXHR)
{
alert(jqXHR.status);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("Error" + jqXHR.status);
}
});
return false;
}
this is what I get in the chrome dev window for the second function:
Request URL:http://localhost:8888/tasks/aTask
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Connection:keep-alive
Content-Length:9
Content-Type:application/x-www-form-urlencoded
Cookie:[email protected]:true:18580476422013912411; JSESSIONID=10yktze1j72fa
Host:localhost:8888
Origin:http://localhost:8888
Referer:http://localhost:8888/users/38
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.79 Safari/535.11
X-Requested-With:XMLHttpRequest
Form Dataview URL encoded
userId:38
Response Headersview source
Content-Length:0
Server:Jetty(6.1.x)
and this is what I get for the first (failing) one:
Request URL:http://localhost:8888/tasks/aTask
Request Headersview source
Accept:*/*
Content-Type:application/x-www-form-urlencoded
Origin:http://localhost:8888
Referer:http://localhost:8888/users/38
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.79 Safari/535.11
X-Requested-With:XMLHttpRequest
Form Dataview URL encoded
userId:38
A:
I'm not very sure, but I think it might be because your anonymous function is not returning the result of the function. Try changing:
removeGroup(this.id);
to
return removeGroup(this.id);
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it good or bad practice to create alternate styles of rows(eg:alternate background color) in ListView using separate xml?
For example,to create alternate layout in ListView which uses different alternate color :
<LinearLayout
android:id="@+id/view1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/textview_publish_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TextView>
</LinearLayout>
I can set the color at the getView method:
MyActivity.this.findViewById(R.id.view1).setBackgroundColor(position%2=0?Color.RED.Color.BLUE);
But I would rather copy and place same layout file:
row_style1.xml
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FF0000"
android:orientation="vertical">
<TextView
android:id="@+id/textview_publish_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TextView>
</LinearLayout>
row_style2.xml
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#0000FF"
android:orientation="vertical">
<TextView
android:id="@+id/textview_publish_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TextView>
</LinearLayout>
and then inflate different layouts at the getView method:
view=LayoutInflater.from(MyFragment.this.getActivity()).inflate(i%2==0?R.layout.row_style1:R.layout.row_style2,null);
I think it is more maintainable because it separate more style concerns from code, especially when there is more different styles between different parts, eg:
findViewById(R.id.view1).setBackgroundColor(position%2=0?Color.RED.Color.BLUE);
findViewById(R.id.view2).setBackgroundColor(position%2=0?Color.YELLOW.Color.GREEN);
which can be simplified by inflating different layouts. Is it good or bad practice to do this?
A:
Generally speaking, if it's reasonable to expect that the overall structure of each row is going to remain the same in both cases, then by introducing repetition (two separate, but similar, layout files), you also introduce a dependency between the two (you need to remember to change both files every time). If you consider just the layout files by themselves, that's less maintainable. But you may be willing to pay that cost if it gets you some other, sufficiently valuable design benefit. (As a side note: When it comes to good/bad practices, try to understand the "why" behind them; once you do that, you can decide if they make sense for your particular case. Depending on your experience, you may not always be able to do that, but it's a good idea to try.)
You could also use a single layout file, that leaves android:background undefined. Then you'd define the two colors as resources (in res/values/colors.xml), and set them from code, by either getting preexisting views as before, or by inflating the single layout, and then setting the background color on the resulting view. This way you avoid having two codependent layout files, and you avoid hardcoding the background colors.
Another approach would be (I should mention) to create a custom component, where you'd have full control, but that's probably not worth the effort in this case.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using BPF with SOCK_DGRAM on Linux machine
Is it possible to filter packets using BPF on datagram socket?
No error occures when I try to attach a filter, but I don't receive any packet.
I compiled a filter using libpcap, and the filter works with tcpdump.
Here is shortened version of my code:
static const char filter[] = "udp[8] == 0x00";
int sock = socket(AF_INET, SOCK_DGRAM, 0);
pcap_t *pcap = pcap_open_dead(DLT_RAW, 1024);
struct bpf_program bpf_prog;
pcap_compile(pcap, &bpf_prog, filter, 0, PCAP_NETMASK_UNKNOWN);
struct sock_fprog linux_bpf = {
.len = bpf_prog.bf_len,
.filter = (struct sock_filter *) bpf_prog.bf_insns,
};
setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &linux_bpf, sizeof(linux_bpf));
My machine is ubuntu 12.04 x86.
A:
well, after some tests and trials, it is possible.
however, libpcap does not support it directly.
what should be done is open a pcap handler specifying ethernet data type, and then access the bytes in the udp packet as if you access the ethernet packet.
the filter offsets start from the beginning of the packet, but the 'packet' depends on the layer you opened the socket for.
if one opens socket with SOCK_DGRAM, the bpf instruction ldb 0 will load the first byte of the udp header. so when accessing ether[0] in the filter libpcap will compile it to ldb 0 which is what we want.
so, the corrected code should be something like this:
static const char filter[] = "ether[8] == 0x00";
int sock = socket(AF_INET, SOCK_DGRAM, 0);
pcap_t *pcap = pcap_open_dead(DLT_EN10MB, 1024);
struct bpf_program bpf_prog;
pcap_compile(pcap, &bpf_prog, filter, 0, PCAP_NETMASK_UNKNOWN);
struct sock_fprog linux_bpf = {
.len = bpf_prog.bf_len,
.filter = (struct sock_filter *) bpf_prog.bf_insns,
};
setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &linux_bpf, sizeof(linux_bpf));
| {
"pile_set_name": "StackExchange"
} |
Q:
System.Collections.Generic.List size in memory
Just wondering if anyone has ever tried to determine the actual size of a System.Collections.Generic.List in memory?
I am currently caching one such object using System.HttpRuntime.Cache which seems to work well but I'd love to be able to determine the actual impact on my server.
using (System.IO.MemoryStream stream = new System.IO.MemoryStream(capacity))
{
new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter().Serialize(stream, obj);
thisSerialized = stream.ToArray();
return thisSerialized.Length;
}
This works for others but not for what I need.
A:
The serialized size of the list will be totally irrelevant.
A List<T> will have a bit of overhead (two ints), and an array of size Capacity.
Arrays of reference types use IntPtr.Size (4 or 8) bytes of memory per element; arrays of value types use Marshal.SizeOf(type) bytes of memory per element.
(Arrays also have a bit of overhead)
Any reference types inside of the list (or in structs in the list) will use memory separately.
| {
"pile_set_name": "StackExchange"
} |
Q:
CSS Multi-column Layout - Chrome does not allow to have the right column longer than the left?
i just coded my website. I am a photographer so all my content are pictures.
Every single picture is organized in a div- Box.
I used a flexible multi-column Layout:
.content {
-webkit-column-count: 2;
-moz-column-count: 2;
column-count: 2;
max-width:1400px;
}
Explorer and Firefox works perfect, but Chromedoes not allow the right column to be longer than the left and it looks horrible:
http://www.rosioffenbach.com/tarotpt1.html
A looooooot of whitespace at the right side.
I am very thankful for your help.
I have to say that I am a beginner.
I tried
-webkit-column-fill: balance;
-webkit-column-fill: balance-all;
But i did not work
.content {
width:70%;
position: relative;
margin-right: auto;
margin-left: auto;
padding-top:1%;
max-width:1400px;
}
.content {
-webkit-column-count: 1;
-webkit-column-gap: 3%;
-moz-column-count: 1;
-moz-column-gap: 3%;
column-count: 1;
column-gap: 3%;
}
I want that as in firefox and explorer the columns are as equal as possible, and that includes the option that the right column is longer than the left.
A:
Try removing display: inline-block from .contentstrecke{ }. After that removal, Firefox and Chrome look identical.
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating a LabelFrame inside a Tkinter Canvas
I'm trying to place a LabelFrame which displays a Label inside a Canvas however I receive this error:
TclError: can't use .28425672.27896648 in a window item of this canvas
Here's my code:
from Tkinter import LabelFrame, Label, Tk, Canvas
root = Tk()
canvas = Canvas(root)
canvas.pack()
label_frame = LabelFrame(text="I'm a Label frame")
label = Label(label_frame,text="Hey I'm a Label")
canvas.create_window(10,20,window=label)
root.mainloop()
A:
Make the label_frame child of the canvas, and pack the label inside the frame. Then pass label_frame (instead of label) to create_window .
...
label_frame = LabelFrame(canvas, text="I'm a Label frame")
label = Label(label_frame, text="Hey I'm a Label")
label.pack()
canvas.create_window(10, 20, window=label_frame, anchor='w')
...
anchor is CENTER by default. To correctly align, specify anchor as w.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to access a property of an object using the bracket notation in TypeScript strict mode
The following TypeScript sample code shows an error Element implicitly has an 'any' type because type '{one: number; two: number;}' has no index signature in the line const one = obj[prop]; in strict mode.
The compiler allows the line const two = obj[propName];, so I cannot understand why the error is shown or how to generally speaking access a property of an object using the bracket notation.
const obj = { one: 1, two: 2 };
const props = { one: 'one', two: 'two' };
// it is not possible add or change any properties in the props object
props.zero = 'zero';
props.one = 1;
// prop has the type string
const prop = props.one;
// using the bracket notation fails with the following error message:
// Element implicitly has an 'any' type because type '{one: number; two: number;}' has no index signature.
// const prop: string
const one = obj[prop];
// this works because propName is of type 'two'
const propName = 'two';
const two = obj[propName];
A:
Element implicitly has an 'any' type because type '{one: number; two: number;}' has no index signature
Your object has no index signature, it has two named properties.
The compiler allows the line const two = obj['two'];
It allows the names of your properties, that's why obj['two'] and obj['one'] will work.
and the const prop is a string, so I cannot understand why the error is shown
Because a string can have much more values that just 'one' or 'two' and so the compiler cannot ensure, your object[myString] call will work. It's only valid for two defined string values.
how to generally speaking access a property of an object using the bracket notation.
This would work:
const prop: 'one' | 'two' = 'one';
const test = obj[prop]
You say: prop has value 'one' or 'two' and so the compiler knows your obj[prop] will always be valid.
or
class Example {
one: string;
two: string;
}
const prop: keyof Example = 'one';
const test = obj[prop];
Here keyof(ClassName) tells the compiler, that your prop var will have an existing property name of Example.
The above examples assume, that you have an object where only the properties named 'one' and 'two' are valid. If you want to use your object in a "dictionary style", tell typescript about that and add an index signature:
const obj: {[key:string]: string;} = { one: 'one' };
const text = obj[myString];
Now obj allows every string values as key.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sitecore core index is rebuilding continuously
We are seeing continuous logs are logged for sitecore_core indexing with zero item processed in log file. What is the solution to fix the issue?
Logs:
ManagedPoolThread #2 04:09:29 INFO Job started: Index_Update_IndexName=sitecore_core_index
ManagedPoolThread #2 04:09:29 INFO Job ended: Index_Update_IndexName=sitecore_core_index (units processed: )
ManagedPoolThread #7 04:09:29 INFO Job started: Index_Update_IndexName=sitecore_core_index
ManagedPoolThread #7 04:09:29 INFO Job ended: Index_Update_IndexName=sitecore_core_index (units processed: )
ManagedPoolThread #10 04:09:29 INFO Job started: Index_Update_IndexName=sitecore_core_index
ManagedPoolThread #10 04:09:29 INFO Job ended: Index_Update_IndexName=sitecore_core_index (units processed: )
ManagedPoolThread #9 04:09:29 INFO Job started: Index_Update_IndexName=sitecore_core_index
ManagedPoolThread #9 04:09:29 INFO Job ended: Index_Update_IndexName=sitecore_core_index (units processed: )
ManagedPoolThread #9 04:09:29 INFO Job started: Index_Update_IndexName=sitecore_core_index
ManagedPoolThread #9 04:09:30 INFO Job ended: Index_Update_IndexName=sitecore_core_index (units processed: )
ManagedPoolThread #19 04:09:30 INFO Job started: Index_Update_IndexName=sitecore_core_index
ManagedPoolThread #19 04:09:30 INFO Job ended: Index_Update_IndexName=sitecore_core_index (units processed: )
ManagedPoolThread #4 04:09:30 INFO Job started: Index_Update_IndexName=sitecore_core_index
ManagedPoolThread #4 04:09:30 INFO Job ended: Index_Update_IndexName=sitecore_core_index (units processed: )
ManagedPoolThread #1 04:09:30 INFO Job started: Index_Update_IndexName=sitecore_core_index
ManagedPoolThread #1 04:09:30 INFO Job ended: Index_Update_IndexName=sitecore_core_index (units processed: )
ManagedPoolThread #1 04:09:30 INFO Job started: Index_Update_IndexName=sitecore_core_index
ManagedPoolThread #1 04:09:30 INFO Job ended: Index_Update_IndexName=sitecore_core_index (units processed: )
ManagedPoolThread #1 04:09:30 INFO Job started: Index_Update_IndexName=sitecore_core_index
ManagedPoolThread #1 04:09:30 INFO Job ended: Index_Update_IndexName=sitecore_core_index (units processed: )
ManagedPoolThread #6 04:09:30 INFO Job started: Index_Update_IndexName=sitecore_core_index
ManagedPoolThread #6 04:09:30 INFO Job ended: Index_Update_IndexName=sitecore_core_index (units processed: )
ManagedPoolThread #17 04:09:30 INFO Job started: Index_Update_IndexName=sitecore_core_index
ManagedPoolThread #17 04:09:30 INFO Job ended: Index_Update_IndexName=sitecore_core_index (units processed: )
ManagedPoolThread #15 04:09:30 INFO Job started: Index_Update_IndexName=sitecore_core_index
ManagedPoolThread #15 04:09:30 INFO Job ended: Index_Update_IndexName=sitecore_core_index (units processed: )
ManagedPoolThread #16 04:09:30 INFO Job started: Index_Update_IndexName=sitecore_core_index
ManagedPoolThread #16 04:09:30 INFO Job ended: Index_Update_IndexName=sitecore_core_index (units processed: )
A:
There are a few steps involved in order to troubleshoot and fix this issue.
Step 1:
The first step would be to check what index update strategy is used for sitecore_core_index. You can search for <index id="sitecore_core_index" on /sitecore/admin/showconfig.aspx page, <strategies node.
By default, IntervalAsynchronousStrategy index update strategy is configured for it.
When this strategy is used, an index will be updated based on a time interval rather than OnPublishEnd event. The interval is configured in Sitecore.ContentSearch.DefaultConfigurations.config config file. By default, the index update will be triggered every minute.
<intervalAsyncCore type="Sitecore.ContentSearch.Maintenance.Strategies.IntervalAsynchronousStrategy, Sitecore.ContentSearch">
<param desc="database">core</param>
<param desc="interval">00:01:00</param>
<CheckForThreshold>true</CheckForThreshold>
</intervalAsyncCore>
Step 2:
Verify that the interval parameter is set to a value that will not
cause unnecessarily frequent updates, and adjust it to fit your
needs. sitecore_core_index is considered to be a less critical
index that you do not need to updat frequently.
Verify that this index update strategy is not combined with other strategies that it
is not compatible with (e.g. SynchronousStrategy). For more information about this and other index update
strategies, please refer to this Sitecore documentation page.
Step 3:
The next step can be to change log level for Crawling Log to DEBUG (only for a short period of time while troubleshooting). The values is stored in Sitecore.ContentSearch.config config file.
<logger name="Sitecore.Diagnostics.Crawling" additivity="false">
<level value="DEBUG"/>
<appender-ref ref="CrawlingLogFileAppender"/>
</logger>
And verify Crawling.log.txt log files for more information on the issue why the index is updated so frequently. If there is an issue, it will be logged. (e.g. EventQueue, Solr connectivity, etc.)
Step 4:
The strategy uses EventQueue table in core database. It is possible that EventQueue table gets flooded with lots of events. Two admin pages can be verified to see details on running, queued and finished jobs and EventQueue statistics:
/sitecore/admin/Jobs.aspx
/sitecore/admin/EventQueueStats.aspx
If the aforemntioned two pages will not provide enough info, you can run this SQL query on your EventQueue table in Core database for more details, it will show events for updating sitecore_core_index:
SELECT TOP (10000) [Id]
,[EventType]
,[InstanceType]
,[InstanceData]
,[InstanceName]
,[RaiseLocally]
,[RaiseGlobally]
,[UserName]
,[Stamp]
,[Created]
FROM [db_Core].[dbo].[EventQueue]
WHERE InstanceData = '{"FullRebuild":false,"IndexName":"sitecore_core_index"}'
On Jobs.aspx page, verify if Index_Update_IndexName=sitecore_core_index job is queued many times in a short period of time.
Additionally, please refer to this KnowledgeBase article, it provides similar details provided above.
Update:
The reason why the log file shows that zero units were processed during index update job is because it is a bug. INFO-level log records for index update job will only be shown in log.txt files when an index was actually updated. If the update strategy was executed and the EvenQueue is empty, it will only add DEBUG-level log record to Crawling.log.txt file, without adding an INFO-level log records (the one you have provided above):
33056 21:42:02 DEBUG [Index=sitecore_core_index] IntervalAsynchronousStrategy executing.
33056 21:42:02 DEBUG [Index=sitecore_core_index] Event Queue is empty. Incremental update returns
That means that by default an INFO-level log record for index update job should always contain a certain number of processed units, greater than zero.
Therefore, in the log file chunk you have provided, instead of showing zero processed units, it should have displayed some other number greater than zero.
Sitecore Support has registered this as a bug. Unfortunately, there is no easy way to fix this and display the correct number of items. To track the future status of this bug report, please use the reference number 95080.
| {
"pile_set_name": "StackExchange"
} |
Q:
Error using StaticResource as Storyboard for a VisualTransition
I have a VisualTransition inside of a VisualStateGroup for a Button control. The Storyboard property is bound to a StaticResource Storyboard:
<VisualTransition From="MyLock" To="Unlocked" GeneratedDuration="0:0:2.0" Storyboard="{StaticResource Storyboard_Locked_ToUnlocked}"/>
When I go to the "Unlocked" state using the VisualStateManager, I get the following exception:
"System.InvalidOperationException: Specified value of type 'System.Windows.Media.Animation.Storyboard' must have IsFrozen set to false to modify."
Nothing in the Storyboard is modifying the Storyboard itself so I'm not sure what this means.
Two strange things. Number one, this did not start happening until migrating from VS 2010 to VS 2012 and installing the .Net 4.5 framework. Second, if I copy all of the code and move it into the Storyboard property itself inside a tag, I do not get the error. So it appears to not be anything in the Storyboard itself, just a problem with using a StaticResource for this.
When researching, the only thing I could find about the error dealt with subscribing to the Completed event of the storyboard, which I am not doing anywhere, unless VisualStateManager is doing this somehow.
Thanks in advance for any help.
Edit: I should also add that I want to use this in two different transitions, and that is why I would prefer it to be a StaticResource so I don't have to copy/paste the xaml. I commented out one of the transitions and still got the error so it's not the fact that I'm sharing it either.
A:
To anyone else who runs into this issue, I have found a solution.
Simply changing the Storyboard to not be shared allows it to be created for each animation call, which gets rid of this error. Set x:Shared to False on the Storyboard to do this:
<Storyboard x:Shared="False" x:Key="Storyboard_Locked_ToUnlocked">
| {
"pile_set_name": "StackExchange"
} |
Q:
ZF2 Inner join with where clause returns empty result
When I try the follow mysql query in send I just get back an empty results set (who suposed to be filled).
I tried the follow query in my mysql workbench (gives a results back)
SELECT `websites`.*, `s`.`website_id` AS `websites.id`
FROM `websites`
INNER JOIN `websites_statistics` AS `s` ON `s`.`website_id` = `websites`.`id`
WHERE `websites`.`website` = 'google.com' LIMIT 0,1
And this one in my ZF2 application (empty result set)
$sql = new Sql($this->tableGateway->getAdapter());
$select = $sql->select();
$select->from('websites')
->join(array('s' => 'websites_statistics'), 's.website_id = websites.id', array('websites.id' => 'website_id'), \Zend\Db\Sql\Select::JOIN_INNER)
->where(array('websites.website' => 'google.com'));
$resultSet = $this->tableGateway->selectWith($select);
echo $select->getSqlString();
return $resultSet;
Debug result:
SELECT "websites".*,
"s"."website_id" AS "websites.id"
FROM "websites"
INNER JOIN "websites_statistics" AS "s" ON "s"."website_id" = "websites"."id"
WHERE "websites"."website" = 'google.com'
(!updated) The query a bit so it's more easier. I think there goes something wrong at the first moment because I think "s"."website_id" AS "websites.id" has to flip in the other direction .. "websites.id" AS "s"."website_id" I need websites.id to take record by website_id from the websites_statistics table.
Thanks in advance!
Nick
A:
I got it work. The problem wasn't the query it's self. I had to add the fields of the second table (to one I join) to the model (exchangeArray) of the first table! That did the trick. Thanks you all.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to select my second radio button in javascript without using id?
Hee, I'm working on something but can and dont want to change the HTML. Adding an ID button is not possible. I want to select the second radio input.
This is the html:
<fieldset>
<legend>I want to sign up:</legend>
<label>
<input type="radio" name="submit-for" value="project">
<span>For project</span>
</label>
<label>
<input type="radio" name="submit-for" value="stage">
<span>As intern</span>
</label>
</fieldset>
This are the ways i tried selecting it in javascript but it didnt work:
document.querySelector('input[type="radio"]:nth-of-type(2)').onclick = function () {
document.getElementById("project").style.display = 'none';
document.getElementById("stage").style.display = 'block';
};
and
document.querySelector('input[type="radio"]:nth-child(2)').onclick = function () {
document.getElementById("project").style.display = 'none';
document.getElementById("stage").style.display = 'block';
};
Can someone please help?
A:
Do you really want to select "the second" radio button, or do you want to select "the radio button with value 'stage'"? The second option sounds more extensible.
document.querySelector('input[type="radio"][value="stage"]')
EDIT: Also, upvoted your question for not resorting to ID usage. Always good practice, whether or not you're forced into it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Bare minimum you need to work for an open source project
I have recently started working on some open source project which I found relevant to my interests.
During this initiation period I came across some terminologies/stuff that I am not acquainted with, like configure, tool chain, binutils, etc. which I agree depends upon the type of project you are working on.
Now my question is, are there some bare requirements a developer should know before starting to work on the project?
Any help/reference will be greatly appreciated.
EDIT:
I have seen the GNU configure and build system in most of the projects I have seen.
If someone bothers about it "The GNU configure and build system" is a good place to start.
A:
If it's a pre-existing one, you'll need to read their development docs (if any), learn how to use their version control system, and have the requisite tools for building the code and running it.
If you have all that, and the knowledge of the code/language, then you just need enthusiasm and some spare time :)
A:
I wouldn't define them as bare requirements in the sense that it appears you are looking for. If you're a programmer you already have (hopefully!) the self-learning and problem solving characteristics that probably led you to be a programmer at first.
You'll never really know 'everything', and will likely learn something new everywhere you go. Heck, I got my current job never even hearing the words "Model-View-Controller", but picked up the concept in no time.
Your examples, toolchain and binutils, are not complex concepts and a simple wiki article should suffice.
| {
"pile_set_name": "StackExchange"
} |
Q:
ObjectInputStream doesn't have available bytes after being constructed with a ByteArrayInputStream
I'm constructing a class that is handling a Binary De/Serialization. The method open() receives an InputStream and a OutputStream. Those are created by another open() method that receives a path as argument. The InputStream is actually a ByteArrayInputStream.
I already did some tests to prove that the InputStream is arriving at the open() method with content - and it actually is. But when I try to set a ObjectInputStream using it, it doesn't work. No exceptions are thrown, but when I try to read bytes from it, it always gives me -1.
BinaryStrategy class
public class BinaryStrategy implements SerializableStrategy{
public BinaryStrategy(){
try{
open("products.ser");
}catch(IOException ioe){
}
}
@Override
public void open(InputStream input, OutputStream output) throws IOException {
try{
this.ois = new ObjectInputStream(input);
}catch(Exception ioe){
System.out.println(ioe);
}
this.oos = new ObjectOutputStream(output);
}
@Override
public void writeObject(fpt.com.Product obj) throws IOException {
oos.writeObject(obj);
oos.flush();
}
@Override
public Product readObject() throws IOException {
Product read = new Product();
try{
read.readExternal(ois);
}catch(IOException | ClassNotFoundException exc){
System.out.println(exc);
}
return read;
}
}
interface SerializableStrategy (just the default method)
default void open(Path path) throws IOException {
if (path != null) {
ByteArrayInputStream in = null;
if (Files.exists(path)) {
byte[] data = Files.readAllBytes(path);
in = new ByteArrayInputStream(data);
}
OutputStream out = Files.newOutputStream(path);
open(in, out);
}
Product class
public class Product implements java.io.Externalizable {
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeLong(getId());
out.writeObject(getName());
out.writeObject(getPrice());
out.writeObject(getQuantity());
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
this.setId((Long)in.readLong());
this.setName((String) in.readObject());
this.setPrice((Double) in.readObject());
this.setQuantity((Integer) in.readObject());
}
I had to personalize it because the attributes are SimplePropertys
At public void open(InputStream input, OutputStream output) I tried to do some stuff as follow to test:
public void open(InputStream input, OutputStream output) throws IOException {
try{
System.out.println(input.available() + " " + input.read() + " " + input.read());
//is gives me: 181 172 237
//181 is the exact size of the file I have, so i think that the Output is ok
//172 237 - just some chars that are in the file
//I know that for now on it is going to give me an excepetion because
// of the position of the index that is reading. I did it just to test
this.ois = new ObjectInputStream(input);
}catch(Exception ioe){
System.out.println(ioe);
}
this.oos = new ObjectOutputStream(output);
}
And then the other test:
public void open(InputStream input, OutputStream output) throws IOException {
try{
this.ois = new ObjectInputStream(input);
System.out.println(ois.available() + " " + ois.read());
//here is where I am receiving -1 and 0 available bytes!
//so something is going wrong right here.
//i tried to just go on and try to read the object,
//but I got a EOFException, in other words, -1.
}catch(Exception ioe){
System.out.println(ioe);
}
this.oos = new ObjectOutputStream(output);
}
A:
ObjectInputStream, internally uses a BlockDataInputStream perform its read operations. This reads a block of data and not just a byte as we expect, when you call a read. It reads a byte only if it falls as a "block"
The output is not what I was expecting either.
But, if you look at the code of ObjectInputStream.read(), it makes sense.
So, in your case it makes sense to use only readObject to restore your objects' state.
Heres your code again...
class SimpleJava {
public static void open(InputStream input, OutputStream output) throws IOException {
try {
ObjectInputStream ois = new ObjectInputStream(input);
System.out.println(ois.available());// 0
System.out.println(ois.available() + " " + ois.read() + " " + ois.read());// 0 -1 -1
// Reads the object even if the available returned 0
// and ois.read() returned -1
System.out.println("object:" + ois.readObject());// object:abcd
}
catch (Exception ioe) {
ioe.printStackTrace();
}
}
static void open(Path path) throws IOException {
if (path != null) {
ByteArrayInputStream in = null;
if (Files.exists(path)) {
byte[] data = Files.readAllBytes(path);
in = new ByteArrayInputStream(data);
}
OutputStream out = Files.newOutputStream(path);
open(in, out);
}
}
public static void main(String[] args) throws Exception {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("/home/pradhan/temp.object")));
oos.writeObject("abcd");//writes a string object for us to read later
oos.close();
//
open(FileSystems.getDefault().getPath("/home/user/temp.object"));
}
}
Heres the output...
0
0 -1 -1
object:abcd
| {
"pile_set_name": "StackExchange"
} |
Q:
Java Message logging Web Application
My Apache Tomcat Server is getting periodic updates from a Java based client Application, At the moment the scenario is just one client and talking to the server.
I want to log the messages from the client onto the server with time-stamp what kind of framework will help me in achieving this?
A:
EDIT: The OP goal was actually pretty unclear and I'm modifying my answer after some clarifications.
Well, I'm not sure, but maybe a logging framework will suit your needs. If so, have a look at:
Log4J: The most famous logging framework, widely used.
Java Logging aka java.util.logging: didn't succeed to replace Log4J.
Logback: "Logback is intended as a successor to the popular log4j project. It was designed, in addition to many individual contributors, by Ceki Gülcü, the founder of log4j".
SL4J: A "Simple Logging Facade for Java serves as a simple facade or abstraction for various logging frameworks, e.g. java.util.logging, log4j and logback, allowing the end user to plug in the desired logging framework at deployment time".
And pick one of them (I'd use Log4J or Logback).
To save your messages for later processing from the webapp (e.g. generating a web page with some graphs/charts), the best approach is to use a database. Just read/write them from/to a simple table with a timestamp column.
If you are not really familiar with Java, JDBC, persistence, connection pooling, datasource, etc, I'd suggest to use the Spring framework as it will hide most of the complexity. For the database part, have a look at the Chapter 11. Data access using JDBC from the Spring documentation. Pay a special attention to the JdbcTemplate or the SimpleJdbcTemplate, they should allow you to get the job done.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to display elements in block
I want the elements below to line up under each other.
As you can see in the picture the gray element is not lining up like the others.
A:
If what you would like is to replicate the code, you could do it like this:
#holder {
width: 300px;
height: 300px;
border: 1px solid black;
}
#gray {
width: 100%;
height: 33.333%;
background-color: gray;
}
#red {
width: 100%;
height: 33.333%;
background-color: red;
}
#orange {
width: 100%;
height: 33.333%;
background-color: orange;
}
<div id="holder">
<div id="red">
</div>
<div id="gray">
</div>
<div id="orange">
</div>
</div>
If you have current code though that you would like fixed, please post it here :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Do EnderStorage Ender Chests prevent strangers from accessing them if they make a chest with the same color code by accident?
Please note that this is a question about the minecraft mod EnderStorage, NOT vanilla ender chests.
The EnderStorage mod has custom ender chests which can be privatised by using different dyes on the 3 color slots.
When it comes to using those on a server, what happens if someone accidentally makes an ender chest with the same color code as the one I'm using? Will that person be able to see the contents of my ender chest, or is there something in place to prevent that?
A:
By default, all EnderStorage chests with the same color code will connect to each other, regardless of who placed those chests. However, you can make an EnderStorage chest private by right clicking on the latch with a diamond. This will cause the chest to also be associated with you, and will now only connect that chest to other diamond-latched chests with the same color code.
| {
"pile_set_name": "StackExchange"
} |
Q:
A question involving immunoprecipitation to identify interacting proteins?
Using recombinant Flag-tagged Dcr-2 and His-tagged protein X, pull-down assays were performed to determine whether protein X and Dcr-2 interact directly. The recombinant proteins (either alone or in combination) in binding buffer (150 mM NaCl, 1 mM EDTA, 50 mM Tris pH 7.5, 1% Triton X-100) were pulled-down by Flag antibodies coupled to Sepharose beads. Following extensive washing, the proteins were eluted from the beads with SDS buffer, and duplicate sets of samples were analyzed by SDS PAGE. Samples were also taken of the proteins before they were used in the pull-down assay and these were run on the same gel (input lanes in Figure 2B). One gel was stained with Coomassie blue dye (Figure 2A), and the other was transferred to nitrocellulose for Western Blotting. The membrane was probed with a His-antibody (Figure 2B).
The question asks: Do Dcr‐2 and protein X interact directly?
My reasoning is that they DO interact directly. In Fig 2B: the intense bands on LHS shows that Dcr-2 interacts with protein X-that is bound to anti-His. In Fig 2A: the protein X interacts with the Dcr-2 bound to antibody FLAG. I feel I'm not explaining this very though...Could someone please explain their reasoning? Thank you
A:
First: You are right with your reasoning that Protein X (X) and Dcr-2 interact directly. Lets go through the blots: In the input you check for the proteins loaded into the setting and stain unspecifically with Coomassie.
This part of the blot shows you no unspecific input, and both proteins of interest present. This also shows that Dcr-2 is much bigger than X which allows an easy identification of band patterns.
In the eluate you will only see proteins which are bound directly in the reaction or which interact with bound proteins. Dcr-2 is Flag-tagged so it will directly bind to the beads and can be eluated from them. This is shown in the coomassie part of the blot. Dcr-2 alone binds and can be eluated, while X alone does not bind and therefore gives no signal. Dcr-2 and X together give two bands, sind Dcr-2 binds to the beads and X is interacting with Dcr-2.
This binding is also shown with the anti-His antibody which only recognizes Protein X. The protein shows up in the input where X is added. It also shows up in the elution lane (where Dcr-2 is also present) showing that X is an interaction partner for Dcr-2.
| {
"pile_set_name": "StackExchange"
} |
Q:
Riemann Surface of $w^{2}=\sqrt{1-z^{2}}$
I'm working in the problem of finding branch points and build the Riemann Surface of the following complex function:
$$
w(z)=\sqrt{1-z^{2}} \,\, .
$$
I'm reading lots of texts about how to do this, but I'm not able to do it. How to indentify the branch points and how to build the Riemann surfaces step-by-step of this function?
Greetings!
A:
Since the square root has two possible values, your Riemann surface will have two sheets. Branch points of the square root are at $0$ and at $\infty$, so in this case the finite branch points are at the points where $1-z^2 = 0$, i.e., at $z=\pm 1$. At both of these points you have a simple zero, so analytic continuation around them will get you to the other sheet. Now you can make a branch cut from $-1$ to $+1$ and glue the two sheets together along this cut. Visualizing this on the Riemann sphere and opening up the cuts, you will get two spheres with disks removed, glued along their respective boundaries, which will again get you a sphere.
| {
"pile_set_name": "StackExchange"
} |
Q:
limit of series paradoxe?
I'm little bit confused about limit arithmetic:
$$\lim _{n\to \infty }\left(1\right)\:=\:\lim _{n\to \infty }\left(n\cdot \frac{1}{n}\right)\:=\:\lim _{n\to \infty }\left(\frac{1}{n}\:+\:\frac{1}{n}\:+\:...+\frac{1}{n}\right)\:=\\\lim _{n\to \infty }\left(\frac{1}{n}\right)+\lim _{n\to \infty }\left(\frac{1}{n}\right)+....+\lim _{n\to \infty }\left(\frac{1}{n}\right)\:=\\0\:+0\:+...\:+0\:=\:0$$
what i'm missing in the arithmetic?
A:
The equality
$$\lim_{n\to\infty} \left(\frac1n+\frac1n +\cdots + \frac1n\right) = \lim_{n\to\infty}\frac 1n+\lim_{n\to\infty}\frac 1n+\cdots +\lim_{n\to\infty}\frac 1n$$
is not true.
What is true is this:
If you have $k$ sequences of real numbers, $\left(a_n^{(1)}\right)_{n\in\mathbb N}, \left(a_n^{(2)}\right)_{n\in\mathbb N}, \dots, \left(a_n^{(k)}\right)_{n\in\mathbb N}$
and all these sequences converge, then
$$\lim_{n\to\infty} (a_n^{(1)} + a_n^{(2)}+\cdots + a_n^{(k)}) = \lim_{n\to\infty}a_n^{(1)} + \lim_{n\to\infty}a_n^{(2)} + \cdots \lim_{n\to\infty}a_n^{(k)}$$
but that is not what you have. What you have is an infinite amount of sequences. For each $k\in\mathbb N$, you have a sequence $\left(a_n^{(k)}\right)_{n\in\mathbb N}$, where $a_n^{(k)}$ is defined as
$$
a_n^{(k)} = \begin{cases}
0 & \mbox{ if } k>n\\
\frac1n&\mbox{ if } k\leq n
\end{cases}.
$$
Then, you want to say that
$$\lim_{n\to\infty}\left(a_n^{(1)} + a_n^{(2)} + \cdots \right) = \lim_{n\to\infty}a_n^{(1)} + \lim_{n\to\infty}a_n^{(2)} + \lim_{n\to\infty}a_n^{(3)} + \cdots$$
which is not true in all cases, as your example clearly shows.
| {
"pile_set_name": "StackExchange"
} |
Q:
current Bounds form google map with ng-map
I use this:ngmap.github.io and ionic framework.
I try get current position daynamicly like this js code:
google.maps.event.addListener(map, 'idle', function(){
var bounds = map.getBounds();
//returns an object with the NorthEast and SouthWest LatLng points of the bounds
});
how can I convert this code to angularjs?
A:
According to the documentation:
NgMap.getMap().then(function(map) {...}) is used to to get a map instance.
Example
var app = angular.module('myapp', ['ngMap']);
app.controller('mapcntrl', function (NgMap, $scope) {
NgMap.getMap().then(function (map) {
console.log(map.getBounds().toString());
});
});
<script src="https://maps.google.com/maps/api/js"></script>
<script src="https://code.angularjs.org/1.3.15/angular.js"></script>
<script src="https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/scripts/ng-map.js"></script>
<div ng-app="myapp" ng-controller="mapcntrl">
<ng-map center="[-26.1367035,124.2706638]" zoom="5"></ng-map>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does this MD5 algorithm return what seems to be a memory location and not a hash?
I am trying to wrap my head around the Brad Conte MD5 algorithm.
You can get it here: https://github.com/B-Con/crypto-algorithms
(md5.c, md5.h, md5_test.c)
Also an example of generating a hash here: http://bradconte.com/files/projects/code/md5_example.c
The example says it should be printing the hashes:
d41d8cd98f00b204e9800998ecf8427e
900150983cd24fb0d6963f7d28e17f72
d174ab98d277d9f5a5611c2c9f419d9f
But for me it prints:
ffffffd41dffffff8cffffffd9ffffff8f00ffffffb204ffffffe9ffffff8009ffffff98ffffffe cfffffff8427e
ffffff900150ffffff983cffffffd24fffffffb0ffffffd6ffffff963f7d28ffffffe17f72
ffffffd174ffffffabffffff98ffffffd277ffffffd9fffffff5ffffffa5611c2cffffff9f41ffffff9dffffff9f
These seems like memory addresses and not hashes to me?
I'm new to both C and MD5, so I might be doing something wrong - but I find it weird that the example does not print what the description says it should.
Would someone care to check this out?
A:
The printf converts a char to an int. The result depends on whether a char is signed or not (and thus gets sign-extended in your case).
Are you sure you want to use a crypto package that makes such mistakes?
| {
"pile_set_name": "StackExchange"
} |
Q:
Ruby scaffold undefined method 'configure'
Hi I was following exactly the steps to create a demo application for Rubys on windows. but when I try to generate the tables using the scaffold command,
rails generate scaffold User name:string email:string
I got the following errors:
C:/Users/YoYo/Ruby_Projects/demo_app/config/environments/development.rb:1:in `<t
op (required)>': undefined method `configure' for #<DemoApp::Application:0x00000
00534bc00> (NoMethodError)
from D:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/activesupport-4.0.5/lib/act
ive_support/dependencies.rb:229:in `require'
from D:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/activesupport-4.0.5/lib/act
ive_support/dependencies.rb:229:in `block in require'
from D:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/activesupport-4.0.5/lib/act
ive_support/dependencies.rb:214:in `load_dependency'
from D:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/activesupport-4.0.5/lib/act
ive_support/dependencies.rb:229:in `require'
from D:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/railties-4.0.5/lib/rails/en
gine.rb:591:in `block (2 levels) in <class:Engine>'
from D:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/railties-4.0.5/lib/rails/en
gine.rb:590:in `each'
from D:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/railties-4.0.5/lib/rails/en
gine.rb:590:in `block in <class:Engine>'
from D:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/railties-4.0.5/lib/rails/in
itializable.rb:30:in `instance_exec'
from D:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/railties-4.0.5/lib/rails/in
itializable.rb:30:in `run'
from D:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/railties-4.0.5/lib/rails/in
itializable.rb:55:in `block in run_initializers'
from D:/Ruby200-x64/lib/ruby/2.0.0/tsort.rb:150:in `block in tsort_each'
from D:/Ruby200-x64/lib/ruby/2.0.0/tsort.rb:183:in `block (2 levels) in
each_strongly_connected_component'
from D:/Ruby200-x64/lib/ruby/2.0.0/tsort.rb:210:in `block (2 levels) in
each_strongly_connected_component_from'
from D:/Ruby200-x64/lib/ruby/2.0.0/tsort.rb:219:in `each_strongly_connec
ted_component_from'
from D:/Ruby200-x64/lib/ruby/2.0.0/tsort.rb:209:in `block in each_strong
ly_connected_component_from'
from D:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/railties-4.0.5/lib/rails/in
itializable.rb:44:in `each'
from D:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/railties-4.0.5/lib/rails/in
itializable.rb:44:in `tsort_each_child'
from D:/Ruby200-x64/lib/ruby/2.0.0/tsort.rb:203:in `each_strongly_connec
ted_component_from'
from D:/Ruby200-x64/lib/ruby/2.0.0/tsort.rb:182:in `block in each_strong
ly_connected_component'
from D:/Ruby200-x64/lib/ruby/2.0.0/tsort.rb:180:in `each'
from D:/Ruby200-x64/lib/ruby/2.0.0/tsort.rb:180:in `each_strongly_connec
ted_component'
from D:/Ruby200-x64/lib/ruby/2.0.0/tsort.rb:148:in `tsort_each'
from D:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/railties-4.0.5/lib/rails/in
itializable.rb:54:in `run_initializers'
from D:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/railties-4.0.5/lib/rails/ap
plication.rb:215:in `initialize!'
from C:/Users/YoYo/Ruby_Projects/demo_app/config/environment.rb:5:in `<t
op (required)>'
from D:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/railties-4.0.5/lib/rails/ap
plication.rb:189:in `require'
from D:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/railties-4.0.5/lib/rails/ap
plication.rb:189:in `require_environment!'
from D:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/railties-4.0.5/lib/rails/co
mmands.rb:44:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'
Does anyone know how to solve?
A:
So what you configured is a problem---
You can use-
DemoApp::Application.configure do
config.cache_classes = false
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
config.action_mailer.raise_delivery_errors = false
config.active_support.deprecation = :log
config.active_record.migration_error = :page_load
config.assets.debug = true
config.assets.raise_runtime_errors = true
end
rails-generate-scaffold-error
| {
"pile_set_name": "StackExchange"
} |
Q:
version control: free one for visual studio express
I am using c# express and would like to use a free version control system. Please share your recommendations.
A:
Visual Studio Express is crippled in the sense that it cant load any plugins or addons.
Just go with TortoiseSVN. Works easy enough.
A:
It seems to me you are new to Version Control. If you haven't used source control before, I recommend looking at a distributed version control system (DVCS) directly. My choice was Mercurial, because it has excellent documentation, a clean and consistent interface, works well on all major platforms (using it on Windows, Linux and MacOSX) and a great support for PlugIns (several are officially redistributed, such as mq) that let you do very advanced stuff. There are great GUIs available (TortoiseHG, but also standalone). There is a nice introduction to Mercurial here, but the it's also useful for the general conept.
Popular DVCS include: Mercurial, Git and Bazaar but in the end it doesn't matter which tool you choose There is lots of information here on SO about comparisons.
The best IDE PlugIn is don't use one. I think IDE integration is not necessary when working with a DVCS. When working in a centralized system, it is reasonable for the purpose of automatic check out on edit, rename support etc.. However, I like keeping things seperate. I don't want my IDE cluttered up. I don't see any benefits in using a plugin compared to a standalone solution (that I keep running on a second monitor). To support renaming, a good DVCS has built in heuristics to find and track renames automatically.
I am fine with TortoiseHG and the command line for more complicated tasks.
A:
Don't use your IDE for version control. Get to know your version control system itself. Which one you should use depends on your requirements. My personal favourite at the moment is Mercurial.
| {
"pile_set_name": "StackExchange"
} |
Q:
OpenCV imwrite params read access violation
A very simple question...why am I getting a read access violation error with this code?
cv::Mat laserSpeckle = Mat::zeros(100,100,CV_8UC1);
imwrite( "C://testimage.jpg", laserSpeckle );
When i attach a debugger and look into it further, it throws the exception at this snippet in grfmt.cpp.
if( params[i] == CV_IMWRITE_JPEG_QUALITY )
{
quality = params[i+1];
quality = MIN(MAX(quality, 0), 100);
}
It occurs with .png and .tiff too. Im an OpenCV newbie, my apologies if this is something really simple. I am using Qt for what its worth.
A:
Do you build OpenCV yourself? If yes, make sure that the option WITH_JPEG is enabled when you configure your build files:
cmake ... -DWITH_JPEG=ON ...
| {
"pile_set_name": "StackExchange"
} |
Q:
Updating operation from sum to subtract or viceversa depending on a given value
I need to sum or subtract the values of an array.
For example:
[1, 5, 10] should be represented as: 1 + 5 + 10 = 16.
And [1, 5, -1, 10, 5] should be: 1 + 5 - 10 - 5 the -1 number indicates subtraction or sum depending where the -1 is. The 1st -1 will indicate subtraction, the second one -1 indicates that everything is getting back to a regular sum as everything was in the beginning, the 3rd will be subtraction again, and so on.
Now look how it should be with 2 -1s: [1, 5, -1, 10, 5, -1, 5, 5], it
should be represented as: 1 + 5 - 10 - 5 + 5 + 5, got it ?
So, everything should be sum up until the array contains a -1 so it changes to subraction, if there is another -1 the operation should change to be a sum. And so on, every time there is a new '-1' the operation changes to the contrary it was before.
I am doing that calculation like this:
function calculate (){
logingValues();
var total = 0;
var shouldSubtract = false;
for (var i = 0; i < arrayOfNumbers.length; i++) {
if (arrayOfNumbers[i] === "") continue;
var currentNumber = parseInt(arrayOfNumbers[i], 10);
if(isNaN(currentNumber)) {
currentNumber = 0;
}
if (currentNumber === -1) {
shouldSubtract = true;
} else {
if (shouldSubtract) {
total -= currentNumber;
shouldSubtract = false;
} else {
total += currentNumber;
}
}
}
caculationEffect(total);
}
And here is the whole code
Any suggestions?
A:
Here is my short Array.prototype.reduce solution:
[1, 5, -1, 10, 5, -1, 5, 5].reduce(function(ctx, x) {
if (x === -1) // if the current value is -1 ...
ctx.sign *= -1; // - change the sign
else // otherwise ...
ctx.sum += x * ctx.sign; // - transform according to the sign
return ctx; // return context
}, { sign: 1, sum: 0 }).sum;
A:
You could use a variable for the deciding if to add or subtract the actual value.
function sum(array){
var negative;
return array.reduce(function (a, b) {
if (b === -1) {
negative = !negative;
return a;
}
return negative ? a - b : a + b;
}, 0);
}
console.log(sum([1, 5, 10]));
console.log(sum([1, 5, -1, 10, 5]));
console.log(sum([1, 5, -1, 10, 5, -1, 5, 5]));
| {
"pile_set_name": "StackExchange"
} |
Q:
How to convert NSString with hex values to Char - Objective C
I have a NSString @"460046003600430035003900" which represent hex color FF6C59.
How can i get that hex color from strings in above format:
eg:
460046003500430032003000 = FF5C20
300030004200350033004500 = 00B53E
A:
#import <Foundation/Foundation.h>
@interface WeirdFormatDecoder : NSObject
@end
@implementation WeirdFormatDecoder
+(NSString*) decode:(NSString*)string
{
if (!string) return @"";
NSAssert([string length]%2==0, @"bad format");
NSMutableString *s = [NSMutableString new];
for (NSUInteger i=0; i<[string length]-2; i=i+2) {
char c = [[string substringWithRange:NSMakeRange(i, 2)] integerValue];
if (c==0) continue;
else if (c<41){
[s appendFormat:@"%c",[@"0123456789" characterAtIndex:c-30]];
} else {
[s appendFormat:@"%c",[@"ABCDEF" characterAtIndex:c-41]];
}
}
return s;
}
@end
int main(int argc, char *argv[]) {
@autoreleasepool {
NSLog(@"%@",[WeirdFormatDecoder decode:@"460046003600430035003900"]); // FF6C59
return EXIT_SUCCESS;
}
}
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.