Most recommended method is using wrapper function and spread operator together. For example, if you have initialized a state called name
like this,
const [names, setNames] = useState([])
You can push to this array like this,
setNames(names => [...names, newName])
Hope that helps.
Well you could either initialize the xib using a view controller and use viewController.view. or do it the way you did it. Only making a UIView
subclass as the controller for UIView
is a bad idea.
If you don't have any outlets from your custom view then you can directly use a UIViewController
class to initialize it.
Update: In your case:
UIViewController *genericViewCon = [[UIViewController alloc] initWithNibName:@"CustomView"];
//Assuming you have a reference for the activity indicator in your custom view class
CustomView *myView = (CustomView *)genericViewCon.view;
[parentView addSubview:myView];
//And when necessary
[myView.activityIndicator startAnimating]; //or stop
Otherwise you have to make a custom UIViewController
(to make it as the file's owner so that the outlets are properly wired up).
YourCustomController *yCustCon = [[YourCustomController alloc] initWithNibName:@"YourXibName"].
Wherever you want to add the view you can use.
[parentView addSubview:yCustCon.view];
However passing the another view controller(already being used for another view) as the owner while loading the xib is not a good idea as the view property of the controller will be changed and when you want to access the original view, you won't have a reference to it.
EDIT: You will face this problem if you have setup your new xib with file's owner as the same main UIViewController
class and tied the view property to the new xib view.
i.e;
The below code will cause confusion later on, if you write it inside view did load of YourMainViewController
. That is because self.view
from this point on will refer to your customview
-(void)viewDidLoad:(){
UIView *childView= [[[NSBundle mainBundle] loadNibNamed:@"YourXibName" owner:self options:nil] objectAtIndex:0];
}
The best thing is to use @Value
annotation it will automatically assign value to your object private Environment en
.
This will reduce your code and it will be easy to filter your files.
Also worth noting you can use 'em' as well as 'px' - blogs and text based sites do it because then the browser makes layout decisions more relative to the text content.
On Wordpress twentysixteen I wanted my tagline to display on mobiles as well as desktops, so I put this in my child theme style.css
@media screen and (max-width:59em){
p.site-description {
display: block;
}
}
A common case for simply setting -fpermissive and not sweating it exists: the thoroughly-tested and working third-party library that won't compile on newer compiler versions without -fpermissive. These libraries exist, and are very likely not the application developer's problem to solve, nor in the developer's schedule budget to do it.
Set -fpermissive and move on in that case.
For anyone stumbling across the same issue:
I fixed the problem by cloning the repo again at another location. I then copied my whole src dir (without .git dir obviously) from the corrupted repo into the freshly cloned repo. Thus I had all the recent changes and a clean and working repository.
Why not just do this take 010010001001001 split it into two bits 8 letter each (01001000, 01001001). Then issue the powers
01001000. 01001001.
The first 8 ignore the first three they determine if it's capital or not, the go right to left doing powers of 2 (2^1, 2^2 2^3 2^4 2^5). So then add all the ones up , there's only one, and it = 8, and te eight letter in the alphabet is h so our first bit is the letter h, try it on the other bit
string strHeader = Request.Headers["XYZComponent"]
bool bHeader = Boolean.TryParse(strHeader, out bHeader ) && bHeader;
if "true" than true
if "false" or anything else ("fooBar") than false
or
string strHeader = Request.Headers["XYZComponent"]
bool b;
bool? bHeader = Boolean.TryParse(strHeader, out b) ? b : default(bool?);
if "true" than true
if "false" than false
else ("fooBar") than null
For portability
you can say "${s#"${s%?}"}"
:
#!/bin/sh
m=bzzzM n=bzzzN
for s in \
'vv' 'w' '' 'uu ' ' uu ' ' uu' / \
'ab?' 'a?b' '?ab' 'ab??' 'a??b' '??ab' / \
'cd#' 'c#d' '#cd' 'cd##' 'c##d' '##cd' / \
'ef%' 'e%f' '%ef' 'ef%%' 'e%%f' '%%ef' / \
'gh*' 'g*h' '*gh' 'gh**' 'g**h' '**gh' / \
'ij"' 'i"j' '"ij' "ij'" "i'j" "'ij" / \
'kl{' 'k{l' '{kl' 'kl{}' 'k{}l' '{}kl' / \
'mn$' 'm$n' '$mn' 'mn$$' 'm$$n' '$$mn' /
do case $s in
(/) printf '\n' ;;
(*) printf '.%s. ' "${s#"${s%?}"}" ;;
esac
done
Output:
.v. .w. .. . . . . .u.
.?. .b. .b. .?. .b. .b.
.#. .d. .d. .#. .d. .d.
.%. .f. .f. .%. .f. .f.
.*. .h. .h. .*. .h. .h.
.". .j. .j. .'. .j. .j.
.{. .l. .l. .}. .l. .l.
.$. .n. .n. .$. .n. .n.
I went through this and found all the answers super cool, however wants to add to answer given by @deejers
SELECT
col1,
col2,
col3,
CASE
WHEN condition1 THEN calculation1
WHEN condition2 THEN calculation2
WHEN condition3 THEN calculation3
WHEN condition4 THEN calculation4
WHEN condition5 THEN calculation5
END AS 'calculatedcol1',
col4,
col5 -- etc
FROM table
you can make ELSE optional as its not mandatory, it is very helpful in many scenarios.
Others have already given good answers on how to generate code at runtime so I thought I would address your second paragraph. I have some experience with this and just want to share a lesson I learned from that experience.
At the very least, I could define an interface that they would be required to implement, then they would provide a code 'section' that implemented that interface.
You may have a problem if you use an interface
as a base type. If you add a single new method to the interface
in the future all existing client-supplied classes that implement the interface
now become abstract, meaning you won't be able to compile or instantiate the client-supplied class at runtime.
I had this issue when it came time to add a new method after about 1 year of shipping the old interface and after distributing a large amount of "legacy" data that needed to be supported. I ended up making a new interface that inherited from the old one but this approach made it harder to load and instantiate the client-supplied classes because I had to check which interface was available.
One solution I thought of at the time was to instead use an actual class as a base type such as the one below. The class itself can be marked abstract but all methods should be empty virtual methods (not abstract methods). Clients can then override the methods they want and I can add new methods to the base class without invalidating existing client-supplied code.
public abstract class BaseClass
{
public virtual void Foo1() { }
public virtual bool Foo2() { return false; }
...
}
Regardless of whether this problem applies you should consider how to version the interface between your code base and the client-supplied code.
I downloaded the jar file manually and replace the one in my local directory and it worked
I'm certain there are better ways of doing this, but I have in the past used a method something like the following to serialize an object into a string that I can log:
private string ObjectToXml(object output)
{
string objectAsXmlString;
System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(output.GetType());
using (System.IO.StringWriter sw = new System.IO.StringWriter())
{
try
{
xs.Serialize(sw, output);
objectAsXmlString = sw.ToString();
}
catch (Exception ex)
{
objectAsXmlString = ex.ToString();
}
}
return objectAsXmlString;
}
You'll see that the method might also return the exception rather than the serialized object, so you'll want to ensure that the objects you want to log are serializable.
Work with checkboxes using observables
You could even choose to use a behaviourSubject
to utilize the power of observables so you can start a certain chain of reaction starting at the isChecked$
observable.
In your component.ts:
public isChecked$ = new BehaviorSubject(false);
toggleChecked() {
this.isChecked$.next(!this.isChecked$.value)
}
In your template
<input type="checkbox" [checked]="isChecked$ | async" (change)="toggleChecked()">
c
can be used on lists (and not only on vectors):
# you have
l1 = list(2, 3)
l2 = list(4)
# you want
list(2, 3, 4)
[[1]]
[1] 2
[[2]]
[1] 3
[[3]]
[1] 4
# you can do
c(l1, l2)
[[1]]
[1] 2
[[2]]
[1] 3
[[3]]
[1] 4
If you have a list of lists, you can do it (perhaps) more comfortably with do.call
, eg:
do.call(c, list(l1, l2))
There seem to be a lot of solutions for Windows here but this is the simplest:
Tools -> Build System -> New Build System, type in the above, save as Browser.sublime-build
:
{
"cmd": "explorer $file"
}
Then go back to your HTML file. Tools -> Build System -> Browser. Then press CTRL-B
and the file will be opened in whatever browser is your system default browser.
There are many ways to nullify session in ASP.NET. Session in essence is a cookie, set on client's browser and in ASP.NET, its name is usually ASP.NET_SessionId
. So, theoretically if you delete that cookie (which in terms of browser means that you set its expiration date to some date in past, because cookies can't be deleted by developers), then you loose the session in server. Another way as you said is to use Session.Clear()
method. But the best way is to set another irrelevant object (usually null
value) in the session in correspondance to a key. For example, to nullify Session["FirstName"]
, simply set it to Session["FirstName"] = null
.
The approved answer from George Claghorn worked great for simply inserting text at the cursor position. If the user had selected text though, and you want that text to be replaced (the default experience with most text), you need to make a small change when setting the 'back' variable.
Also, if you don't need to support older versions of IE, modern versions support textarea.selectionStart, so you can take out all of the browser detection, and IE-specific code.
Here is a simplified version that works for Chrome and IE11 at least, and handles replacing selected text.
function insertAtCaret(areaId, text) {
var txtarea = document.getElementById(areaId);
var scrollPos = txtarea.scrollTop;
var caretPos = txtarea.selectionStart;
var front = (txtarea.value).substring(0, caretPos);
var back = (txtarea.value).substring(txtarea.selectionEnd, txtarea.value.length);
txtarea.value = front + text + back;
caretPos = caretPos + text.length;
txtarea.selectionStart = caretPos;
txtarea.selectionEnd = caretPos;
txtarea.focus();
txtarea.scrollTop = scrollPos;
}
If you do not want to the text twice as column heading as well as value, use the following stmt!
SELECT 'some text' as '';Example:
mysql>SELECT 'some text' as ''; +-----------+ | | +-----------+ | some text | +-----------+ 1 row in set (0.00 sec)
One example:
List somelist = new ArrayList();
You can look at the javadoc for List and find all known implementing classes of the List
interface that are included with the java api.
As kmcamara discovered, this is exactly the kind of problem that VLOOKUP is intended to solve, and using vlookup is arguably the simplest of the alternative ways to get the job done.
In addition to the three parameters for lookup_value, table_range to be searched, and the column_index for return values, VLOOKUP takes an optional fourth argument that the Excel documentation calls the "range_lookup".
Expanding on deathApril's explanation, if this argument is set to TRUE (or 1) or omitted, the table range must be sorted in ascending order of the values in the first column of the range for the function to return what would typically be understood to be the "correct" value. Under this default behavior, the function will return a value based upon an exact match, if one is found, or an approximate match if an exact match is not found.
If the match is approximate, the value that is returned by the function will be based on the next largest value that is less than the lookup_value. For example, if "12AT8003" were missing from the table in Sheet 1, the lookup formulas for that value in Sheet 2 would return '2', since "12AT8002" is the largest value in the lookup column of the table range that is less than "12AT8003". (VLOOKUP's default behavior makes perfect sense if, for example, the goal is to look up rates in a tax table.)
However, if the fourth argument is set to FALSE (or 0), VLOOKUP returns a looked-up value only if there is an exact match, and an error value of #N/A if there is not. It is now the usual practice to wrap an exact VLOOKUP in an IFERROR function in order to catch the no-match gracefully. Prior to the introduction of IFERROR, no matches were checked with an IF function using the VLOOKUP formula once to check whether there was a match, and once to return the actual match value.
Though initially harder to master, deusxmach1na's proposed solution is a variation on a powerful set of alternatives to VLOOKUP that can be used to return values for a column or list to the left of the lookup column, expanded to handle cases where an exact match on more than one criterion is needed, or modified to incorporate OR as well as AND match conditions among multiple criteria.
Repeating kcamara's chosen solution, the VLOOKUP formula for this problem would be:
=VLOOKUP(A1,Sheet1!A$1:B$600,2,FALSE)
One problem with the for loop solutions above is that for the following input array with all positive values, the sum result is negative:
int[] arr = new int[] { Int32.MaxValue, 1 };
int sum = 0;
for (int i = 0; i < arr.Length; i++)
{
sum += arr[i];
}
Console.WriteLine(sum);
The sum is -2147483648, as the positive result is too big for the int data type and overflows into a negative value.
For the same input array the arr.Sum() suggestions cause an overflow exception to be thrown.
A more robust solution is to use a larger data type, such as a "long" in this case, for the "sum" as follows:
int[] arr = new int[] { Int32.MaxValue, 1 };
long sum = 0;
for (int i = 0; i < arr.Length; i++)
{
sum += arr[i];
}
The same improvement works for summation of other integer data types, such as short, and sbyte. For arrays of unsigned integer data types such as uint, ushort and byte, using an unsigned long (ulong) for the sum avoids the overflow exception.
The for loop solution is also many times faster than Linq .Sum()
To run even faster, HPCsharp nuget package implements all of these .Sum() versions as well as SIMD/SSE versions and multi-core parallel ones, for many times faster performance.
A simple implementation could consist of:
Every time you write data, you advance the write pointer and increment the counter. When you read data, you increase the read pointer and decrement the counter. If either pointer reaches n, set it to zero.
You can't write if counter = n. You can't read if counter = 0.
Now only I came across this situation and found some more interesting features around GROUP_CONCAT
. I hope these details will make you feel interesting.
simple GROUP_CONCAT
SELECT GROUP_CONCAT(TaskName)
FROM Tasks;
Result:
+------------------------------------------------------------------+
| GROUP_CONCAT(TaskName) |
+------------------------------------------------------------------+
| Do garden,Feed cats,Paint roof,Take dog for walk,Relax,Feed cats |
+------------------------------------------------------------------+
GROUP_CONCAT with DISTINCT
SELECT GROUP_CONCAT(TaskName)
FROM Tasks;
Result:
+------------------------------------------------------------------+
| GROUP_CONCAT(TaskName) |
+------------------------------------------------------------------+
| Do garden,Feed cats,Paint roof,Take dog for walk,Relax,Feed cats |
+------------------------------------------------------------------+
GROUP_CONCAT with DISTINCT and ORDER BY
SELECT GROUP_CONCAT(DISTINCT TaskName ORDER BY TaskName DESC)
FROM Tasks;
Result:
+--------------------------------------------------------+
| GROUP_CONCAT(DISTINCT TaskName ORDER BY TaskName DESC) |
+--------------------------------------------------------+
| Take dog for walk,Relax,Paint roof,Feed cats,Do garden |
+--------------------------------------------------------+
GROUP_CONCAT with DISTINCT and SEPARATOR
SELECT GROUP_CONCAT(DISTINCT TaskName SEPARATOR ' + ')
FROM Tasks;
Result:
+----------------------------------------------------------------+
| GROUP_CONCAT(DISTINCT TaskName SEPARATOR ' + ') |
+----------------------------------------------------------------+
| Do garden + Feed cats + Paint roof + Relax + Take dog for walk |
+----------------------------------------------------------------+
GROUP_CONCAT and Combining Columns
SELECT GROUP_CONCAT(TaskId, ') ', TaskName SEPARATOR ' ')
FROM Tasks;
Result:
+------------------------------------------------------------------------------------+
| GROUP_CONCAT(TaskId, ') ', TaskName SEPARATOR ' ') |
+------------------------------------------------------------------------------------+
| 1) Do garden 2) Feed cats 3) Paint roof 4) Take dog for walk 5) Relax 6) Feed cats |
+------------------------------------------------------------------------------------+
GROUP_CONCAT and Grouped Results
Assume that the following are the results before using GROUP_CONCAT
+------------------------+--------------------------+
| ArtistName | AlbumName |
+------------------------+--------------------------+
| Iron Maiden | Powerslave |
| AC/DC | Powerage |
| Jim Reeves | Singing Down the Lane |
| Devin Townsend | Ziltoid the Omniscient |
| Devin Townsend | Casualties of Cool |
| Devin Townsend | Epicloud |
| Iron Maiden | Somewhere in Time |
| Iron Maiden | Piece of Mind |
| Iron Maiden | Killers |
| Iron Maiden | No Prayer for the Dying |
| The Script | No Sound Without Silence |
| Buddy Rich | Big Swing Face |
| Michael Learns to Rock | Blue Night |
| Michael Learns to Rock | Eternity |
| Michael Learns to Rock | Scandinavia |
| Tom Jones | Long Lost Suitcase |
| Tom Jones | Praise and Blame |
| Tom Jones | Along Came Jones |
| Allan Holdsworth | All Night Wrong |
| Allan Holdsworth | The Sixteen Men of Tain |
+------------------------+--------------------------+
USE Music;
SELECT ar.ArtistName,
GROUP_CONCAT(al.AlbumName)
FROM Artists ar
INNER JOIN Albums al
ON ar.ArtistId = al.ArtistId
GROUP BY ArtistName;
Result:
+------------------------+----------------------------------------------------------------------------+
| ArtistName | GROUP_CONCAT(al.AlbumName) |
+------------------------+----------------------------------------------------------------------------+
| AC/DC | Powerage |
| Allan Holdsworth | All Night Wrong,The Sixteen Men of Tain |
| Buddy Rich | Big Swing Face |
| Devin Townsend | Epicloud,Ziltoid the Omniscient,Casualties of Cool |
| Iron Maiden | Somewhere in Time,Piece of Mind,Powerslave,Killers,No Prayer for the Dying |
| Jim Reeves | Singing Down the Lane |
| Michael Learns to Rock | Eternity,Scandinavia,Blue Night |
| The Script | No Sound Without Silence |
| Tom Jones | Long Lost Suitcase,Praise and Blame,Along Came Jones |
+------------------------+----------------------------------------------------------------------------+
I'm doing something like that.
Getting the values in lowercase and MySQL does the rest
$string = $_GET['string'];
mysqli_query($con,"SELECT *
FROM table_name
WHERE LOWER(column_name)
LIKE LOWER('%$string%')");
And For MySQL PDO Alternative:
$string = $_GET['string'];
$q = "SELECT *
FROM table_name
WHERE LOWER(column_name)
LIKE LOWER(?);";
$query = $dbConnection->prepare($q);
$query->bindValue(1, "%$string%", PDO::PARAM_STR);
$query->execute();
This can also occur if the read end of the output from your script dies prematurely
ie open.py | otherCommand
if otherCommand exits and open.py tries to write to stdout
I had a bad gawk script that did this lovely to me.
If you want to find the last populated cell in a particular column, the best method is:
Range("A" & Rows.Count).End(xlUp).Row
This code uses the very last cell in the entire column (65536 for Excel 2003, 1048576 in later versions), and then find the first populated cell above it. This has the ability to ignore "breaks" in your data and find the true last row.
After much aggravation this is what I have found to work"simply". First thing, I am using MYSQL Workbench and the import would not work as it should, as the import dump file would always revert to the original schema name. I spent several hours trying every thing to no avail,all for a spelling error. I solved the issue by opening one of the .sql dump files in notebook and hand editing the typo's of the schema name, take care to rename all instances schema name has three in the beginning, save the file and then import. this worked perfectly for me and hope that it will help others looking for the simple answer to changing database names/schema names. One more tip that I have found true, when programs do not do as they should go to the "source" literally find the source code. Hope this helps someone
Low rep so they wont let me comment on the prior/post answer(it keeps changing rank or position), so I added it here. reverse engineering will work fine as long as there is no data in the sever table. if data exists and you try to update the server after the name change it will either pull an error or just create a new database/schema with no data, I know I tried ten times to no avail. The above works simply and avoids headaches, as one can review the SQL code for other errors if any or change table names or creation data. the .sql file is just a compiled SQL code so in theory one could copy and add it through PHP or the script console of the database management tool.
private String bytesIntoHumanReadable(long bytes) {
long kilobyte = 1024;
long megabyte = kilobyte * 1024;
long gigabyte = megabyte * 1024;
long terabyte = gigabyte * 1024;
if ((bytes >= 0) && (bytes < kilobyte)) {
return bytes + " B";
} else if ((bytes >= kilobyte) && (bytes < megabyte)) {
return (bytes / kilobyte) + " KB";
} else if ((bytes >= megabyte) && (bytes < gigabyte)) {
return (bytes / megabyte) + " MB";
} else if ((bytes >= gigabyte) && (bytes < terabyte)) {
return (bytes / gigabyte) + " GB";
} else if (bytes >= terabyte) {
return (bytes / terabyte) + " TB";
} else {
return bytes + " Bytes";
}
}
Other way is using short-circuit:
x = (typeof y !== 'undefined') && y || 1
Although I myself think that ternary is more readable.
Keep it simple - as you said, a flat file is sufficient. Use a flat file.
This is assuming that you have analyzed your requirements correctly. I would skip the serializing as XML step, overkill for a simple dictionary. Same thing for a database.
Yes, it is valid.
As for making it work with functors as well, the usual solution is something like this instead:
template <typename F>
void doOperation(F f)
{
int temp=0;
f(temp);
std::cout << "Result is " << temp << std::endl;
}
which can now be called as either:
doOperation(add2);
doOperation(add3());
The problem with this is that if it makes it tricky for the compiler to inline the call to add2
, since all the compiler knows is that a function pointer type void (*)(int &)
is being passed to doOperation
. (But add3
, being a functor, can be inlined easily. Here, the compiler knows that an object of type add3
is passed to the function, which means that the function to call is add3::operator()
, and not just some unknown function pointer.)
Trying to write a REST API from scratch is not a simple task. There are many issues to factor and you will need to write a lot of code to process requests and data coming from the caller, authentication, retrieval of data and sending back responses.
Your best bet is to use a framework that already has this functionality ready and tested for you.
Some suggestions are:
Phalcon - REST API building - Easy to use all in one framework with huge performance
Apigility - A one size fits all API handling framework by Zend Technologies
Laravel API Building Tutorial
and many more. Simple searches on Bitbucket/Github will give you a lot of resources to start with.
Trust me, this will work for you:
npm config set registry http://registry.npmjs.org/
Found method to see your own html file (from here (scroll down to answer from prac): https://productforums.google.com/forum/#!topic/drive/YY_fou2vo0A)
-- use Get Link to get URL with id=... substring -- put uc instead of open in URL
[textField resignFirstResponder];
Use this
Divide by 2
to the power of 20
, (1024*1024)
bytes = 1
megabyte
1024*1024 = 1,048,576
2^20 = 1,048,576
1,048,576/1,048,576 = 1
It is the same thing.
If you look at the function (by typing it's name at the console) you will see that it is just a simple functionalized version of the [<-
function which is described at ?"["
. [
is a rather basic function to R so you would be well-advised to look at that page for further details. Especially important is learning that the index argument (the second argument in replace
can be logical, numeric or character classed values. Recycling will occur when there are differing lengths of the second and third arguments:
You should "read" the function call as" "within the first argument, use the second argument as an index for placing the values of the third argument into the first":
> replace( 1:20, 10:15, 1:2)
[1] 1 2 3 4 5 6 7 8 9 1 2 1 2 1 2 16 17 18 19 20
Character indexing for a named vector:
> replace(c(a=1, b=2, c=3, d=4), "b", 10)
a b c d
1 10 3 4
Logical indexing:
> replace(x <- c(a=1, b=2, c=3, d=4), x>2, 10)
a b c d
1 2 10 10
I found this source very interesting.
In fact, it is the Lambda that turns into a Double Colon. The Double Colon is more readable. We follow those steps:
STEP1:
// We create a comparator of two persons
Comparator c = (Person p1, Person p2) -> p1.getAge().compareTo(p2.getAge());
STEP2:
// We use the interference
Comparator c = (p1, p2) -> p1.getAge().compareTo(p2.getAge());
STEP3:
// The magic using method reference
Comparator c = Comparator.comparing(Person::getAge);
You are correct: calling finish()
will only exit the current activity, not the entire application. however, there is a workaround for this:
Every time you start an Activity, start it using startActivityForResult(...)
. When you want to close the entire app, you can do something like this:
setResult(RESULT_CLOSE_ALL);
finish();
Then define every activity's onActivityResult(...)
callback so when an activity returns with the RESULT_CLOSE_ALL
value, it also calls finish()
:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(resultCode)
{
case RESULT_CLOSE_ALL:
setResult(RESULT_CLOSE_ALL);
finish();
}
super.onActivityResult(requestCode, resultCode, data);
}
This will cause a cascade effect closing all activities.
Also, I support CommonsWare in his suggestion: store the password in a variable so that it will be destroyed when the application is closed.
According to Wikipedia:
[...] A traditional pipe is "unnamed" because it exists anonymously and persists only for as long as the process is running. A named pipe is system-persistent and exists beyond the life of the process and must be "unlinked" or deleted once it is no longer being used. Processes generally attach to the named pipe (usually appearing as a file) to perform IPC (inter-process communication).
I'm sure you can use RAISERROR ... WITH NOWAIT
If you use severity 10 it's not an error. This also provides some handy formatting eg %s, %i and you can use state too to track where you are.
Try this
select * from mytable
where p1 not like '%[^0-9]%' and substring(p1,1,1)='5'
Of course, you'll need to adjust the substring value, but the rest should work...
I might have a solution for the video as background, stretched to the browser-width or height, (but the video will still preserve the aspect ratio, couldnt find a solution for that yet.):
Put the video right after the body-tag with style="width:100%;"
.
Right afterwords, put a "bodydummy"-tag:
<body>
<video id="bgVideo" autoplay poster="videos/poster.png">
<source src="videos/test-h264-640x368-highqual-winff.mp4" type="video/mp4"/>
<source src="videos/test-640x368-webmvp8-miro.webm" type="video/webm"/>
<source src="videos/test-640x368-theora-miro.ogv" type="video/ogg"/>
</video>
<img id="bgImg" src="videos/poster.png" />
<!-- This image stretches exactly to the browser width/height and lies behind the video-->
<div id="bodyDummy">
Put all your content inside the bodydummy
-div and put the z-indexes correctly in CSS like this:
#bgImg{
position: absolute;
top: 0;
left: 0;
border: 0;
z-index: 1;
width: 100%;
height: 100%;
}
#bgVideo{
position: absolute;
top: 0;
left: 0;
border: 0;
z-index: 2;
width: 100%;
height: 100%;
}
#bodyDummy{
position: absolute;
top: 0;
left: 0;
z-index: 3;
overflow: auto;
width: 100%;
height: 100%;
}
Hope I could help. Let me know when you could find a solution that the video does not maintain the aspect ratio, so it could fill the whole browser window so we do not have to put a bgimage.
we can groupby the 'name' and 'month' columns, then call agg() functions of Panda’s DataFrame objects.
The aggregation functionality provided by the agg() function allows multiple statistics to be calculated per group in one calculation.
df.groupby(['name', 'month'], as_index = False).agg({'text': ' '.join})
I adapted one of the answers from the referenced question, but added the ability to define an explicit mapping for character names.
var char_names = {
160:'nbsp',
161:'iexcl',
220:'Uuml',
223:'szlig',
196:'Auml',
252:'uuml',
};
function HTMLEncode(str){
var aStr = str.split(''),
i = aStr.length,
aRet = [];
while (--i >= 0) {
var iC = aStr[i].charCodeAt();
if (iC < 32 || (iC > 32 && iC < 65) || iC > 127 || (iC>90 && iC<97)) {
if(char_names[iC]!=undefined) {
aRet.push('&'+char_names[iC]+';');
}
else {
aRet.push('&#'+iC+';');
}
} else {
aRet.push(aStr[i]);
}
}
return aRet.reverse().join('');
}
var text = "Übergroße Äpfel mit Würmer";
alert(HTMLEncode(text));
You could move the conditional to:
v = [22, 13, 45, 50, 98, 69, 43, 44, 1]
[ (x+1 if x >=45 else x+5) for x in v ]
But it's starting to look a little ugly, so you might be better off using a normal loop. Note that I used v
instead of l
for the list variable to reduce confusion with the number 1 (I think l
and O
should be avoided as variable names under any circumstances, even in quick-and-dirty example code).
function isPrevDate() {
alert("startDate is " + Startdate);
if(Startdate.length != 0 && Startdate !='') {
var start_date = Startdate.split('-');
alert("Input date: "+ start_date);
start_date=start_date[1]+"/"+start_date[2]+"/"+start_date[0];
alert("start date arrray format " + start_date);
var a = new Date(start_date);
//alert("The date is a" +a);
var today = new Date();
var day = today.getDate();
var mon = today.getMonth()+1;
var year = today.getFullYear();
today = (mon+"/"+day+"/"+year);
//alert(today);
var today = new Date(today);
alert("Today: "+today.getTime());
alert("a : "+a.getTime());
if(today.getTime() > a.getTime() )
{
alert("Please select Start date in range");
return false;
} else {
return true;
}
}
}
delete this line:
jsonp: 'jsonp_callback',
Or replace this line:
url: 'http://url.of.my.server/submit?callback=json_callback',
because currently you are asking jQuery to create a random callback function name with callback=?
and then telling jQuery that you want to use jsonp_callback
instead.
Disclaimer: I am from 42matters, who provides this data already on https://42matters.com/api , feel free to check it out or drop us a line.
As lenik mentioned there are open-source libraries that already help with obtaining some data from GPlay. If you want to build one yourself you can try to parse the Google Play App page, but you should pay attention to the following:
So that in mind getting one page metadata is a matter of fetching the page html and parsing it properly. With JSoup you can try:
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(crawlUrl);
HttpResponse rsp = httpClient.execute(request);
int statusCode = rsp.getStatusLine().getStatusCode();
if (statusCode == 200) {
String content = EntityUtils.toString(rsp.getEntity());
Document doc = Jsoup.parse(content);
//parse content, whatever you need
Element price = doc.select("[itemprop=price]").first();
}
For that very simple use case that should get you started. However, the moment you want to do more interesting stuff, things get complicated:
The list goes on. If you don't want to do all this by yourself, you can consider 42matters API, which supports lookup and search, top google charts, advanced queries and filters. And this for 35 languages and more than 50 countries.
[2]:
SomeVal=ActiveWorkbook.worksheets("Sheet2").cells(aRow,aCol).Value
did not work. However the following code only worked for me.
SomeVal = ThisWorkbook.Sheets(2).cells(aRow,aCol).Value
Do something like:
<?php
if ($_SERVER['SCRIPT_FILENAME'] == '<path to php include file>') {
header('HTTP/1.0 403 Forbidden');
exit('Forbidden');
}
?>
This answer is for "One Man" Team to solve this problem quickly without reading through too many information about "Team"
Step 1) Go to web browser, open your developer account. Go to Certificates, Identifiers & Profiles. Select Certificates / Production. You will see the certificate that was missing private key listed there. Click Revoke. And follow the instructions to remove this certificate. Step 2) That's it! go back to Xcode to Validate you app. It will now ask you to generate a new certificate. Now you happily uploading your apps.
/etc/services
is only advisory, it's a listing of well-known ports. It doesn't mean that anything is actually running on that port or that the named service will run on that port.
In PostgreSQL's case it's typical to use port 5432 if it is available. If it isn't, most installers will choose the next free port, usually 5433.
You can see what is actually running using the netstat
tool (available on OS X, Windows, and Linux, with command line syntax varying across all three).
This is further complicated on Mac OS X systems by the horrible mess of different PostgreSQL packages - Apple's ancient version of PostgreSQL built in to the OS, Postgres.app, Homebrew, Macports, the EnterpriseDB installer, etc etc.
What ends up happening is that the user installs Pg and starts a server from one packaging, but uses the psql
and libpq
client from a different packaging. Typically this occurs when they're running Postgres.app or homebrew Pg and connecting with the psql
that shipped with the OS. Not only do these sometimes have different default ports, but the Pg that shipped with Mac OS X has a different default unix socket path, so even if the server is running on the same port it won't be listening to the same unix socket.
Most Mac users work around this by just using tcp/ip with psql -h localhost
. You can also specify a port if required, eg psql -h localhost -p 5433
. You might have multiple PostgreSQL instances running so make sure you're connecting to the right one by using select version()
and SHOW data_directory;
.
You can also specify a unix socket directory; check the unix_socket_directories
setting of the PostgreSQL instance you wish to connect to and specify that with psql -h
, e.g.psql -h /tmp
.
A cleaner solution is to correct your system PATH
so that the psql
and libpq
associated with the PostgreSQL you are actually running is what's found first on the PATH
. The details of that depend on your Mac OS X version and which Pg packages you have installed. I don't use Mac and can't offer much more detail on that side without spending more time than is currently available.
In the end, both do the same thing. There are some differences in code: Web Services doesn't add a Root namespace of project, but Service Reference adds service classes to the namespace of the project. The ServiceSoapClient
class gets a different naming, which is not important. In working with TFS I'd rather use Service Reference because it works better with source control. Both work with SOAP protocols.
I find it better to use the Service Reference because it is new and will thus be better maintained.
My question was closed, I have no idea why . The accepted answer here is not the same as what I need.
This gives me the correct integer value for an IP..
public double IPAddressToNumber(string IPaddress)
{
int i;
string [] arrDec;
double num = 0;
if (IPaddress == "")
{
return 0;
}
else
{
arrDec = IPaddress.Split('.');
for(i = arrDec.Length - 1; i >= 0 ; i = i -1)
{
num += ((int.Parse(arrDec[i])%256) * Math.Pow(256 ,(3 - i )));
}
return num;
}
}
a = 10 * [0]
gives you an array of length 10, filled with zeroes.
It depends on your mark-up, but it can certainly be made to work, I used the following:
$(document).ready(
function() {
$('td p').slideUp();
$('td h2').click(
function(){
$(this).siblings('p').slideToggle();
}
);
}
);
<table>
<thead>
<tr>
<th>Actor</th>
<th>Which Doctor</th>
<th>Significant companion</th>
</tr>
</thead>
<tbody>
<tr>
<td><h2>William Hartnell</h2></td>
<td><h2>First</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
<td><h2>Susan Foreman</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
</tr>
<tr>
<td><h2>Patrick Troughton</h2></td>
<td><h2>Second</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
<td><h2>Jamie MacCrimmon</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
</tr>
<tr>
<td><h2>Jon Pertwee</h2></td>
<td><h2>Third</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
<td><h2>Jo Grant</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
</tr>
</tbody>
</table>
The way I approached it is to collapse specific elements within the cells of the row, so that, in my case, the row would slideUp()
as the paragraphs were hidden, and still leave an element, h2
to click on in order to re-show the content. If the row collapsed entirely there'd be no easily obvious way to bring it back.
As @Peter Ajtai noted, in the comments, the above approach focuses on only one cell (though deliberately). To expand all the child p
elements this would work:
$(document).ready(
function() {
$('td p').slideUp();
$('td h2').click(
function(){
$(this).closest('tr').find('p').slideToggle();
}
);
}
);
There is one more thing you should be aware of - MIME.
If you need to use a MIME type and it isn't supported by default, you can register your own handlers in config/initializers/mime_types.rb:
Mime::Type.register "text/markdown", :markdown
The default HTML editor (for static HTML) doesn't have a design view. To set the default editor to the Web forms editor which does have a design view,
Open with
HTML (web forms) editor
Set as default
OK
buttonOnce you have done that, all you need to do is click on design
or split
view as shown below:
var text = File.ReadAllText(file, Encoding.GetEncoding(codePage));
List of codepages : http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756(v=vs.85).aspx
look at the my.cnf
file, if there contain [client]
section, and the port
is other than real listen port (default 3306), you must connect the server with explicit parameter -P 3306
, e.g.
mysql -u root -h 127.0.0.1 -p -P 3306
the following two ways work well:
C:\>mongodb\bin\mongoimport --jsonArray -d test -c docs --file example2.json
C:\>mongodb\bin\mongoimport --jsonArray -d test -c docs < example2.json
if the collections are under a specific user, you can use -u -p --authenticationDatabase
Within the range 0 = c < 128, yes the '
is the only difference for CPython 2.6.
>>> set(unichr(c).encode('unicode_escape') for c in range(128)) - set(chr(c).encode('string_escape') for c in range(128))
set(["'"])
Outside of this range the two types are not exchangeable.
>>> '\x80'.encode('string_escape')
'\\x80'
>>> '\x80'.encode('unicode_escape')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can’t decode byte 0x80 in position 0: ordinal not in range(128)
>>> u'1'.encode('unicode_escape')
'1'
>>> u'1'.encode('string_escape')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: escape_encode() argument 1 must be str, not unicode
On Python 3.x, the string_escape
encoding no longer exists, since str
can only store Unicode.
I have had this error when connecting to a RabbitMQ MQTT server via TLS. I'm pretty sure the server is broken but anyway it worked with OpenSSL 1.0.1, but not OpenSSL 1.0.2.
You can check your version in Python using this:
import ssl
ssl.OPENSSL_VERSION
I'm not sure how to downgrade OpenSSL within Python (it seems to be statically linked on Windows at least), other than using an older version of Python.
This is an old question, but here's another way to do it.
You can modify the R code itself instead of the chunk options, by wrapping the source
call in suppressPackageStartupMessages()
, suppressMessages()
, and/or suppressWarnings()
. E.g:
```{r echo=FALSE}
suppressWarnings(suppressMessages(suppressPackageStartupMessages({
source("C:/Rscripts/source.R")
})
```
You can also put those functions around your library()
calls inside the "source.R"
script.
I use Git Bash for my Windows.
$ eval $(ssh-agent -s) //activates the connection
$ ssh-add ~/.ssh/id_rsa //adds the identity
$ clip < ~/.ssh/id_rsa.pub //THIS IS THE IMPORTANT ONE. This adds your key to your clipboard. Go back to GitHub and just paste it in, and voilá! You should be good to go.
Thought I would chip in here with when I have found ON
to be more useful than USING
. It is when OUTER
joins are introduced into queries.
ON
benefits from allowing the results set of the table that a query is OUTER
joining onto to be restricted while maintaining the OUTER
join. Attempting to restrict the results set through specifying a WHERE
clause will, effectively, change the OUTER
join into an INNER
join.
Granted this may be a relative corner case. Worth putting out there though.....
For example:
CREATE TABLE country (
countryId int(10) unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT,
country varchar(50) not null,
UNIQUE KEY countryUIdx1 (country)
) ENGINE=InnoDB;
insert into country(country) values ("France");
insert into country(country) values ("China");
insert into country(country) values ("USA");
insert into country(country) values ("Italy");
insert into country(country) values ("UK");
insert into country(country) values ("Monaco");
CREATE TABLE city (
cityId int(10) unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT,
countryId int(10) unsigned not null,
city varchar(50) not null,
hasAirport boolean not null default true,
UNIQUE KEY cityUIdx1 (countryId,city),
CONSTRAINT city_country_fk1 FOREIGN KEY (countryId) REFERENCES country (countryId)
) ENGINE=InnoDB;
insert into city (countryId,city,hasAirport) values (1,"Paris",true);
insert into city (countryId,city,hasAirport) values (2,"Bejing",true);
insert into city (countryId,city,hasAirport) values (3,"New York",true);
insert into city (countryId,city,hasAirport) values (4,"Napoli",true);
insert into city (countryId,city,hasAirport) values (5,"Manchester",true);
insert into city (countryId,city,hasAirport) values (5,"Birmingham",false);
insert into city (countryId,city,hasAirport) values (3,"Cincinatti",false);
insert into city (countryId,city,hasAirport) values (6,"Monaco",false);
-- Gah. Left outer join is now effectively an inner join
-- because of the where predicate
select *
from country left join city using (countryId)
where hasAirport
;
-- Hooray! I can see Monaco again thanks to
-- moving my predicate into the ON
select *
from country co left join city ci on (co.countryId=ci.countryId and ci.hasAirport)
;
If the string is empty, comboBox.getSelectedItem().toString()
will give a NullPointerException
. So better to typecast by (String)
.
SELECT *
FROM sys.tables t
INNER JOIN sys.objects o on o.object_id = t.object_id
WHERE o.is_ms_shipped = 0;
To match a substring inside parentheses excluding any inner parentheses you may use
\(([^()]*)\)
pattern. See the regex demo.
In JavaScript, use it like
var rx = /\(([^()]*)\)/g;
Pattern details
\(
- a (
char([^()]*)
- Capturing group 1: a negated character class matching any 0 or more chars other than (
and )
\)
- a )
char.To get the whole match, grab Group 0 value, if you need the text inside parentheses, grab Group 1 value.
Most up-to-date JavaScript code demo (using matchAll
):
const strs = ["I expect five hundred dollars ($500).", "I expect.. :( five hundred dollars ($500)."];
const rx = /\(([^()]*)\)/g;
strs.forEach(x => {
const matches = [...x.matchAll(rx)];
console.log( Array.from(matches, m => m[0]) ); // All full match values
console.log( Array.from(matches, m => m[1]) ); // All Group 1 values
});
_x000D_
Legacy JavaScript code demo (ES5 compliant):
var strs = ["I expect five hundred dollars ($500).", "I expect.. :( five hundred dollars ($500)."];
var rx = /\(([^()]*)\)/g;
for (var i=0;i<strs.length;i++) {
console.log(strs[i]);
// Grab Group 1 values:
var res=[], m;
while(m=rx.exec(strs[i])) {
res.push(m[1]);
}
console.log("Group 1: ", res);
// Grab whole values
console.log("Whole matches: ", strs[i].match(rx));
}
_x000D_
just replace JFrame
to JDialog
in class
public class MyDialog extends JFrame // delete JFrame and write JDialog
and then write setModal(true);
in constructor
After that you will be able to construct your Form in netbeans and the form becomes modal
Incase you're running some command with sudo, it won't allow it. Sudo needs a tty.
All the options above create new system process. Which is a performance nightmare. For this purpose I stitched together PHP module with "transparent" calls to Python.
https://github.com/kirmorozov/runpy
It may be tricky to compile, but will save system processes and will let you keep Python runtime between PHP calls.
Try using NumberFormat.getCurrencyInstance() to format your string before you put it into a TextView.
Something like:
NumberFormat currency = NumberFormat.getCurrencyInstance();
myTextView.setText(currency.format(dollars));
Edit - There is no inputType for currency that I could find in the docs. I imagine this is because there are some currencies that don't follow the same rule for decimal places, such as the Japanese Yen.
As LeffelMania mentioned, you can correct user input by using the above code with a TextWatcher
that is set on your EditText
.
Don't.
Because:
Edit: While I agree with the commenter who said "censorship is wrong", that is not the nature of this answer.
<run your last command on this line>
a=${?}
if [ ${a} -ne 0 ]; then echo "do something"; fi
use whatever command you want to use instead of the echo "do something"
command
@import url('https://fonts.googleapis.com/css?family=Muli:200,300,400,700&subset=latin-ext');_x000D_
body{ font-family: 'Muli', sans-serif; color:white;}_x000D_
#lists {_x000D_
width: 350px;_x000D_
height: 460px;_x000D_
overflow: hidden;_x000D_
background-color:#222222;_x000D_
padding:0px;_x000D_
float:left;_x000D_
margin: 10px;_x000D_
}_x000D_
_x000D_
.listimg {_x000D_
width: 100%;_x000D_
height: 220px;_x000D_
overflow: hidden;_x000D_
float: left;_x000D_
_x000D_
}_x000D_
#lists .listimg img {_x000D_
width: 350px;_x000D_
height: 220px;_x000D_
-moz-transition: all 0.3s;_x000D_
-webkit-transition: all 0.3s;_x000D_
transition: all 0.3s;_x000D_
}_x000D_
#lists:hover{cursor: pointer;}_x000D_
#lists:hover > .listimg img {_x000D_
-moz-transform: scale(1.3);_x000D_
-webkit-transform: scale(1.3);_x000D_
transform: scale(1.3);_x000D_
-webkit-filter: blur(5px);_x000D_
filter: blur(5px);_x000D_
}_x000D_
_x000D_
#lists h1{margin:20px; display:inline-block; margin-bottom:0px; }_x000D_
#lists p{margin:20px;}_x000D_
_x000D_
.listdetail{ text-align:right; font-weight:200; padding-top:6px;padding-bottom:6px;}
_x000D_
<div id="lists">_x000D_
<div class="listimg">_x000D_
<img src="https://lh3.googleusercontent.com/WeEw5I-wk2UO-y0u3Wsv8MxprCJjxTyTzvwdEc9pcdTsZVj_yK5thdtXNDKoZcUOHlegFhx7=w1920-h914-rw">_x000D_
</div>_x000D_
<div class="listtext">_x000D_
<h1>Eyes Lorem Impsum Samet</h1>_x000D_
<p>Impsum Samet Lorem</p>_x000D_
</div>_x000D_
<div class="listdetail">_x000D_
<p>Click for More Details...</p>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div id="lists">_x000D_
<div class="listimg">_x000D_
<img src="https://lh4.googleusercontent.com/fqK7aQ7auobK_NyXRYCsL9SOpVj6SoYqVlgbOENw6IqQvEWzym_3988798NlkGDzu0MWnR-7nxIhj7g=w1920-h870-rw">_x000D_
</div>_x000D_
<div class="listtext">_x000D_
<h1>Two Frogs Lorem Impsum Samet</h1>_x000D_
<p>Impsum Samet Lorem</p>_x000D_
</div>_x000D_
<div class="listdetail">_x000D_
<p>More Details...</p>_x000D_
</div>_x000D_
</div>
_x000D_
math.log
is the natural logarithm:
math.log(x[, base]) With one argument, return the natural logarithm of x (to base e).
Your equation is therefore:
n = math.log((1 + (FV * r) / p) / math.log(1 + r)))
Note that in your code you convert n to a str
twice which is unnecessary
I have been reviewing the source code of Entity Framework and found a way to actually update an entity if you know the Key property:
public void Update<T>(T item) where T: Entity
{
// assume Entity base class have an Id property for all items
var entity = _collection.Find(item.Id);
if (entity == null)
{
return;
}
_context.Entry(entity).CurrentValues.SetValues(item);
}
Otherwise, check the AddOrUpdate implementation for ideas.
Hope this help!
This is taken from the Python docs:
Identifiers (also referred to as names) are described by the following lexical definitions:
identifier ::= (letter|"_") (letter | digit | "_")*
letter ::= lowercase | uppercase
lowercase ::= "a"..."z"
uppercase ::= "A"..."Z"
digit ::= "0"..."9"
Identifiers are unlimited in length. Case is significant.
That should explain how to name your variables.
This way will let you run the test scripts from wherever you want without messing around with system variables from the command line.
This adds the main project folder to the python path, with the location found relative to the script itself, not relative to the current working directory.
import sys, os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
Add that to the top of all your test scripts. That will add the main project folder to the system path, so any module imports that work from there will now work. And it doesn't matter where you run the tests from.
You can obviously change the project_path_hack file to match your main project folder location.
If you want to make it easier for yourself by only having tabs, replace the spaces with tabs:
tr " " "\t" < <file> | sort <options>
Micah's solution below worked for me as the site I had to customise was not in UTF-8, so I could not use json; I'd vote it up but my rep isn't high enough.
function escapeJavaScriptText($string)
{
return str_replace("\n", '\n', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "\0..\37'\\")));
}
I really like the reflections library for doing this.
It provides a lot of different types of scanners (getTypesAnnotatedWith
, getSubTypesOf
, etc), and it is dead simple to write or extend your own.
I figured it out now. Here's the correct answer
CREATE PROCEDURE checkUser
(
brugernavn1 varchar(64),
password varchar(64)
)
BEGIN
SELECT COUNT(*) FROM bruger
WHERE bruger.brugernavn=brugernavn1
AND bruger.pass=password;
END;
@ points to a global var in mysql. The above syntax is correct.
SELECT id, GROUP_CONCAT( string SEPARATOR ' ') FROM table GROUP BY id
More details here.
From the link above, GROUP_CONCAT
: This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values.
Just one more line for @tofutim answer ... if you want custom field name for concatenated row ...
SELECT
(
col1 || '-' || SUBSTR('00' || col2, -2, 2) | '-' || SUBSTR('0000' || col3, -4, 4)
) AS my_column
FROM
mytable;
Tested on SQLite 3.8.8.3, Thanks!
Use the LEN
function:
Returns the number of characters of the specified string expression, excluding trailing blanks.
Below code will fix root = tk.Tk()
to its size before it was called:
root.resizable(False, False)
With the new C++ standard (may need special flags to be enabled on your compiler) you can simply do:
std::vector<int> v { 34,23 };
// or
// std::vector<int> v = { 34,23 };
Or even:
std::vector<int> v(2);
v = { 34,23 };
On compilers that don't support this feature (initializer lists) yet you can emulate this with an array:
int vv[2] = { 12,43 };
std::vector<int> v(&vv[0], &vv[0]+2);
Or, for the case of assignment to an existing vector:
int vv[2] = { 12,43 };
v.assign(&vv[0], &vv[0]+2);
Like James Kanze suggested, it's more robust to have functions that give you the beginning and end of an array:
template <typename T, size_t N>
T* begin(T(&arr)[N]) { return &arr[0]; }
template <typename T, size_t N>
T* end(T(&arr)[N]) { return &arr[0]+N; }
And then you can do this without having to repeat the size all over:
int vv[] = { 12,43 };
std::vector<int> v(begin(vv), end(vv));
Get content with Curl php
request server support Curl function, enable in httpd.conf in folder Apache
function UrlOpener($url)
global $output;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
If get content by google cache use Curl you can use this url: http://webcache.googleusercontent.com/search?q=cache:Put your url Sample: http://urlopener.mixaz.net/
For me turning on and off the setting on
iOS Simulator -> Hardware -> Keyboard -> Connect Hardware Keyboard
proved to fix the issue on simulators.
msgbox("your text here" & Environment.NewLine & "more text") is the easist way. no point in making your code harder or more ocmplicated than you need it to be...
import os
print len(os.listdir(os.getcwd()))
Looks like the path you gave doesn't have any bootstrap files in them.
href="~/lib/bootstrap/dist/css/bootstrap.min.css"
Make sure the files exist over there , else point the files to the correct path, which should be in your case
href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"
There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml
. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml
mediatype.
Based on @Jim Lewis's approach:
Here is a quick solution using find
and also sorting files by their modification date:
$ find directory/ -maxdepth 1 -type f -print0 | \
xargs -r0 stat -c "%y %n" | \
sort | cut -d' ' -f4- | \
xargs -d "\n" -I{} cmd -op1 {}
For sorting see:
http://www.commandlinefu.com/commands/view/5720/find-files-and-list-them-sorted-by-modification-time
C++ doesn't allow virtual template member functions right now. The most likely reason is the complexity of implementing it. Rajendra gives good reason why it can't be done right now but it could be possible with reasonable changes of the standard. Especially working out how many instantiations of a templated function actually exist and building up the vtable seems difficult if you consider the place of the virtual function call. Standards people just have a lot of other things to do right now and C++1x is a lot of work for the compiler writers as well.
When would you need a templated member function? I once came across such a situation where I tried to refactor a hierarchy with a pure virtual base class. It was a poor style for implementing different strategies. I wanted to change the argument of one of the virtual functions to a numeric type and instead of overloading the member function and override every overload in all sub-classes I tried to use virtual template functions (and had to find out they don't exist.)
You can simply use Request["recipient"]
to "read the HTTP values sent by a client during a Web request"
To access data from the QueryString, Form, Cookies, or ServerVariables collections, you can write Request["key"]
Source: MSDN
Update: Summarizing conversation
In order to view the values that MailGun is posting to your site you will need to read them from the web request that MailGun is making, record them somewhere and then display them on your page.
You should have one endpoint where MailGun will send the POST values to and another page that you use to view the recorded values.
It appears that right now you have one page. So when you view this page, and you read the Request values, you are reading the values from YOUR request, not MailGun.
Use dropna:
dat.dropna()
You can pass param how
to drop if all labels are nan or any of the labels are nan
dat.dropna(how='any') #to drop if any value in the row has a nan
dat.dropna(how='all') #to drop if all values in the row are nan
Hope that answers your question!
Edit 1:
In case you want to drop rows containing nan
values only from particular column(s), as suggested by J. Doe in his answer below, you can use the following:
dat.dropna(subset=[col_list]) # col_list is a list of column names to consider for nan values.
You must specify the file to be downloaded (attachment) by the client in the http header:
Response.ContentType = "application/vnd.ms-excel"
Response.AppendHeader "content-disposition", "attachment: filename=excelTest.xls"
http://classicasp.aspfaq.com/general/how-do-i-prompt-a-save-as-dialog-for-an-accepted-mime-type.html
I too got this exception on a Samsung S3. I suspect 2 root causes,
Use DDMS and look at your heap as you play your app, that will give you some indication on which setcontentview is creating the issue.
I copied all the drawables across all folders to get rid of problem 2.
Issue is resolved.
In case anybody is looking for methods to convert from/to C# and SQL Server formats, here goes a simple implementation:
private readonly string[] SqlServerTypes = { "bigint", "binary", "bit", "char", "date", "datetime", "datetime2", "datetimeoffset", "decimal", "filestream", "float", "geography", "geometry", "hierarchyid", "image", "int", "money", "nchar", "ntext", "numeric", "nvarchar", "real", "rowversion", "smalldatetime", "smallint", "smallmoney", "sql_variant", "text", "time", "timestamp", "tinyint", "uniqueidentifier", "varbinary", "varchar", "xml" };
private readonly string[] CSharpTypes = { "long", "byte[]", "bool", "char", "DateTime", "DateTime", "DateTime", "DateTimeOffset", "decimal", "byte[]", "double", "Microsoft.SqlServer.Types.SqlGeography", "Microsoft.SqlServer.Types.SqlGeometry", "Microsoft.SqlServer.Types.SqlHierarchyId", "byte[]", "int", "decimal", "string", "string", "decimal", "string", "Single", "byte[]", "DateTime", "short", "decimal", "object", "string", "TimeSpan", "byte[]", "byte", "Guid", "byte[]", "string", "string" };
public string ConvertSqlServerFormatToCSharp(string typeName)
{
var index = Array.IndexOf(SqlServerTypes, typeName);
return index > -1
? CSharpTypes[index]
: "object";
}
public string ConvertCSharpFormatToSqlServer(string typeName)
{
var index = Array.IndexOf(CSharpTypes, typeName);
return index > -1
? SqlServerTypes[index]
: null;
}
Edit: fixed typo
The python-ldap is based on OpenLDAP, so you need to have the development files (headers) in order to compile the Python module. If you're on Ubuntu, the package is called libldap2-dev
.
Debian/Ubuntu:
sudo apt-get install libsasl2-dev python-dev libldap2-dev libssl-dev
RedHat/CentOS:
sudo yum install python-devel openldap-devel
If you CAST
your data as a VARCHAR()
instead of explicitly CONVERT
ing your data you can simply
SELECT REPLACE(CAST(CreatedDate AS VARCHAR(20)),'Jan 1 1900 12:00AM','')
The CAST
will automatically return your Date then as Jun 18 2020 12:46PM
fix length strings formats which you can additionally SUBSTRING()
SELECT SUBSTRING(REPLACE(CAST(CreatedDate AS VARCHAR(20)),'Jan 1 1900 12:00AM',''),1,11)
Output
Jun 18 2020
jQuery has few functions which work with text, if you use text()
one, it will do the job for you:
$("#regTitle").text("Hello World");
Also, you can use html()
instead, if you have any html tag...
Msg * "insert your message here"
works fine, just save as a .bat file in notepad or make sure the format is set to "all files"
You can use Template Literals (enclosed with back-tick: `...`) instead for backgroundImage
property like this:
backgroundImage: `url(${Background})`
Just running the SELECT
statement will have no effect on the data. You have to use an UPDATE
statement with the REPLACE
to make the change occur:
UPDATE photos
SET caption = REPLACE(caption,'"','\'')
Here is a working sample: http://sqlize.com/7FjtEyeLAh
Multithreading For Performance, a tutorial by Gilles Debunne.
This is from the Android Developers Blog. The suggested code uses:
AsyncTasks
.FIFO cache
.garbage collect
-ed cache.Drawable
while you download.Similar to what Mark E has proposed, you have to come up with your own. Just to help you a bit, there is a neat article http://gleichmann.wordpress.com/2008/01/15/building-your-own-literals-in-java-tuples-and-maps/ which gives you a really neat way of creating tuples and maps that might be something you might want to consider.
In the service project do the following:
Now you need to make a setup project. The best thing to do is use the setup wizard.
Right click on your solution and add a new project: Add > New Project > Setup and Deployment Projects > Setup Wizard
a. This could vary slightly for different versions of Visual Studio. b. Visual Studio 2010 it is located in: Install Templates > Other Project Types > Setup and Deployment > Visual Studio Installer
On the second step select "Create a Setup for a Windows Application."
On the 3rd step, select "Primary output from..."
Click through to Finish.
Next edit your installer to make sure the correct output is included.
You can edit the installer output name by right clicking the Installer project in your solution and select Properties. Change the 'Output file name:' to whatever you want. By selecting the installer project as well and looking at the properties windows, you can edit the Product Name
, Title
, Manufacturer
, etc...
Next build your installer and it will produce an MSI and a setup.exe. Choose whichever you want to use to deploy your service.
Have a look at the following
@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<label for="file">Upload Image:</label>
<input type="file" name="file" id="file" style="width: 100%;" />
<input type="submit" value="Upload" class="submit" />
}
your controller should have action method which would accept HttpPostedFileBase
;
public ActionResult FileUpload(HttpPostedFileBase file)
{
if (file != null)
{
string pic = System.IO.Path.GetFileName(file.FileName);
string path = System.IO.Path.Combine(
Server.MapPath("~/images/profile"), pic);
// file is uploaded
file.SaveAs(path);
// save the image path path to the database or you can send image
// directly to database
// in-case if you want to store byte[] ie. for DB
using (MemoryStream ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
byte[] array = ms.GetBuffer();
}
}
// after successfully uploading redirect the user
return RedirectToAction("actionname", "controller name");
}
Update 1
In case you want to upload files using jQuery with asynchornously, then try this article.
the code to handle the server side (for multiple upload) is;
try
{
HttpFileCollection hfc = HttpContext.Current.Request.Files;
string path = "/content/files/contact/";
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
string fileName = "";
if (Request.Browser.Browser == "IE")
{
fileName = Path.GetFileName(hpf.FileName);
}
else
{
fileName = hpf.FileName;
}
string fullPathWithFileName = path + fileName;
hpf.SaveAs(Server.MapPath(fullPathWithFileName));
}
}
}
catch (Exception ex)
{
throw ex;
}
this control also return image name (in a javascript call back) which then you can use it to display image in the DOM.
Alternatively, you can try Async File Uploads in MVC 4.
cursor.execute(sql,array)
Only takes two arguments.
It will iterate the "array"-object and match ? in the sql-string.
(with sanity checks to avoid sql-injection)
A nice one-liner:
dist = numpy.linalg.norm(a-b)
However, if speed is a concern I would recommend experimenting on your machine. I've found that using math
library's sqrt
with the **
operator for the square is much faster on my machine than the one-liner NumPy solution.
I ran my tests using this simple program:
#!/usr/bin/python
import math
import numpy
from random import uniform
def fastest_calc_dist(p1,p2):
return math.sqrt((p2[0] - p1[0]) ** 2 +
(p2[1] - p1[1]) ** 2 +
(p2[2] - p1[2]) ** 2)
def math_calc_dist(p1,p2):
return math.sqrt(math.pow((p2[0] - p1[0]), 2) +
math.pow((p2[1] - p1[1]), 2) +
math.pow((p2[2] - p1[2]), 2))
def numpy_calc_dist(p1,p2):
return numpy.linalg.norm(numpy.array(p1)-numpy.array(p2))
TOTAL_LOCATIONS = 1000
p1 = dict()
p2 = dict()
for i in range(0, TOTAL_LOCATIONS):
p1[i] = (uniform(0,1000),uniform(0,1000),uniform(0,1000))
p2[i] = (uniform(0,1000),uniform(0,1000),uniform(0,1000))
total_dist = 0
for i in range(0, TOTAL_LOCATIONS):
for j in range(0, TOTAL_LOCATIONS):
dist = fastest_calc_dist(p1[i], p2[j]) #change this line for testing
total_dist += dist
print total_dist
On my machine, math_calc_dist
runs much faster than numpy_calc_dist
: 1.5 seconds versus 23.5 seconds.
To get a measurable difference between fastest_calc_dist
and math_calc_dist
I had to up TOTAL_LOCATIONS
to 6000. Then fastest_calc_dist
takes ~50 seconds while math_calc_dist
takes ~60 seconds.
You can also experiment with numpy.sqrt
and numpy.square
though both were slower than the math
alternatives on my machine.
My tests were run with Python 2.6.6.
If you're using eclipse you can open default.properties
file in your workspace and change the project target to the new sdk (target=android-8
for 2.2). I accidentally selected the 1.5 sdk for my version and didn't catch it until much later, but updating that and restarting eclipse seemed to have done the trick.
/**
* Shows confirmation dialog about signing in.
*/
private void startAuthDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
alertDialog.getWindow().setLayout(800, 1400);
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.auth_dialog, null);
alertDialog.getWindow().setContentView(dialogView);
EditText editText = (EditText) dialogView.findViewById(R.id.label_field);
editText.setText("test label");
}
There was another question that was closed as being a duplicate of this one, but if you read it closely, it's subtly different. So in case someone (like me) actually wants to split a list into a given number of almost equally sized sublists, then read on.
I simply ported the algorithm described here to Java.
@Test
public void shouldPartitionListIntoAlmostEquallySizedSublists() {
List<String> list = Arrays.asList("a", "b", "c", "d", "e", "f", "g");
int numberOfPartitions = 3;
List<List<String>> split = IntStream.range(0, numberOfPartitions).boxed()
.map(i -> list.subList(
partitionOffset(list.size(), numberOfPartitions, i),
partitionOffset(list.size(), numberOfPartitions, i + 1)))
.collect(toList());
assertThat(split, hasSize(numberOfPartitions));
assertEquals(list.size(), split.stream().flatMap(Collection::stream).count());
assertThat(split, hasItems(Arrays.asList("a", "b", "c"), Arrays.asList("d", "e"), Arrays.asList("f", "g")));
}
private static int partitionOffset(int length, int numberOfPartitions, int partitionIndex) {
return partitionIndex * (length / numberOfPartitions) + Math.min(partitionIndex, length % numberOfPartitions);
}
Here the fastest working implementation while keeping the same array ("mutable"):
function clearArray(array) {
while (array.length) {
array.pop();
}
}
FYI it cannot be simplified to while (array.pop())
: the tests will fail.
FYI Map and Set define clear()
, it would have seem logical to have clear()
for Array too.
TypeScript version:
function clearArray<T>(array: T[]) {
while (array.length) {
array.pop();
}
}
The corresponding tests:
describe('clearArray()', () => {
test('clear regular array', () => {
const array = [1, 2, 3, 4, 5];
clearArray(array);
expect(array.length).toEqual(0);
expect(array[0]).toEqual(undefined);
expect(array[4]).toEqual(undefined);
});
test('clear array that contains undefined and null', () => {
const array = [1, undefined, 3, null, 5];
clearArray(array);
expect(array.length).toEqual(0);
expect(array[0]).toEqual(undefined);
expect(array[4]).toEqual(undefined);
});
});
Here the updated jsPerf: http://jsperf.com/array-destroy/32 http://jsperf.com/array-destroy/152
Most browsers (in mine case Firefox) select the OK button by default. So I managed to solve this by using the following code. It basically presses enter for you and the file is downloaded.
Robot robot = new Robot();
// A short pause, just to be sure that OK is selected
Thread.sleep(3000);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
For me the basic oracle only was not installed. Please ensure you have oracle installed and then try checking host and port.
There's an even more sophisticated alternative. You can do the checking all client-side using a JQuery trick.
$('a[href^="http://"]').filter(function(){
return this.hostname && this.hostname !== location.hostname;
}).each(function() {
var link = jQuery(this);
var faviconURL =
link.attr('href').replace(/^(http:\/\/[^\/]+).*$/, '$1')+'/favicon.ico';
var faviconIMG = jQuery('<img src="favicon.png" alt="" />')['appendTo'](link);
var extImg = new Image();
extImg.src = faviconURL;
if (extImg.complete)
faviconIMG.attr('src', faviconURL);
else
extImg.onload = function() { faviconIMG.attr('src', faviconURL); };
});
From http://snipplr.com/view/18782/add-a-favicon-near-external-links-with-jquery/ (the original blog is presently down)
The approach I used when faced with this problem was to add the signer of the temporary certificate to the trusted authorities list on the computer in question.
I normally do testing with certificates created with CACERT, and adding them to my trusted authorities list worked swimmingly.
Doing it this way means you don't have to add any custom code to your application and it properly simulates what will happen when your application is deployed. As such, I think this is a superior solution to turning off the check programmatically.
I know this is an old thread but thought I should mention that the extern
keyword. I've recently ran into this issue and solved as follows
Helper.h
namespace DX
{
extern inline void ThrowIfFailed(HRESULT hr);
}
Helper.cpp
namespace DX
{
inline void ThrowIfFailed(HRESULT hr)
{
if (FAILED(hr))
{
std::stringstream ss;
ss << "#" << hr;
throw std::exception(ss.str().c_str());
}
}
}
PDOStatement has a public property $queryString. It should be what you want.
I've just notice that PDOStatement has an undocumented method debugDumpParams() which you may also want to look at.
There is a more efficient way of doing this in Windows 7. SETX is installed by default and supports connecting to other systems.
To modify a remote system's global environment variables, you would use
setx /m /s HOSTNAME-GOES-HERE VariableNameGoesHere VariableValueGoesHere
This does not require restarting Windows Explorer.
You should use Root
to refer to the root element:
xmlFile.Root.Elements("Band")
If you want to find elements anywhere in the document use Descendants
instead:
xmlFile.Descendants("Band")
The easiest way I found is just to redirect the requests that trigger 404 to the client. This is done by adding an hashtag even when $locationProvider.html5Mode(true)
is set.
This trick works for environments with more Web Application on the same Web Site and requiring URL integrity constraints (E.G. external authentication). Here is step by step how to do
Set the <base>
element properly
<base href="@(Request.ApplicationPath + "/")">
First redirect 404 to a custom page, for example "Home/Error"
<system.web>
<customErrors mode="On">
<error statusCode="404" redirect="~/Home/Error" />
</customErrors>
</system.web>
Implement a simple ActionResult
to "translate" input in a clientside route.
public ActionResult Error(string aspxerrorpath) {
return this.Redirect("~/#/" + aspxerrorpath);
}
This is the simplest way.
It is possible (advisable?) to enhance the Error function with some improved logic to redirect 404 to client only when url is valid and let the 404 trigger normally when nothing will be found on client. Let's say you have these angular routes
.when("/", {
templateUrl: "Base/Home",
controller: "controllerHome"
})
.when("/New", {
templateUrl: "Base/New",
controller: "controllerNew"
})
.when("/Show/:title", {
templateUrl: "Base/Show",
controller: "controllerShow"
})
It makes sense to redirect URL to client only when it start with "/New" or "/Show/"
public ActionResult Error(string aspxerrorpath) {
// get clientside route path
string clientPath = aspxerrorpath.Substring(Request.ApplicationPath.Length);
// create a set of valid clientside path
string[] validPaths = { "/New", "/Show/" };
// check if clientPath is valid and redirect properly
foreach (string validPath in validPaths) {
if (clientPath.StartsWith(validPath)) {
return this.Redirect("~/#/" + clientPath);
}
}
return new HttpNotFoundResult();
}
This is just an example of improved logic, of course every web application has different needs
Very simple example and it always works.
/**
* Setup stretch and scrollable TabLayout.
* The TabLayout initial parameters in layout must be:
* android:layout_width="wrap_content"
* app:tabMaxWidth="0dp"
* app:tabGravity="fill"
* app:tabMode="fixed"
*
* @param context your Context
* @param tabLayout your TabLayout
*/
public static void setupStretchTabLayout(Context context, TabLayout tabLayout) {
tabLayout.post(() -> {
ViewGroup.LayoutParams params = tabLayout.getLayoutParams();
if (params.width == ViewGroup.LayoutParams.MATCH_PARENT) { // is already set up for stretch
return;
}
int deviceWidth = context.getResources()
.getDisplayMetrics().widthPixels;
if (tabLayout.getWidth() < deviceWidth) {
tabLayout.setTabMode(TabLayout.MODE_FIXED);
params.width = ViewGroup.LayoutParams.MATCH_PARENT;
} else {
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
params.width = ViewGroup.LayoutParams.WRAP_CONTENT;
}
tabLayout.setLayoutParams(params);
});
}
Everyone who answered before me is correct. You use it kind of as an alias shortcut name for a table when you have long queries or queries that have joins. Here's a couple examples.
Example 1
SELECT P.ProductName,
P.ProductGroup,
P.ProductRetailPrice
FROM Products AS P
Example 2
SELECT P.ProductName,
P.ProductRetailPrice,
O.Quantity
FROM Products AS P
LEFT OUTER JOIN Orders AS O ON O.ProductID = P.ProductID
WHERE O.OrderID = 123456
Example 3 It's a good practice to use the AS keyword, and very recommended, but it is possible to perform the same query without one (and I do often).
SELECT P.ProductName,
P.ProductRetailPrice,
O.Quantity
FROM Products P
LEFT OUTER JOIN Orders O ON O.ProductID = P.ProductID
WHERE O.OrderID = 123456
As you can tell, I left out the AS keyword in the last example. And it can be used as an alias.
Example 4
SELECT P.ProductName AS "Product",
P.ProductRetailPrice AS "Retail Price",
O.Quantity AS "Quantity Ordered"
FROM Products P
LEFT OUTER JOIN Orders O ON O.ProductID = P.ProductID
WHERE O.OrderID = 123456
Output of Example 4
Product Retail Price Quantity Ordered
Blue Raspberry Gum $10 pk/$50 Case 2 Cases
Twizzler $5 pk/$25 Case 10 Cases
You can do this:
And to capture locale. You can do this:
private static final String LOCALE = LocaleContextHolder.getLocale().getLanguage()
+ "-" + LocaleContextHolder.getLocale().getCountry();
To check if this extensions are enabled or not, you can create a php file i.e. info.php
and write the following code there:
<?php
echo "GD: ", extension_loaded('gd') ? 'OK' : 'MISSING', '<br>';
echo "XML: ", extension_loaded('xml') ? 'OK' : 'MISSING', '<br>';
echo "zip: ", extension_loaded('zip') ? 'OK' : 'MISSING', '<br>';
?>
That's it.
Swift 3:
Simplest way to adjust only size:
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as! UITableViewHeaderFooterView
if let textlabel = header.textLabel {
textlabel.font = textlabel.font.withSize(15)
}
}
first_list = [1, 2, 2, 5]
second_list = [2, 5, 7, 9]
print( set( first_list + second_list ) )
I got this error because I have installed "Eclipse IDE for Enterprise Java Developers", I uninstalled this and installed "Eclipse IDE for Java Developers". Problem solved for me.
UICollectionView is same as UITableView but it gives us the additional functionality of simply creating a grid view, which is a bit problematic in UITableView. It will be a very long post I mention a link from where you will get everything in simple steps.
You can use the instanceof operator to test to see if it is a double prior to casting. You can then safely cast it to a double. In addition you can test it against other known types (e.g. Integer) and then coerce them into a double manually if desired.
Double d = null;
if (obj instanceof Double) {
d = (Double) obj;
}
The reason you separate the login and non-login shell is because the .bashrc
file is reloaded every time you start a new copy of Bash. The .profile
file is loaded only when you either log in or use the appropriate flag to tell Bash to act as a login shell.
Personally,
PATH
setup into a .profile
file (because I sometimes use other shells);.bashrc
file;I put this
#!/bin/bash
#
# CRM .bash_profile Time-stamp: "2008-12-07 19:42"
#
# echo "Loading ${HOME}/.bash_profile"
source ~/.profile # get my PATH setup
source ~/.bashrc # get my Bash aliases
in my .bash_profile
file.
Oh, and the reason you need to type bash
again to get the new alias is that Bash loads your .bashrc
file when it starts but it doesn't reload it unless you tell it to. You can reload the .bashrc
file (and not need a second shell) by typing
source ~/.bashrc
which loads the .bashrc
file as if you had typed the commands directly to Bash.
Find out two pieces of information
$> telnet <hostname or ip> <port>
Assuming the daemon is up and running and listening on that port it should etablish a telnet session. Likely causes:
I prefer the answer of tabSF . implementing the same to your answer. here below is my approach
Worksheets("Sheet1").Range("A1").Value = "=IF(Sheet1!A1=0," & CHR(34) & CHR(34) & ",Sheet1!A1)"
void foo<TOne, TTwo>()
where TOne : BaseOne
where TTwo : BaseTwo
More info here:
http://msdn.microsoft.com/en-us/library/d5x73970.aspx
For starters, you can "disable" the option from being selected accidentally by users:
<option value="" disabled="disabled">Choose an option</option>
Then, inside your JavaScript event (doesn't matter whether it is jQuery or JavaScript), for your form to validate whether it is set, do:
select = document.getElementById('select'); // or in jQuery use: select = this;
if (select.value) {
// value is set to a valid option, so submit form
return true;
}
return false;
Or something to that effect.
That's because the response from chrome.runtime.sendMessage
is asynchronous; here's the order of operations:
var newDeals = [];
// (1) first chrome.runtime.sendMessage is called, and *registers a callback*
// so that when the data comes back *in the future*
// the function will be called
chrome.runtime.sendMessage({...}, function(deals) {
// (3) sometime in the future, this function runs,
// but it's too late
newDeals = deals;
});
// (2) this is called immediately, `newDeals` is an empty array
this.setState({ deals: newDeals });
When you pause the script with the debugger, you're giving the extension time to call the callback; by the time you continue, the data has arrived and it appears to work.
To fix, you want to do the setState
call after the data comes back from the Chrome extension:
var newDeals = [];
// (1) first chrome.runtime.sendMessage is called, and *registers a callback*
// so that when the data comes back *in the future*
// the function will be called
chrome.runtime.sendMessage({...}, function(deals) {
// (2) sometime in the future, this function runs
newDeals = deals;
// (3) now you can call `setState` with the data
this.setState({ deals: newDeals });
}.bind(this)); // Don't forget to bind(this) (or use an arrow function)
[Edit]
If this doesn't work for you, check out the other answers on this question, which explain other reasons your component might not be updating.
Use Array.CreateInstance
to create an array dynamically.
private Update BuildMetaData(MetaData[] nvPairs)
{
Update update = new Update();
InputProperty[] ip = Array.CreateInstance(typeof(InputProperty), nvPairs.Count()) as InputProperty[];
int i;
for (i = 0; i < nvPairs.Length; i++)
{
if (nvPairs[i] == null) break;
ip[i] = new InputProperty();
ip[i].Name = "udf:" + nvPairs[i].Name;
ip[i].Val = nvPairs[i].Value;
}
update.Items = ip;
return update;
}
There's an easy way to do that. Very easy. Since I noticed that
$scope.yourModel = [];
removes all $scope.yourModel array list you can do like this
function deleteAnObjectByKey(objects, key) {
var clonedObjects = Object.assign({}, objects);
for (var x in clonedObjects)
if (clonedObjects.hasOwnProperty(x))
if (clonedObjects[x].id == key)
delete clonedObjects[x];
$scope.yourModel = clonedObjects;
}
The $scope.yourModel will be updated with the clonedObjects.
Hope that helps.
You can install the version you need easily:
First get source:
$ wget https://ftp.gnu.org/gnu/automake/automake-1.15.tar.gz
Unpack it:
$ tar -xzvf automake-1.15.tar.gz
Build and install:
$ cd automake-1.15
$ ./configure --prefix=/opt/aclocal-1.15
$ make
$ sudo mkdir -p /opt
$ sudo make install
Use it:
$ export PATH=/opt/aclocal-1.15/bin:$PATH
$ aclocal --version
aclocal (GNU automake) 1.15
Now when aclocal is called, you get the right version.
Yes. Strings can be seen as character arrays, and the way to access a position of an array is to use the []
operator. Usually there's no problem at all in using $str[0]
(and I'm pretty sure is much faster than the substr()
method).
There is only one caveat with both methods: they will get the first byte, rather than the first character. This is important if you're using multibyte encodings (such as UTF-8). If you want to support that, use mb_substr()
. Arguably, you should always assume multibyte input these days, so this is the best option, but it will be slightly slower.
You may use scala-code, which is compatible to java, and allows multiline-Strings enclosed with """:
package foobar
object SWrap {
def bar = """John said: "This is
a test
a bloody test,
my dear." and closed the door."""
}
(note the quotes inside the string) and from java:
String s2 = foobar.SWrap.bar ();
Whether this is more comfortable ...?
Another approach, if you often handle long text, which should be placed in your sourcecode, might be a script, which takes the text from an external file, and wrappes it as a multiline-java-String like this:
sed '1s/^/String s = \"/;2,$s/^/\t+ "/;2,$s/$/"/' file > file.java
so that you may cut-and-paste it easily into your source.
output = rs.getString("column");// if data is null `output` would be null, so there is no chance of NPE unless `rs` is `null`
if(output == null){// if you fetched null value then initialize output with blank string
output= "";
}
There is a sorting algorithm in the standard library, in the header <algorithm>
. It sorts inplace, so if you do the following, your original word will become sorted.
std::sort(word.begin(), word.end());
If you don't want to lose the original, make a copy first.
std::string sortedWord = word;
std::sort(sortedWord.begin(), sortedWord.end());
If
should be if
. Your program should look like this:
answer = raw_input("Is the information correct? Enter Y for yes or N for no")
if answer.upper() == 'Y':
print("this will do the calculation")
else:
exit()
Note also that the indentation is important, because it marks a block in Python.
You need to setup a SDK for Java projects, like @rizzletang said, but you don't need to create a new project, you can do it from the Welcome
screen.
On the bottom right, select Configure > Project Defaults > Project Structure
:
Picking the Project
tab on the left will show that you have no SDK selected:
Just click the New...
button on the right hand side of the dropdown and point it to your JDK. After that, you can go back to the import screen and it should just show up.
Does it support
<!DOCTYPE html>
Yes it does.
Perhaps a better question is what modern web features IE8 supports. Some of the best places to answer that are caniuse.com, html5test.com, and browserscope.org.
HTML5 means a lot of different things to different people. These days, it means HTML, CSS, and JavaScript functionality. The term is becoming a bit "Web 2.0"-like.
Unfortunately an ajax request gets the entire file, but you can filter the content once it's retrieved:
$.ajax({
url:href,
type:'GET',
success: function(data) {
var content = $('<div>').append(data).find('#content');
$('#content').html( content );
}
});
Note the use of a dummy element as find()
only works with descendants, and won't find root elements.
or let jQuery filter it for you:
$('#content').load(href + ' #IDofDivToFind');
I'm assuming this isn't a cross domain request, as that won't work, only pages on the same domain.
For what it's worth, here is my way:
List<string> list = new List<string>(new string[] { "cat", "Dog", "parrot", "dog", "parrot", "goat", "parrot", "horse", "goat" });
Dictionary<string, int> wordCount = new Dictionary<string, int>();
//count them all:
list.ForEach(word =>
{
string key = word.ToLower();
if (!wordCount.ContainsKey(key))
wordCount.Add(key, 0);
wordCount[key]++;
});
//remove words appearing only once:
wordCount.Keys.ToList().FindAll(word => wordCount[word] == 1).ForEach(key => wordCount.Remove(key));
Console.WriteLine(string.Format("Found {0} duplicates in the list:", wordCount.Count));
wordCount.Keys.ToList().ForEach(key => Console.WriteLine(string.Format("{0} appears {1} times", key, wordCount[key])));
Assuming your df.index is sorted you can use:
df.loc[df.index.max() + 1] = None
It handles well different indexes and column types.
[EDIT] it works with pd.DatetimeIndex if there is a constant frequency, otherwise we must specify the new index exactly e.g:
df.loc[df.index.max() + pd.Timedelta(milliseconds=1)] = None
long example:
df = pd.DataFrame([[pd.Timestamp(12432423), 23, 'text_field']],
columns=["timestamp", "speed", "text"],
index=pd.DatetimeIndex(start='2111-11-11',freq='ms', periods=1))
df.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 1 entries, 2111-11-11 to 2111-11-11
Freq: L
Data columns (total 3 columns):
timestamp 1 non-null datetime64[ns]
speed 1 non-null int64
text 1 non-null object
dtypes: datetime64[ns](1), int64(1), object(1)
memory usage: 32.0+ bytes
df.loc[df.index.max() + 1] = None
df.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 2 entries, 2111-11-11 00:00:00 to 2111-11-11 00:00:00.001000
Data columns (total 3 columns):
timestamp 1 non-null datetime64[ns]
speed 1 non-null float64
text 1 non-null object
dtypes: datetime64[ns](1), float64(1), object(1)
memory usage: 64.0+ bytes
df.head()
timestamp speed text
2111-11-11 00:00:00.000 1970-01-01 00:00:00.012432423 23.0 text_field
2111-11-11 00:00:00.001 NaT NaN NaN
It's the other way around: =
and ==
are for string comparisons, -eq
is for numeric ones. -eq
is in the same family as -lt
, -le
, -gt
, -ge
, and -ne
, if that helps you remember which is which.
==
is a bash-ism, by the way. It's better to use the POSIX =
. In bash the two are equivalent, and in plain sh =
is the only one guaranteed to work.
$ a=foo
$ [ "$a" = foo ]; echo "$?" # POSIX sh
0
$ [ "$a" == foo ]; echo "$?" # bash specific
0
$ [ "$a" -eq foo ]; echo "$?" # wrong
-bash: [: foo: integer expression expected
2
(Side note: Quote those variable expansions! Do not leave out the double quotes above.)
If you're writing a #!/bin/bash
script then I recommend using [[
instead. The doubled form has more features, more natural syntax, and fewer gotchas that will trip you up. Double quotes are no longer required around $a
, for one:
$ [[ $a == foo ]]; echo "$?" # bash specific
0
See also:
It's worth noting that if you want a currently-focused field to update the keyboard type immediately, there's one extra step:
// textField is set to a UIKeyboardType other than UIKeyboardTypeEmailAddress
[textField setKeyboardType:UIKeyboardTypeEmailAddress];
[textField reloadInputViews];
Without the call to reloadInputViews
, the keyboard will not change until the selected field (the first responder) loses and regains focus.
A full list of the UIKeyboardType
values can be found here, or:
typedef enum : NSInteger {
UIKeyboardTypeDefault,
UIKeyboardTypeASCIICapable,
UIKeyboardTypeNumbersAndPunctuation,
UIKeyboardTypeURL,
UIKeyboardTypeNumberPad,
UIKeyboardTypePhonePad,
UIKeyboardTypeNamePhonePad,
UIKeyboardTypeEmailAddress,
UIKeyboardTypeDecimalPad,
UIKeyboardTypeTwitter,
UIKeyboardTypeWebSearch,
UIKeyboardTypeAlphabet = UIKeyboardTypeASCIICapable
} UIKeyboardType;
EDIT: The correct way to do this is in @LiviuT's answer!
You can always extend Angular's scope to allow you to remove such listeners like so:
//A little hack to add an $off() method to $scopes.
(function () {
var injector = angular.injector(['ng']),
rootScope = injector.get('$rootScope');
rootScope.constructor.prototype.$off = function(eventName, fn) {
if(this.$$listeners) {
var eventArr = this.$$listeners[eventName];
if(eventArr) {
for(var i = 0; i < eventArr.length; i++) {
if(eventArr[i] === fn) {
eventArr.splice(i, 1);
}
}
}
}
}
}());
And here's how it would work:
function myEvent() {
alert('test');
}
$scope.$on('test', myEvent);
$scope.$broadcast('test');
$scope.$off('test', myEvent);
$scope.$broadcast('test');
I am doing integration test, and needed this to debug the generated SQL statement in Entity Framework Core 2.1, so I use DebugLoggerProvider
or ConsoleLoggerProvider
like so:
[Fact]
public async Task MyAwesomeTest
{
//setup log to debug sql queries
var loggerFactory = new LoggerFactory();
loggerFactory.AddProvider(new DebugLoggerProvider());
loggerFactory.AddProvider(new ConsoleLoggerProvider(new ConsoleLoggerSettings()));
var builder = new DbContextOptionsBuilder<DbContext>();
builder
.UseSqlServer("my connection string") //"Server=.;Initial Catalog=TestDb;Integrated Security=True"
.UseLoggerFactory(loggerFactory);
var dbContext = new DbContext(builder.Options);
........
Here is a sample output from Visual Studio console:
Array.forEach
cannot be broken and using try...catch
or hacky methods such as Array.every
or Array.some
will only make your code harder to understand. There are only two solutions of this problem:
1) use a old for
loop: this will be the most compatible solution but can be very hard to read when used often in large blocks of code:
var testArray = ['a', 'b', 'c'];
for (var key = 0; key < testArray.length; key++) {
var value = testArray[key];
console.log(key); // This is the key;
console.log(value); // This is the value;
}
2) use the new ECMA6 (2015 specification) in cases where compatibility is not a problem. Note that even in 2016, only a few browsers and IDEs offer good support for this new specification. While this works for iterable objects (e.g. Arrays), if you want to use this on non-iterable objects, you will need to use the Object.entries
method. This method is scarcely available as of June 18th 2016 and even Chrome requires a special flag to enable it: chrome://flags/#enable-javascript-harmony
. For Arrays, you won't need all this but compatibility remains a problem:
var testArray = ['a', 'b', 'c'];
for (let [key, value] of testArray.entries()) {
console.log(key); // This is the key;
console.log(value); // This is the value;
}
3) A lot of people would agree that neither the first or second option are good candidates. Until option 2 becomes the new standard, most popular libraries such as AngularJS and jQuery offer their own loop methods which can be superior to anything available in JavaScript. Also for those who are not already using these big libraries and that are looking for lightweight options, solutions like this can be used and will almost be on par with ECMA6 while keeping compatibility with older browsers.
An endpoint is the 'connection point' of a service, tool, or application accessed over a network. In the world of software, any software application that is running and "listening" for connections uses an endpoint as the "front door." When you want to connect to the application/service/tool to exchange data you connect to its endpoint
Have you tried height="100%"
in the definition of your iframe ? It seems to do what you seek, if you add height:100%
in the css for "body" (if you do not, 100% will be "100% of your content").
EDIT: do not do this. The height
attribute (as well as the width
one) must have an integer as value, not a string.
Yes, you can delete data from iOS device support by the symbols of the operating system, one for each version for each architecture. It's used for debugging. If you don't need to support those devices any more, you can delete the directory without ill effect
I think this is bit round-about explanation but still it clarifies using real life example.
Small Example:
Let's say playing an audio involves three steps:
If your audio player does step 1,2,3 sequentially for every song then it is synchronous. You will have to wait for some time to hear the song till the song actually gets fetched and decompressed.
If your audio player does step 1,2,3 independent of each other, then it is asynchronous. ie. While playing audio 1 ( step 3), if it fetches audio 3 from harddisk in parallel (step 1) and it decompresses the audio 2 in parallel. (step 2 ) You will end up in hearing the song without waiting much for fetch and decompress.
var str = " \n this is a string \n \n \n"_x000D_
_x000D_
console.log(str);_x000D_
console.log(str.trim());
_x000D_
String.trim()
removes whitespace from the beginning and end of strings... including newlines.
const myString = " \n \n\n Hey! \n I'm a string!!! \n\n";
const trimmedString = myString.trim();
console.log(trimmedString);
// outputs: "Hey! \n I'm a string!!!"
Here's an example fiddle: http://jsfiddle.net/BLs8u/
NOTE! it only trims the beginning and end of the string, not line breaks or whitespace in the middle of the string.
Numeric primitives in class scope are initialized to zero when not explicitly initialized.
Numeric primitives in local scope (variables in methods) must be explicitly initialized.
If you are only worried about division by zero exceptions, checking that your double is not exactly zero works great.
if(value != 0)
//divide by value is safe when value is not exactly zero.
Otherwise when checking if a floating point value like double
or float
is 0, an error threshold is used to detect if the value is near 0, but not quite 0.
public boolean isZero(double value, double threshold){
return value >= -threshold && value <= threshold;
}
or you may try something like
"abc.def.ghi".substring(0,"abc.def.ghi".indexOf(c)-1);
<style type="text/css">
div.inline { display:inline; }
</style>
<div class="inline">a</div>
<div class="inline">b</div>
<div class="inline">c</div>
To add a little to @Bakuriu's answer:
If you already know where the warning is likely to occur then it's often cleaner to use the numpy.errstate
context manager, rather than numpy.seterr
which treats all subsequent warnings of the same type the same regardless of where they occur within your code:
import numpy as np
a = np.r_[1.]
with np.errstate(divide='raise'):
try:
a / 0 # this gets caught and handled as an exception
except FloatingPointError:
print('oh no!')
a / 0 # this prints a RuntimeWarning as usual
In my original example I had a = np.r_[0]
, but apparently there was a change in numpy's behaviour such that division-by-zero is handled differently in cases where the numerator is all-zeros. For example, in numpy 1.16.4:
all_zeros = np.array([0., 0.])
not_all_zeros = np.array([1., 0.])
with np.errstate(divide='raise'):
not_all_zeros / 0. # Raises FloatingPointError
with np.errstate(divide='raise'):
all_zeros / 0. # No exception raised
with np.errstate(invalid='raise'):
all_zeros / 0. # Raises FloatingPointError
The corresponding warning messages are also different: 1. / 0.
is logged as RuntimeWarning: divide by zero encountered in true_divide
, whereas 0. / 0.
is logged as RuntimeWarning: invalid value encountered in true_divide
. I'm not sure why exactly this change was made, but I suspect it has to do with the fact that the result of 0. / 0.
is not representable as a number (numpy returns a NaN in this case) whereas 1. / 0.
and -1. / 0.
return +Inf and -Inf respectively, per the IEE 754 standard.
If you want to catch both types of error you can always pass np.errstate(divide='raise', invalid='raise')
, or all='raise'
if you want to raise an exception on any kind of floating point error.
TextView pf = new TextView(context);
pf.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
For different layouts like ConstraintLayout
and others, they have their own LayoutParams
, like so:
pf.setLayoutParams(new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
or
parentView.addView(pf, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
After playing with it for a very long time, this is what I came up with:
jQuery.fn.scrollTo = function (elem) {
var b = $(elem);
this.scrollTop(b.position().top + b.height() - this.height());
};
and I call it like this
$("#basketListGridHolder").scrollTo('tr[data-uid="' + basketID + '"]');
It may also be, that you by mistake commented out such a line like require_once __DIR__.'/../vendor/autoload.php';
--- your namespaces are not loaded.
Or you forget to add a classmap to the composer, thus classes are not autoloaded and are not available. For example,
"autoload": {
"psr-4": {
"": "src/"
},
"classmap": [
"dir/YourClass.php",
]
},
"require": {
"php": ">=5.3.9",
"symfony/symfony": "2.8.*",
For an inner join, WHERE
and ON
can be used interchangeably. In fact, it's possible to use ON
in a correlated subquery. For example:
update mytable
set myscore=100
where exists (
select 1 from table1
inner join table2
on (table2.key = mytable.key)
inner join table3
on (table3.key = table2.key and table3.key = table1.key)
...
)
This is (IMHO) utterly confusing to a human, and it's very easy to forget to link table1
to anything (because the "driver" table doesn't have an "on" clause), but it's legal.
Replying to very old post. But maybe it will help some newbie and if non of the above works out.
Explanation: I know nobody wants explanation crap; rather the solution. But in one liner, you are trying to access a service from your local machine to a remote machine which does not trust your machine. You request need to gain the trust from remote server.
Solution: The following solution assumes that you have the following conditions met
Steps:
You need a .keystore extension file to signup your app. If you don't know how to create .keystore file; then follow along with the following section Create .keystore file or otherwise skip to next section Sign Apk File
Create .keystore file
Open Android Studio. Click top menu Build > Generate Signed APK. In the next window click the Create new... button. In the new window, please input in data in all fields. Remember the two Password field i recommend should have the same password; don't use different password; and also remember the save path at top most field Key store path:. After you input all the field click OK button.
Sign Apk File
Now you need to build a signed app with the .keystore file you just created. Follow these steps
Choose existing...
buttonKey store password
and Key password
fields. Also enter the aliasbuild.gradle
files, you need to select Build Types
and Flavors
.Build Types
choose release
from the dropdownFor Flavors
however it will depends on your settings in build.gradle
file. Choose staging
from this field. I used the following settings in the build.gradle
, you can use the same as mine, but make sure you change the applicationId
to your package name
productFlavors {
staging {
applicationId "com.yourapplication.package"
manifestPlaceholders = [icon: "@drawable/ic_launcher"]
buildConfigField "boolean", "CATALYST_DEBUG", "true"
buildConfigField "boolean", "ALLOW_INVALID_CERTIFICATE", "true"
}
production {
buildConfigField "boolean", "CATALYST_DEBUG", "false"
buildConfigField "boolean", "ALLOW_INVALID_CERTIFICATE", "false"
}
}
Click the bottom two Signature Versions
checkboxes and click Finish
button.
Almost There:
All the hardwork is done, now the movement of truth. Inorder to access the Staging server backed-up by proxy, you need to make some setting in your real testing Android devices.
Proxy Setting in Android Device:
Modify network
Advanced options
if you can't see the Proxy Hostname
fieldProxy Hostname
enter the host IP or name you want to connect. A typical staging server will be named as stg.api.mygoodcompany.com
9502
Save
buttonOne Last Stop:
Remember we generated the signed apk file in Sign APK File section. Now is the time to install that APK file.
adb install
name of the apk file
adb command not found
. Enter the full path as C:\Users\shah\AppData\Local\Android\sdk\platform-tools\adb.exe
install
name of the apk file
I hope the problem might be solved. If not please leave me a comments.
Salam!
This solved the problem for me!
Without the need for an external div. Just apply it to your given text box.
box-sizing: border-box;
With this property "The width and height properties (and min/max properties) includes content, padding and border, but not the margin"
See description of property at w3schools.
Hope this helps someone!
From version 9.1.4 you only need to import ReactiveFormsModule
For fast testing (<1 second) use buildroid with VirtualBox's first network card set to “host only network” and then run
C:\Program Files (x86)\Android\android-sdk\platform-tools>adb connect *.*.*.*:5555
connected to *.*.*.*:5555
(^) DOS / bash (v)
# adb connect *.*.*.*:5555
connected to *.*.*.*:5555
where *. *. * .* is the buildroid IP address you get by clicking the buildroid app in buildroid main screen.
You can't do it using environment variables. It's done via "non standard" options. Run: java -X
for details. The options you're looking for are -Xmx
and -Xms
(this is "initial" heap size, so probably what you're looking for.)
Just my two cents to this very old question. I would highly recommend taking a look at ElasticSearch.
Elasticsearch is a search server based on Lucene. It provides a distributed, multitenant-capable full-text search engine with a RESTful web interface and schema-free JSON documents. Elasticsearch is developed in Java and is released as open source under the terms of the Apache License.
The advantages over other FTS (full text search) Engines are:
We are using this search engine at our project and very happy with it.
Symfony 2.3 / 2.4:
This function get's all the errors. The ones on the form like "The CSRF token is invalid. Please try to resubmit the form." as well as additional errors on the form children which have no error bubbling.
private function getErrorMessages(\Symfony\Component\Form\Form $form) {
$errors = array();
foreach ($form->getErrors() as $key => $error) {
if ($form->isRoot()) {
$errors['#'][] = $error->getMessage();
} else {
$errors[] = $error->getMessage();
}
}
foreach ($form->all() as $child) {
if (!$child->isValid()) {
$errors[$child->getName()] = $this->getErrorMessages($child);
}
}
return $errors;
}
To get all errors as a string:
$string = var_export($this->getErrorMessages($form), true);
Symfony 2.5 / 3.0:
$string = (string) $form->getErrors(true, false);
Docs:
https://github.com/symfony/symfony/blob/master/UPGRADE-2.5.md#form
https://github.com/symfony/symfony/blob/master/UPGRADE-3.0.md#form (at the bottom: The method Form::getErrorsAsString() was removed
)
This is the simplest wat to get the File object to which a certain URL object is pointing at:
File file=new File(url.toURI());
Now, for your concrete questions:
- finding all resources in the META-INF "directory":
You can indeed get the File object pointing to this URL
Enumeration<URL> en=getClass().getClassLoader().getResources("META-INF");
if (en.hasMoreElements()) {
URL metaInf=en.nextElement();
File fileMetaInf=new File(metaInf.toURI());
File[] files=fileMetaInf.listFiles();
//or
String[] filenames=fileMetaInf.list();
}
- all resources named bla.xml (recursivly)
In this case, you'll have to do some custom code. Here is a dummy example:
final List<File> foundFiles=new ArrayList<File>();
FileFilter customFilter=new FileFilter() {
@Override
public boolean accept(File pathname) {
if(pathname.isDirectory()) {
pathname.listFiles(this);
}
if(pathname.getName().endsWith("bla.xml")) {
foundFiles.add(pathname);
return true;
}
return false;
}
};
//rootFolder here represents a File Object pointing the root forlder of your search
rootFolder.listFiles(customFilter);
When the code is run, you'll get all the found ocurrences at the foundFiles
List.
This could help you. It is a way to handle the touch outside event:
How to cancel an Dialog themed like Activity when touched outside the window?
By catching the event and doing nothing, I think you can prevent the closing. But what is strange though, is that the default behavior of your activity dialog should be not to close itself when you touch outside.
(PS: the code uses WindowManager.LayoutParams)
You could set the @Input
on the setter directly, as described below:
_allowDay: boolean;
get allowDay(): boolean {
return this._allowDay;
}
@Input() set allowDay(value: boolean) {
this._allowDay = value;
this.updatePeriodTypes();
}
See this Plunkr: https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p?p=preview.
As a general statement, its good to make your if conditionals as readable as possible. For your example, using ! is ok. the problem is when things look like
if ((a.b && c.d.e) || !f)
you might want to do something like
bool isOk = a.b;
bool isStillOk = c.d.e
bool alternateOk = !f
then your if statement is simplified to
if ( (isOk && isStillOk) || alternateOk)
It just makes the code more readable. And if you have to debug, you can debug the isOk set of vars instead of having to dig through the variables in scope. It is also helpful for dealing with NPEs -- breaking code out into simpler chunks is always good.
Its not ideal but you can use a proxy server and it works fine. For example go to hidemyass.com put in www.google.com and put the link it goes to in an iframe and it works!
public class AlarmReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
//this will update the UI with message
Reminder inst = Reminder.instance();
inst.setAlarmText("");
//this will sound the alarm tone
//this will sound the alarm once, if you wish to
//raise alarm in loop continuously then use MediaPlayer and setLooping(true)
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
//this will send a notification message
ComponentName comp = new ComponentName(context.getPackageName(),
AlarmService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
The React docs says:
Treat this.state as if it were immutable.
Your push
will mutate the state directly and that could potentially lead to error prone code, even if you are "resetting" the state again afterwards. F.ex, it could lead to that some lifecycle methods like componentDidUpdate
won’t trigger.
The recommended approach in later React versions is to use an updater function when modifying states to prevent race conditions:
this.setState(prevState => ({
arrayvar: [...prevState.arrayvar, newelement]
}))
The memory "waste" is not an issue compared to the errors you might face using non-standard state modifications.
Alternative syntax for earlier React versions
You can use concat
to get a clean syntax since it returns a new array:
this.setState({
arrayvar: this.state.arrayvar.concat([newelement])
})
In ES6 you can use the Spread Operator:
this.setState({
arrayvar: [...this.state.arrayvar, newelement]
})
The following lines can be added either in Apache directives or in .htaccess file:
RewriteEngine on
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Don't forget to apply the apache changes if you modify the vhost.
(based on the default Drupal7 .htaccess but should work in many cases)
but.onclick = callJavascriptFunction;
no double quotes no parentheses.
You are calling:
JSON.parse(scatterSeries)
But when you defined scatterSeries
, you said:
var scatterSeries = [];
When you try to parse it as JSON it is converted to a string (""
), which is empty, so you reach the end of the string before having any of the possible content of a JSON text.
scatterSeries
is not JSON. Do not try to parse it as JSON.
data
is not JSON either (getJSON
will parse it as JSON automatically).
ch
is JSON … but shouldn't be. You should just create a plain object in the first place:
var ch = {
"name": "graphe1",
"items": data.results[1]
};
scatterSeries.push(ch);
In short, for what you are doing, you shouldn't have JSON.parse
anywhere in your code. The only place it should be is in the jQuery library itself.
To set a values above or below the range of the colormap, you'll want to use the set_over
and set_under
methods of the colormap. If you want to flag a particular value, mask it (i.e. create a masked array), and use the set_bad
method. (Have a look at the documentation for the base colormap class: http://matplotlib.org/api/colors_api.html#matplotlib.colors.Colormap )
It sounds like you want something like this:
import matplotlib.pyplot as plt
import numpy as np
# Generate some data
x, y, z = np.random.random((3, 30))
z = z * 20 + 0.1
# Set some values in z to 0...
z[:5] = 0
cmap = plt.get_cmap('jet', 20)
cmap.set_under('gray')
fig, ax = plt.subplots()
cax = ax.scatter(x, y, c=z, s=100, cmap=cmap, vmin=0.1, vmax=z.max())
fig.colorbar(cax, extend='min')
plt.show()
You probably want to use some Unicode character encoding, for example UTF-8, and htmlspecialchars. Because there isn't any need to generate "HTML entities" for "all [the] applicable characters" (that is what htmlentities does according to the documentation) if it's already in your character set.
Using functional Python:
text=filter(lambda x:x!=',',map(str,text))
I was trying to follow the flow described here - but haven't luck to completely kill the session.. Then I fond additional step here:
http://wyding.blogspot.com/2013/08/solution-for-ora-01940-cannot-drop-user.html
What I did:
1. select 'alter system kill session ''' || sid || ',' || serial# || ''';' from v$session where username = '<your_schema>';
- as described below.
Out put will be something like this:alter system kill session '22,15' immediate;
2. alter system disconnect session '22,15' IMMEDIATE ;
- 22-sid, 15-serial - repeat the command for each returned session from previous command
3. Repeat steps 1-2 while select...
not return an empty table
4. Call
drop user...
What was missed - call alter system disconnect session '22,15' IMMEDIATE ;
for each of session returned by select 'alter system kill session '..
Try also with '--quit' option, which allows you to abort the current operation and further clear the sequencer state.
--quit Forget about the current operation in progress. Can be used to clear the sequencer state after a failed cherry-pick or revert.
--abort Cancel the operation and return to the pre-sequence state.
use help to see the original doc with more details, $ git help cherry-pick
I would avoid 'git reset --hard HEAD' that is too harsh and you might ended up doing some manual work.
This example program illustrates initialization of an array of C strings.
#include <stdio.h>
const char * array[] = {
"First entry",
"Second entry",
"Third entry",
};
#define n_array (sizeof (array) / sizeof (const char *))
int main ()
{
int i;
for (i = 0; i < n_array; i++) {
printf ("%d: %s\n", i, array[i]);
}
return 0;
}
It prints out the following:
0: First entry
1: Second entry
2: Third entry
You can also use DBMS_METADATA:
select dbms_metadata.get_ddl('FUNCTION', 'FGETALGOGROUPKEY', 'PADCAMPAIGN')
from dual