For Linux Mate 17.1 Go to Menu/All applications/Keyboard/Layouts tab/Click Add/Pick out your layout by country or by language/Click Add and a language icon (US, PT and so on) will show at Panel/Close Keyboard Preferences and just click over it at Panel to switch the input language.
If you want to use JDKs downloaded from Oracle's site, what worked for me (using Mint) is using update-alternatives:
I ran:
sudo update-alternatives --install /usr/bin/java java /home/aqeel/development/jdk/jdk1.6.0_35/bin/java 1
Now you can execute sudo update-alternatives --config java
and choose your java version.
export JAVA_HOME="/home/aqeel/development/jdk/jdk1.6.0_35"
statementNow, I had two JDKs downloaded (let's say the second has been extracted to /home/aqeel/development/jdk/jdk-10.0.1).
How can we change the JAVA_HOME dynamically based on the current java being used?
My solution is not very elegant, I'm pretty sure there are better options out there, but anyway:
To change the JAVA_HOME dynamically based on the chosen java alternative, I added this snippet to the ~/.bashrc:
export JAVA_HOME=$(update-alternatives --query java | grep Value: | awk -F'Value: ' '{print $2}' | awk -F'/bin/java' '{print $1}')
Finally (this is out of the scope) if you have to change the java version constantly, you might want to consider:
Adding an alias to your ~./bash_aliases:
alias change-java="sudo update-alternatives --config java"
(You might have to create the file and maybe uncomment the section related to this in ~/.bashrc)
On Windows :
1-Open Run Window by Winkey + R
2-Type services.msc
3-Search Postgres service based on version installed.
4-Click stop, start or restart the service option.
On Linux :
sudo systemctl restart postgresql
also instead of "restart" you can replace : status, stop or status.
Like Nathan, I often want to dump the results of a sqlalchemy or sqlsoup Query into a Pandas data frame. My own solution for this is:
query = session.query(tbl.Field1, tbl.Field2)
DataFrame(query.all(), columns=[column['name'] for column in query.column_descriptions])
this worked for me ...
On Android 4.2+, uncheck the option Settings > Security > Verify apps and/or Settings > Developer options > Verify apps over USB.
Do you want your function to react to an array argument or variable arguments? If the latter, try:
var func = function(...rest) {
alert(rest.length);
// In JS, don't use for..in with arrays
// use for..of that consumes array's pre-defined iterator
// or a more functional approach
rest.forEach((v) => console.log(v));
};
But if you wish to handle an array argument
var fn = function(arr) {
alert(arr.length);
for(var i of arr) {
console.log(i);
}
};
I was Working with Elastic SQL plugin. Query is done with GET method using cURL as below:
curl -XGET http://localhost:9200/_sql/_explain -H 'Content-Type: application/json' \
-d 'SELECT city.keyword as city FROM routes group by city.keyword order by city'
I exposed a custom port at public server, doing a reverse proxy with Basic Auth set.
This code, works fine plus Basic Auth Header:
$host = 'http://myhost.com:9200';
$uri = "/_sql/_explain";
$auth = "john:doe";
$data = "SELECT city.keyword as city FROM routes group by city.keyword order by city";
function restCurl($host, $uri, $data = null, $auth = null, $method = 'DELETE'){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host.$uri);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($method == 'POST')
curl_setopt($ch, CURLOPT_POST, 1);
if ($auth)
curl_setopt($ch, CURLOPT_USERPWD, $auth);
if (strlen($data) > 0)
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$resp = curl_exec($ch);
if(!$resp){
$resp = (json_encode(array(array("error" => curl_error($ch), "code" => curl_errno($ch)))));
}
curl_close($ch);
return $resp;
}
$resp = restCurl($host, $uri); //DELETE
$resp = restCurl($host, $uri, $data, $auth, 'GET'); //GET
$resp = restCurl($host, $uri, $data, $auth, 'POST'); //POST
$resp = restCurl($host, $uri, $data, $auth, 'PUT'); //PUT
The following C code fragment illustrates the difference between the pre and post increment and decrement operators:
int i;
int j;
Increment operators:
i = 1;
j = ++i; // i is now 2, j is also 2
j = i++; // i is now 3, j is 2
If maven is not creating Local Repository i.e .m2/repository folder then try below step.
In your Eclipse\Spring Tool Suite, Go to Window->preferences-> maven->user settings-> click on Restore Defaults-> Apply->Apply and close
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
$("#content").attr("src","http://vnexpress.net");
})
</script>
</head>
<body>
<iframe id="content"></div>
</body>
</html>
making a dynamycal width with mobile devices support
http://www.codeography.com/2011/06/14/dynamic-fixed-width-layout-with-css.html
$timeFirst = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;
You will then be able to use the seconds to find minutes, hours, days, etc.
Heap dumps anytime you wish to see what is being held in memory Out-of-memory errors Heap dumps - picture of in memory objects - used for memory analysis Java cores - also known as thread dumps or java dumps, used for viewing the thread activity inside the JVM at a given time. IBM javacores should a lot of additional information besides just the threads and stacks -- used to determine hangs, deadlocks, and reasons for performance degredation System cores
Spring MVC will give you the HttpRequest if you just add it to your controller method signature:
For instance:
/**
* Generate a PDF report...
*/
@RequestMapping(value = "/report/{objectId}", method = RequestMethod.GET)
public @ResponseBody void generateReport(
@PathVariable("objectId") Long objectId,
HttpServletRequest request,
HttpServletResponse response) {
// ...
// Here you can use the request and response objects like:
// response.setContentType("application/pdf");
// response.getOutputStream().write(...);
}
As you see, simply adding the HttpServletRequest
and HttpServletResponse
objects to the signature makes Spring MVC to pass those objects to your controller method. You'll want the HttpSession
object too.
EDIT: It seems that HttpServletRequest/Response are not working for some people under Spring 3. Try using Spring WebRequest/WebResponse objects as Eduardo Zola pointed out.
I strongly recommend you to have a look at the list of supported arguments that Spring MVC is able to auto-magically inject to your handler methods.
$_SERVER['SERVER_ADDR']
You use a for..in
loop for this. Be sure to check if the object owns the properties or all inherited properties are shown as well. An example is like this:
var obj = {a: 1, b: 2};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
}
}
Or if you need recursion to walk through all the properties:
var obj = {a: 1, b: 2, c: {a: 1, b: 2}};
function walk(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
walk(val);
}
}
}
walk(obj);
So do the following ,
Lets say your branch name is my_branch and this has the extra commits.
git checkout -b my_branch_with_extra_commits
(Keeping this branch saved under a different name)gitk
(Opens git console)git checkout my_branch
gitk
(This will open the git console )reset branch to here
" git pull --rebase origin branch_name_to _merge_to
git cherry-pick <SHA you copied in step 3. >
Now look at the local branch commit history and make sure everything looks good.
Split on &
to get name/value pairs, then split each pair on =
. Here's an example:
var str = "abc=foo&def=%5Basf%5D&xy%5Bz=5"
var obj = str.split("&").reduce(function(prev, curr, i, arr) {
var p = curr.split("=");
prev[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
return prev;
}, {});
Another approach, using regular expressions:
var obj = {};
str.replace(/([^=&]+)=([^&]*)/g, function(m, key, value) {
obj[decodeURIComponent(key)] = decodeURIComponent(value);
});
This is adapted from John Resig's "Search and Don’t Replace".
My solution using bootstrap components:
<a class="btn btn-primary" href="@Url.Action("resetpassword", "Account")">
<span class="glyphicon glyphicon-user"></span> Reset Password
</a>
Can't tell you how many times this has caught. me.
Guid myGuid = Guid.NewGuid();
To complement answers above...
If you are using EF, adorn the property with Data Annotation [Timestamp], then go to the overrided OnModelCreating, inside your context class, and add this Fluent API code:
modelBuilder.Entity<YourEntity>()
.Property(b => b.Timestamp)
.ValueGeneratedOnAddOrUpdate()
.IsConcurrencyToken()
.ForSqliteHasDefaultValueSql("CURRENT_TIMESTAMP");
It will make a default value to every data that will be insert into this table.
This will match a single non-ASCII character:
[^\x00-\x7F]
This is a valid PCRE (Perl-Compatible Regular Expression).
You can also use the POSIX shorthands:
[[:ascii:]]
- matches a single ASCII char[^[:ascii:]]
- matches a single non-ASCII char[^[:print:]]
will probably suffice for you.**
You can use std::map::at
member function, it returns a reference to the mapped value of the element identified with key k.
std::map<char,int> mymap = {
{ 'a', 0 },
{ 'b', 0 },
};
mymap.at('a') = 10;
mymap.at('b') = 20;
I had a similar problem, the problem was that the extension intl was duplicated.
You can check in file C:/xampp/php/php.ini and find "intl". In my case extension=intl is already present and I scrolled again and found a second intl "extension=php_intl.dll".
The extension must one to execution can't execution extension intl again. This will show error like this "Module 'intl' already loaded".
I fixed it by commenting out extension=php_intl.dll
using ";
" like this ;extension=php_intl.dll
. and restarted the apache service.
While "".join is more pythonic, and the correct answer for this problem, it is indeed possible to use a for loop.
If this is a homework assignment (please add a tag if this is so!), and you are required to use a for loop then what will work (although is not pythonic, and shouldn't really be done this way if you are a professional programmer writing python) is this:
endstring = ""
mylist = ['first', 'second', 'other']
for word in mylist:
print "This is the word I am adding: " + word
endstring = endstring + word
print "This is the answer I get: " + endstring
You don't need the 'prints', I just threw them in there so you can see what is happening.
Note that find . -type f | xargs grep whatever
sorts of solutions will run into "Argument list to long" errors when there are too many files matched by find.
The best bet is grep -r
but if that isn't available, use find . -type f -exec grep -H whatever {} \;
instead.
Personally, I think the "Big Bang" was caused when two GUIDs collided.
Take a look at NSXMLParser. It's a SAX-style parser. You should be able to use it to detect tags or other unwanted elements in the XML document and ignore them, capturing only pure text.
This query can be used in PHP code.
I have an ID column in this table, so I need check for duplication for all columns except this ID column:
#need to change values
SET @goodsType = 1, @sybType=5, @deviceId = asdf12345SDFasdf2345;
INSERT INTO `devices` (`goodsTypeId`, `goodsId`, `deviceId`) #need to change tablename and columnsnames
SELECT * FROM (SELECT @goodsType, @sybType, @deviceId) AS tmp
WHERE NOT EXISTS (
SELECT 'goodsTypeId' FROM `devices` #need to change tablename and columns names
WHERE `goodsTypeId` = @goodsType
AND `goodsId` = @sybType
AND `deviceId` = @deviceId
) LIMIT 1;
and now new item will be added only in case of there is not exist row with values configured in SET
string
Here is another way how you can format using 'f-string' format:
print(
f"{'Trades:':<15}{cnt:>10}",
f"\n{'Wins:':<15}{wins:>10}",
f"\n{'Losses:':<15}{losses:>10}",
f"\n{'Breakeven:':<15}{evens:>10}",
f"\n{'Win/Loss Ratio:':<15}{win_r:>10}",
f"\n{'Mean Win:':<15}{mean_w:>10}",
f"\n{'Mean Loss:':<15}{mean_l:>10}",
f"\n{'Mean:':<15}{mean_trd:>10}",
f"\n{'Std Dev:':<15}{sd:>10}",
f"\n{'Max Loss:':<15}{max_l:>10}",
f"\n{'Max Win:':<15}{max_w:>10}",
f"\n{'Sharpe Ratio:':<15}{sharpe_r:>10}",
)
This will provide the following output:
Trades: 2304
Wins: 1232
Losses: 1035
Breakeven: 37
Win/Loss Ratio: 1.19
Mean Win: 0.381
Mean Loss: -0.395
Mean: 0.026
Std Dev: 0.56
Max Loss: -3.406
Max Win: 4.09
Sharpe Ratio: 0.7395
What you are doing here is you are saying that the first column is 15 chars long and it's left justified and second column (values) is 10 chars long and it's right justified.
With current latest python 3.6.5
pip3 install PyQt5
works fine
Try using:
if(NewType* v = dynamic_cast<NewType*>(old)) {
// old was safely casted to NewType
v->doSomething();
}
This requires your compiler to have rtti support enabled.
EDIT: I've had some good comments on this answer!
Every time you need to use a dynamic_cast (or instanceof) you'd better ask yourself whether it's a necessary thing. It's generally a sign of poor design.
Typical workarounds is putting the special behaviour for the class you are checking for into a virtual function on the base class or perhaps introducing something like a visitor where you can introduce specific behaviour for subclasses without changing the interface (except for adding the visitor acceptance interface of course).
As pointed out dynamic_cast doesn't come for free. A simple and consistently performing hack that handles most (but not all cases) is basically adding an enum representing all the possible types your class can have and check whether you got the right one.
if(old->getType() == BOX) {
Box* box = static_cast<Box*>(old);
// Do something box specific
}
This is not good oo design, but it can be a workaround and its cost is more or less only a virtual function call. It also works regardless of RTTI is enabled or not.
Note that this approach doesn't support multiple levels of inheritance so if you're not careful you might end with code looking like this:
// Here we have a SpecialBox class that inherits Box, since it has its own type
// we must check for both BOX or SPECIAL_BOX
if(old->getType() == BOX || old->getType() == SPECIAL_BOX) {
Box* box = static_cast<Box*>(old);
// Do something box specific
}
I have used the below code in my existing project
<div class="form-group" [ngStyle]="{'border':isSubmitted && form_data.controls.first_name.errors?'1px solid red':'' }">
</div>
This is a rework of this answer which strips out irrelevant information, adds helpful comments, names variables more clearly, and improves the logic.
Don't forget to include the following permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
InternetHelper.java:
public class InternetHelper {
/**
* Get IP address from first non-localhost interface
*
* @param useIPv4 true=return ipv4, false=return ipv6
* @return address or empty string
*/
public static String getIPAddress(boolean useIPv4) {
try {
List<NetworkInterface> interfaces =
Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface interface_ : interfaces) {
for (InetAddress inetAddress :
Collections.list(interface_.getInetAddresses())) {
/* a loopback address would be something like 127.0.0.1 (the device
itself). we want to return the first non-loopback address. */
if (!inetAddress.isLoopbackAddress()) {
String ipAddr = inetAddress.getHostAddress();
boolean isIPv4 = ipAddr.indexOf(':') < 0;
if (isIPv4 && !useIPv4) {
continue;
}
if (useIPv4 && !isIPv4) {
int delim = ipAddr.indexOf('%'); // drop ip6 zone suffix
ipAddr = delim < 0 ? ipAddr.toUpperCase() :
ipAddr.substring(0, delim).toUpperCase();
}
return ipAddr;
}
}
}
} catch (Exception ignored) { } // if we can't connect, just return empty string
return "";
}
/**
* Get IPv4 address from first non-localhost interface
*
* @return address or empty string
*/
public static String getIPAddress() {
return getIPAddress(true);
}
}
Well, your code is not reproducible so we will never know for sure, but this is what help('break')
says:
break breaks out of a for, while or repeat loop; control is transferred to the first statement outside the inner-most loop.
So yes, break
only breaks the current loop. You can also see it in action with e.g.:
for (i in 1:10)
{
for (j in 1:10)
{
for (k in 1:10)
{
cat(i," ",j," ",k,"\n")
if (k ==5) break
}
}
}
Really kinda sad that no one has given you the correct answer....
In regex, ? makes it non greedy. By default regex will match as much as it can (greedy)
Simply add a ? and it will be non-greedy and match as little as possible!
Good luck, hope that helps.
The following code is Linux (maybe Unix) only, but it works in a real project.
private double getAverageValueByLinux() throws InterruptedException {
try {
long delay = 50;
List<Double> listValues = new ArrayList<Double>();
for (int i = 0; i < 100; i++) {
long cput1 = getCpuT();
Thread.sleep(delay);
long cput2 = getCpuT();
double cpuproc = (1000d * (cput2 - cput1)) / (double) delay;
listValues.add(cpuproc);
}
listValues.remove(0);
listValues.remove(listValues.size() - 1);
double sum = 0.0;
for (Double double1 : listValues) {
sum += double1;
}
return sum / listValues.size();
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
private long getCpuT throws FileNotFoundException, IOException {
BufferedReader reader = new BufferedReader(new FileReader("/proc/stat"));
String line = reader.readLine();
Pattern pattern = Pattern.compile("\\D+(\\d+)\\D+(\\d+)\\D+(\\d+)\\D+(\\d+)")
Matcher m = pattern.matcher(line);
long cpuUser = 0;
long cpuSystem = 0;
if (m.find()) {
cpuUser = Long.parseLong(m.group(1));
cpuSystem = Long.parseLong(m.group(3));
}
return cpuUser + cpuSystem;
}
When making an Android app in eclipse, just right-click on the res
folder, click New -> Other
, and select Android Icon Set
under Android.
This allows you to make more icons (or replace any existing ones) easily.
Indeed there is.
chmod a+x
is relative to the current state and just sets the x
flag. So a 640 file becomes 751 (or 750?), a 644 file becomes 755.
chmod 755
, however, sets the mask as written: rwxr-xr-x
, no matter how it was before. It is equivalent to chmod u=rwx,go=rx
.
Use LinkedList
instead. Than, you can create an array if necessary.
First you have to ensure that there is a SMTP server listening on port 25.
To look whether you have the service, you can try using TELNET client, such as:
C:\> telnet localhost 25
(telnet client by default is disabled on most recent versions of Windows, you have to add/enable the Windows component from Control Panel. In Linux/UNIX usually telnet client is there by default.
$ telnet localhost 25
If it waits for long then time out, that means you don't have the required SMTP service. If successfully connected you enter something and able to type something, the service is there.
If you don't have the service, you can use these:
If you are sure that you already have the service, may be the SMTP requires additional security credentials. If you can tell me what SMTP server listening on port 25 I may be able to tell you more.
Try
String regex = "[0-9]+";
or
String regex = "\\d+";
As per Java regular expressions, the +
means "one or more times" and \d
means "a digit".
Note: the "double backslash" is an escape sequence to get a single backslash - therefore, \\d
in a java String gives you the actual result: \d
References:
Edit: due to some confusion in other answers, I am writing a test case and will explain some more things in detail.
Firstly, if you are in doubt about the correctness of this solution (or others), please run this test case:
String regex = "\\d+";
// positive test cases, should all be "true"
System.out.println("1".matches(regex));
System.out.println("12345".matches(regex));
System.out.println("123456789".matches(regex));
// negative test cases, should all be "false"
System.out.println("".matches(regex));
System.out.println("foo".matches(regex));
System.out.println("aa123bb".matches(regex));
Isn't it necessary to add
^
and$
to the regex, so it won't match "aa123bb" ?
No. In java, the matches
method (which was specified in the question) matches a complete string, not fragments. In other words, it is not necessary to use ^\\d+$
(even though it is also correct). Please see the last negative test case.
Please note that if you use an online "regex checker" then this may behave differently. To match fragments of a string in Java, you can use the find
method instead, described in detail here:
Difference between matches() and find() in Java Regex
Won't this regex also match the empty string,
""
?*
No. A regex \\d*
would match the empty string, but \\d+
does not. The star *
means zero or more, whereas the plus +
means one or more. Please see the first negative test case.
Isn't it faster to compile a regex Pattern?
Yes. It is indeed faster to compile a regex Pattern once, rather than on every invocation of matches
, and so if performance implications are important then a Pattern
can be compiled and used like this:
Pattern pattern = Pattern.compile(regex);
System.out.println(pattern.matcher("1").matches());
System.out.println(pattern.matcher("12345").matches());
System.out.println(pattern.matcher("123456789").matches());
Consider the following example: If you want to change a single CSS property(say, color to 'blue'), then the below statement works fine.
document.getElementById("ele_id").style.color="blue";
But, for changing multiple properies the more robust way is using Object.assign()
or, object spread operator {...}
;
const ele=document.getElementById("ele_id");
const custom_style={
display: "block",
color: "red"
}
//Object.assign():
Object.assign(ele.style,custum_style);
Spread operator works similarly, just the syntax is a little different.
Each resource has references to other resources, either in hierarchy or links, so it's easy to browse around. This is an advantage to the human developing the client, saving he/she from constantly consulting the docs, and offering suggestions. It also means the server can change resource names unilaterally (as long as the client software doesn't hardcode the URLs).
You can CURL your way into any part of the API or use the web browser to navigate resources. Makes debugging and testing integration much easier.
Allows you to specify actions without having to hunt the correct wording. Imagine if OOP getters and setters weren't standardized, and some people used retrieve
and define
instead. You would have to memorize the correct verb for each individual access point. Knowing there's only a handful of verbs available counters that problem.
If you GET
a resource that doesn't exist, you can be sure to get a 404
error in a RESTful API. Contrast it with a non-RESTful API, which may return {error: "Not found"}
wrapped in God knows how many layers. If you need the extra space to write a message to the developer on the other side, you can always use the body of the response.
Imagine two APIs with the same functionality, one following REST and the other not. Now imagine the following clients for those APIs:
RESTful:
GET /products/1052/reviews
POST /products/1052/reviews "5 stars"
DELETE /products/1052/reviews/10
GET /products/1052/reviews/10
HTTP:
GET /reviews?product_id=1052
POST /post_review?product_id=1052 "5 stars"
POST /remove_review?product_id=1052&review_id=10
GET /reviews?product_id=1052&review=10
Now think of the following questions:
If the first call of each client worked, how sure can you be the rest will work too?
There was a major update to the API that may or may not have changed those access points. How much of the docs will you have to re-read?
Can you predict the return of the last query?
You have to edit the review posted (before deleting it). Can you do so without checking the docs?
Necromancing.
I assume when somebody lands here, he needs a foreign key to column in a table that contains non-unique keys.
The problem is, that if you have that problem, the database-schema is denormalized.
You're for example keeping rooms in a table, with a room-uid primary key, a DateFrom and a DateTo field, and another uid, here RM_ApertureID to keep track of the same room, and a soft-delete field, like RM_Status, where 99 means 'deleted', and <> 99 means 'active'.
So when you create the first room, you insert RM_UID and RM_ApertureID as the same value as RM_UID. Then, when you terminate the room to a date, and re-establish it with a new date range, RM_UID is newid(), and the RM_ApertureID from the previous entry becomes the new RM_ApertureID.
So, if that's the case, RM_ApertureID is a non-unique field, and so you can't set a foreign-key in another table.
And there is no way to set a foreign key to a non-unique column/index, e.g. in T_ZO_REM_AP_Raum_Reinigung (WHERE RM_UID is actually RM_ApertureID).
But to prohibit invalid values, you need to set a foreign key, otherwise, data-garbage is the result sooner rather than later...
Now what you can do in this case (short of rewritting the entire application) is inserting a CHECK-constraint, with a scalar function checking the presence of the key:
IF EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]') AND parent_object_id = OBJECT_ID(N'[dbo].[T_ZO_REM_AP_Raum_Reinigung]'))
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung DROP CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fu_Constaint_ValidRmApertureId]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fu_Constaint_ValidRmApertureId]
GO
CREATE FUNCTION [dbo].[fu_Constaint_ValidRmApertureId](
@in_RM_ApertureID uniqueidentifier
,@in_DatumVon AS datetime
,@in_DatumBis AS datetime
,@in_Status AS integer
)
RETURNS bit
AS
BEGIN
DECLARE @bNoCheckForThisCustomer AS bit
DECLARE @bIsInvalidValue AS bit
SET @bNoCheckForThisCustomer = 'false'
SET @bIsInvalidValue = 'false'
IF @in_Status = 99
RETURN 'false'
IF @in_DatumVon > @in_DatumBis
BEGIN
RETURN 'true'
END
IF @bNoCheckForThisCustomer = 'true'
RETURN @bIsInvalidValue
IF NOT EXISTS
(
SELECT
T_Raum.RM_UID
,T_Raum.RM_Status
,T_Raum.RM_DatumVon
,T_Raum.RM_DatumBis
,T_Raum.RM_ApertureID
FROM T_Raum
WHERE (1=1)
AND T_Raum.RM_ApertureID = @in_RM_ApertureID
AND @in_DatumVon >= T_Raum.RM_DatumVon
AND @in_DatumBis <= T_Raum.RM_DatumBis
AND T_Raum.RM_Status <> 99
)
SET @bIsInvalidValue = 'true' -- IF !
RETURN @bIsInvalidValue
END
GO
IF EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]') AND parent_object_id = OBJECT_ID(N'[dbo].[T_ZO_REM_AP_Raum_Reinigung]'))
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung DROP CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
GO
-- ALTER TABLE dbo.T_AP_Kontakte WITH CHECK ADD CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung WITH NOCHECK ADD CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
CHECK
(
NOT
(
dbo.fu_Constaint_ValidRmApertureId(ZO_RMREM_RM_UID, ZO_RMREM_GueltigVon, ZO_RMREM_GueltigBis, ZO_RMREM_Status) = 1
)
)
GO
IF EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]') AND parent_object_id = OBJECT_ID(N'[dbo].[T_ZO_REM_AP_Raum_Reinigung]'))
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung CHECK CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
GO
Here column name must be decimal.
select CAST(columnname AS decimal(38,0)) from table
Quick 'n dirty, regex-free, low-robustness chop-chop technique
string="US/Central - 10:26 PM (CST)"
etime="${string% [AP]M*}"
etime="${etime#* - }"
To avoid the fact that destroy_all
instantiates all the records and destroys them one at a time, you can use it directly from the model class.
So instead of :
u = User.find_by_name('JohnBoy')
u.usage_indexes.destroy_all
You can do :
u = User.find_by_name('JohnBoy')
UsageIndex.destroy_all "user_id = #{u.id}"
The result is one query to destroy all the associated records
This might be too late to share, but I have something to contribute which might help someone, I was trying to sub-class the UINavigationBar and wanted to make it look like ios 6 with black status bar and status bar text in white.
Here is what I found working for that
self.navigationController?.navigationBar.clipsToBounds = true
self.navigationController?.navigationBar.translucent = false
self.navigationController?.navigationBar.barStyle = .Black
self.navigationController?.navigationBar.barTintColor = UIColor.whiteColor()
It made my status bar background black, status bar text white and navigation bar's color white.
iOS 9.3, XCode 7.3.1
Apache Commons I/O provides FileUtils#readLines(), which should be fine for all but huge files: http://commons.apache.org/io/api-release/index.html. The 2.1 distribution includes FileUtils.lineIterator(), which would be suitable for large files. Google's Guava libraries include similar utilities.
Sorry, afaik, you cannot do that. To update attributes in two different tables, you will need to execute two separate statements. But they can be in a batch ( a set of SQL sent to the server in one round trip)
Optimistic locking is used when you don't expect many collisions. It costs less to do a normal operation but if the collision DOES occur you would pay a higher price to resolve it as the transaction is aborted.
Pessimistic locking is used when a collision is anticipated. The transactions which would violate synchronization are simply blocked.
To select proper locking mechanism you have to estimate the amount of reads and writes and plan accordingly.
The error is because fName
is included in the SELECT
list, but is not included in a GROUP BY
clause and is not part of an aggregate function (Count()
, Min()
, Max()
, Sum()
, etc.)
You can fix that problem by including fName
in a GROUP BY
. But then you will face the same issue with surname
. So put both in the GROUP BY
:
SELECT
fName,
surname,
Count(*) AS num_rows
FROM
author
INNER JOIN book
ON author.aID = book.authorID;
GROUP BY
fName,
surname
Note I used Count(*)
where you wanted SUM(orders.quantity)
. However, orders
isn't included in the FROM
section of your query, so you must include it before you can Sum()
one of its fields.
If you have Access available, build the query in the query designer. It can help you understand what features are possible and apply the correct Access SQL syntax.
DevTools: [network] explain empty bars preceeding request
Investigated further and have identified that there's no significant difference between our Stalled and Queueing ranges. Both are calculated from the delta's of other timestamps, rather than provided from netstack or renderer.
Currently, if we're waiting for a socket to become available:
- we'll call it stalled if some proxy negotiation happened
- we'll call it queuing if no proxy/ssl work was required.
If the library is static, then at link time the code is linked in with your executable. This makes your executable larger (than if you went the dynamic route).
If the library is dynamic then at link time references to the required methods are built in to your executable. This means that you have to ship your executable and the dynamic library. You also ought to consider whether shared access to the code in the library is safe, preferred load address among other stuff.
If you can live with the static library, go with the static library.
Ok I found out the answer myself. Much like npm cache clean
, Yarn also has its own
yarn cache clean
They aren't comparable.
Ajax (Asynchronous Javascript and XML) is a subset of javascript. Ajax is way for the client-side browser to communicate with the server (for example: retrieve data from a database) without having to perform a page refresh.
jQuery is a javascript library that standardizes the javascript differences cross-browser. jQuery includes some ajax functions.
Addition to the already-accepted answers:
Note that for grep
ing it is simply the addition of the -i
modifier. Ex: grep -rni regular_expression
to search for this 'regular_expression' 'r'ecursively, case 'i'nsensitive, showing line 'n'umbers in the result.
Also, here's a great tool for verifying regular expressions: https://regex101.com/
Ex: See the expression and Explanation in this image.
man grep
) I had the same problem (different web app though) with the error message and it turned out to be the MIME-Type for .js files was text/x-js
instead of application/javascript
due to a duplicate entry in mime.types on the server that was responsible for serving the js files. It seems that this is happening if the header X-Content-Type-Options: nosniff
is set, which makes Firefox (and Chrome) block the content of the js files.
This issue can also raise when you change your system password but not the same updated on your .npmrc file that exist on path C:\Users\user_name, so update your password there too.
please check on it and run npm install first and then npm start.
This can be done without regex
which is more efficient:
var questionText = "1 ding ?"
var index = 0;
var num = "";
do
{
num += questionText[index];
} while (questionText[++index] >= "0" && questionText[index] <= "9");
questionText = questionText.substring(num.length);
And as a bonus, it also stores the number, which may be useful to some people.
Here's a different implementation of Jenny Lang's answer that works for Rails 5.
First create the migration file:
bundle exec be rails g migration DropEpisodes
Then populate the migration file as follows:
class DropEpisodes < ActiveRecord::Migration[5.1]
def change
drop_table :episodes
end
end
Running rails db:migrate
will drop the table. If you run rails db:rollback
, Rails will throw a ActiveRecord::IrreversibleMigration
error.
Replacing server=localhost
with server=.\SQLEXPRESS
might do the job.
@Navaneeth and @Antfish, no need to transform you can do like this also because in above solution only top border is visible so for inside curve you can use bottom border.
.box {_x000D_
width: 500px;_x000D_
height: 100px;_x000D_
border: solid 5px #000;_x000D_
border-color: transparent transparent #000 transparent;_x000D_
border-radius: 0 0 240px 50%/60px;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
JavaScript is case-sensitive. The b
in getElementbyId
should be capitalized.
var content = document.getElementById("edit").innerHTML;
When I try these solutions.
I solved with:
create a new virtual device( select Google APIs(Google Inc)-API Level 15 replace android 4.0.3-APILevel 15 )
then run again. It solved.
I think it's just because the device have no google apis~
IDE:android-studio OS:ubuntu 12.04
josh3736's answer is a good one, but to provide a counterpoint 3 years later:
I recommend using rem
units for fonts, if only because it makes it easier for you, the developer, to change sizes. It's true that users very rarely change the default font size in their browsers, and that modern browser zoom will scale up px
units. But what if your boss comes to you and says "don't enlarge the images or icons, but make all the fonts bigger". It's much easier to just change the root font size and let all the other fonts scale relative to that, then to change px
sizes in dozens or hundreds of css rules.
I think it still makes sense to use px
units for some images, or for certain layout elements that should always be the same size regardless of the scale of the design.
Caniuse.com may have said that only 75% of browsers when josh3736 posted his answer in 2012, but as of March 27 they claim 93.78% support. Only IE8 doesn't support it among the browsers they track.
also very comprehensive...
try{
InputStream fis=new FileInputStream(targetsFile);
BufferedReader br=new BufferedReader(new InputStreamReader(fis));
for (String line = br.readLine(); line != null; line = br.readLine()) {
System.out.println(line);
}
br.close();
}
catch(Exception e){
System.err.println("Error: Target File Cannot Be Read");
}
You need to precede the lines starting with gcc
and rm
with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line).
The result should look like this:
PROG = semsearch
all: $(PROG)
%: %.c
gcc -o $@ $< -lpthread
clean:
rm $(PROG)
Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:
PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread
clean: ; rm $(PROG)
You shouldn't use the keypress
event, but the keyup
or keydown
event because the keypress
event is intended for real (printable) characters. keydown
is handled at a lower level so it will capture all nonprinting keys like delete and enter.
Create and similar object for comparison works too ex:
from datetime import datetime, date
now = datetime.now()
today = date.today()
# compare now with today
two_month_earlier = date(now.year, now.month - 2, now.day)
if two_month_earlier > today:
print(True)
two_month_earlier = datetime(now.year, now.month - 2, now.day)
if two_month_earlier > now:
print("this will work with datetime too")
I was getting the same error with a service access. It was working in browser, but wasnt working when I try to access it in my asp.net/c# application. I changed application pool from appPoolIdentity to NetworkService, and it start working. Seems like a permission issue to me.
If your text will be consumed by non-browsers then it's safer to type the character with the keyboard-combo option shift right bracket
because ’
will not be transformed into an apostrophe by a regular XML or JSON parser. (e.g. if you are serving this content to native Android/iOS apps).
To create a "drop down menu" you can use OptionMenu
in tkinter
Example of a basic OptionMenu
:
from Tkinter import *
master = Tk()
variable = StringVar(master)
variable.set("one") # default value
w = OptionMenu(master, variable, "one", "two", "three")
w.pack()
mainloop()
More information (including the script above) can be found here.
Creating an OptionMenu
of the months from a list would be as simple as:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
mainloop()
In order to retrieve the value the user has selected you can simply use a .get()
on the variable that we assigned to the widget, in the below case this is variable
:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
def ok():
print ("value is:" + variable.get())
button = Button(master, text="OK", command=ok)
button.pack()
mainloop()
I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.
How about this;
myImageView.image=UIImage(named: "image_1")
where image_1 is within the assets folder as image_1.png.
This worked for me since i'm using a switch case to display an image slide.
First, generate an Interface
Assuming you are using TypeScript & Angular CLI, you can generate one by using the following command
ng g interface car
After that set the data types of its properties
// car.interface.ts
export interface car {
id: number;
eco: boolean;
wheels: number;
name: string;
}
You can now import your interface in the class that you want.
import {car} from "app/interfaces/car.interface";
And update the collection/array of car objects by pushing items in the array.
this.car.push({
id: 12345,
eco: true,
wheels: 4,
name: 'Tesla Model S',
});
More on interfaces:
An interface is a TypeScript artifact, it is not part of ECMAScript. An interface is a way to define a contract on a function with respect to the arguments and their type. Along with functions, an interface can also be used with a Class as well to define custom types. An interface is an abstract type, it does not contain any code as a class does. It only defines the 'signature' or shape of an API. During transpilation, an interface will not generate any code, it is only used by Typescript for type checking during development. - https://angular-2-training-book.rangle.io/handout/features/interfaces.html
You would need to create a generic class named MyProp. Then, you will need to add implicit or explicit cast operators so you can get and set the value as if it were the type specified in the generic type parameter. These cast operators can do the extra work that you need.
I faced the same problem once. THe reason for this is that even though the server is available, the config files are missing. You can see the server at Windows -> Show view -> Servers. Their configuration files can be seen at Project Explorer -> Servers. For some reason this second mentioned config files were missing.
I simply deleted the existing server and created a new one with this the config files were also created and the problem was solved!
Similar solution is given at here by Emertana EM java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory
If you put position:relative;
on the outer element, the inner element will place itself according to this one. Then a width:auto;
on the inner element will be the same as the width of the outer.
Found a solution not involving Flex, because Flex doesn't work in older Browsers. Example:
.container {
display:block;
position:relative;
height:150px;
width:1024px;
margin:0 auto;
padding:0px;
border:0px;
background:#ececec;
margin-bottom:10px;
text-align:justify;
box-sizing:border-box;
white-space:nowrap;
font-size:0pt;
letter-spacing:-1em;
}
.cols {
display:inline-block;
position:relative;
width:32%;
height:100%;
margin:0 auto;
margin-right:2%;
border:0px;
background:lightgreen;
box-sizing:border-box;
padding:10px;
font-size:10pt;
letter-spacing:normal;
}
.cols:last-child {
margin-right:0;
}
The trick is pretty simple... The request cycle is still pretty much alive. You can just add a new variable that will create a temporary, calling
app.get('some/url/endpoint', middleware1, middleware2);
Since you can handle your request in the first middleware
(req, res, next) => {
var yourvalue = anyvalue
}
In middleware 1 you handle your logic and store your value like below:
req.anyvariable = yourvalue
In middleware 2 you can catch this value from middleware 1 doing the following:
(req, res, next) => {
var storedvalue = req.yourvalue
}
If it's a .mdf database and the connection string was saved when it was created, you should be able to access it via:
Dim cn As SqlConnection = New SqlConnection(My.Settings.DatabaseNameConnectionString)
Hope that helps someone.
I have resolve the problem as below 1. Get the tag from your branch 2. Write below command
Example: git branch <Hotfix branch> <TAG>
git branch hotfix_4.4.3 v4.4.3
git checkout hotfix_4.4.3
or you can do with other command
git checkout -b <Hotfix branch> <TAG>
-b stands for creating new branch to local
once you ready with your hotfix branch, It's time to move that branch to github, you can do so by writing below command
git push --set-upstream origin hotfix_4.4.3
That will work just fine. You can export an entire calendar with File
> Export…
, or individual events by dragging them to the Finder.
iCalendar (.ics
) files are human-readable, so you can always pop it open in a text editor to make sure no private events made it in there. They consist of nested sections with start with BEGIN:
and end with END:
. You'll mostly find VEVENT
sections (each of which represents an event) and VTIMEZONE
sections, each of which represents a time zone that's referenced from one or more events.
My one line solution:
hash.each { |key, array| puts "#{key}-----", array }
I think it is pretty easy to read.
If you want to change Title of activity when you change activity by clicking on the Button. Declare the necessary variables in MainActivity:
private static final String TITLE_SIGN = "title_sign";
ImageButton mAriesButton;
Add onClickListener in onCreate() and make new intent for another activity:
mTitleButton = (ImageButton) findViewById(R.id.title_button);
mTitleButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,
SignActivity.class);
String title_act = getText(R.string.simple_text).toString();
intent.putExtra("title_act", title_act);
startActivity(intent);
finish();
}
});
SecondActivity code in onCreate():
String txtTitle = getIntent().getStringExtra("title_act");
this.setTitle(txtTitle);
Using a Windows 10 guest, after I performed steps 1 through 3 from @xinampc's answer, I had to open a new File Explorer and navigated to This PC > CD Drive (D:) VirtualBox Guest Additions to run VBoxWindowsAdditions. After I ran that and went through the command prompts, Windows rebooted and I was able to see VBOXSVR under Network.
import numpy as np
def get_mode(xs):
values, counts = np.unique(xs, return_counts=True)
max_count_index = np.argmax(counts) #return the index with max value counts
return values[max_count_index]
print(get_mode([1,7,2,5,3,3,8,3,2]))
The accepted answer has some holes in it. The beauty of the SparseArray is that it allows gaps in the indeces. So, we could have two maps like so, in a SparseArray...
(0,true)
(250,true)
Notice the size here would be 2. If we iterate over size, we will only get values for the values mapped to index 0 and index 1. So the mapping with a key of 250 is not accessed.
for(int i = 0; i < sparseArray.size(); i++) {
int key = sparseArray.keyAt(i);
// get the object by the key.
Object obj = sparseArray.get(key);
}
The best way to do this is to iterate over the size of your data set, then check those indeces with a get() on the array. Here is an example with an adapter where I am allowing batch delete of items.
for (int index = 0; index < mAdapter.getItemCount(); index++) {
if (toDelete.get(index) == true) {
long idOfItemToDelete = (allItems.get(index).getId());
mDbManager.markItemForDeletion(idOfItemToDelete);
}
}
I think ideally the SparseArray family would have a getKeys() method, but alas it does not.
DataTable.Select()
doesnt give the Rows in the order they were present in the datatable.
If order is important I feel iterating over the datarow collection and forming a List is the right way to go or you could also use overload of DataTable.Select(string filterexpression, string sort)
.
But this overload may not handle all the ordering (like order by case ...) that SQL provides.
I find it quite overkill enforce the validity of the href attribute with such a complex and cryptic pattern while a simple expression such as
<a\s+(?:[^>]*?\s+)?href="([^"]*)"
would suffice to capture all URLs. If you want to make sure they contain at least a query string, you could just use
<a\s+(?:[^>]*?\s+)?href="([^"]+\?[^"]+)"
st = @"((www\.|https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+ \w\d:#@%/;$()~_?\+-=\\\.&]*)";
st = @"<a href[^>]*>(.*?)</a>";
st = @"((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)";
st = @"((?:(?:https?|ftp|gopher|telnet|file|notes|ms-help):(?://|\\\\)(?:www\.)?|www\.)[\w\d:#@%/;$()~_?\+,\-=\\.&]+)";
st = @"(?:(?:https?|ftp|gopher|telnet|file|notes|ms-help):(?://|\\\\)(?:www\.)?|www\.)";
st = @"(((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+)|(www\.)[\w\d:#@%/;$()~_?\+-=\\\.&]*)";
st = @"href=[""'](?<url>(http|https)://[^/]*?\.(com|org|net|gov))(/.*)?[""']";
st = @"(<a.*?>.*?</a>)";
st = @"(?:hrefs*=)(?:[s""']*)(?!#|mailto|location.|javascript|.*css|.*this.)(?.*?)(?:[s>""'])";
st = @"http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?";
st = @"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?";
st = @"(http|https)://([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?";
st = @"((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)";
st = @"http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?";
st = @"http(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$";
st = @"(?<Protocol>\w+):\/\/(?<Domain>[\w.]+\/?)\S*";
my choice is
@"(?<Protocol>\w+):\/\/(?<Domain>[\w.]+\/?)\S*"
Second Use this:
st = "(.*)?(.*)=(.*)";
As I mentioned in your other question:
The problem to do with that fact, that you invented your own non-standard attributes (which you shouldn't have done in the first place), and now new standardized attributes (or attributes in the process of being standardized) are colliding with them.
The proper solution is to completely remove your invented attributes and replace them with
something sensible, for example classes (class="Montantetextfield fieldname-Montante required allow-decimal-values"
), or store them in JavaScript:
var validationData = {
"Montante": {fieldname: "Montante", required: true, allowDecimalValues: true}
}
If the proper solution isn't viable, you'll have to rename them. In that case you should use the prefix data-
... because that is reserved by HTML5 for such purposes, and it's less likely to collide with something - but it still could, so you should seriously consider the first solution - even it is more work to change.
None of the above worked for me. I spent too much time clearing other errors that came up. I found this to be the easiest and the best way.
This works for getting JavaFx on Jdk 11, 12 & on OpenJdk12 too!
module thisIsTheNameOfYourProject {
requires javafx.fxml;
requires javafx.controls;
requires javafx.graphics;
opens sample;
}
The entire thing took me only 5mins !!!
If you don't want to save method into jQuery.fn you can use
[].reverse.call($('li'));
If you would like to auto format on save just with Javascript source, add this one into Users Setting
(press Cmd, or Ctrl,):
"[javascript]": { "editor.formatOnSave": true }
See the MSDN reference table for maximum numbers/sizes.
Bytes per varchar(max), varbinary(max), xml, text, or image column: 2^31-1
There's a two-byte overhead for the column, so the actual data is 2^31-3 max bytes in length. Assuming you're using a single-byte character encoding, that's 2^31-3 characters total. (If you're using a character encoding that uses more than one byte per character, divide by the total number of bytes per character. If you're using a variable-length character encoding, all bets are off.)
just FYI in GoDaddy it's this:
AddHandler x-httpd-php5-3 .php
I had a similar issue that was resolved with the following:
If the user is a domain user use Domain username and password
Aggregated List of Libraries
Since in your question you said it's a PHP script, maybe the best solution could be to simply add in your script:
ignore_user_abort(TRUE);
In this way even if wget
terminates, the PHP script goes on being processed at least until it does not exceeds max_execution_time
limit (ini directive: 30 seconds by default).
As per wget
anyay you should not change its timeout, according to the UNIX manual the default wget timeout is 900 seconds (15 minutes), whis is much larger that the 5-6 minutes you need.
datetime has fields hour
and minute
. So to get the hours and minutes, you would use t1.hour
and t1.minute
.
However, when you subtract two datetimes, the result is a timedelta, which only has the days
and seconds
fields. So you'll need to divide and multiply as necessary to get the numbers you need.
that's all you need
childView.frame = parentView.bounds
If you're using ASP.NET 2.0 or greater, you can turn it on in the Web.config file. In the <system.web> section, add the following line:
<httpCookies httpOnlyCookies="true"/>
You can do this in IE:
<script language="VBScript">
Sub myAlert(title, content)
MsgBox content, 0, title
End Sub
</script>
<script type="text/javascript">
myAlert("My custom title", "Some content");
</script>
(Although, I really wish you couldn't.)
Use the String.replaceAll()
method in Java.
replaceAll should be good enough for your problem.
As mentioned, one way is to use
new Integer(my_int_value)
But you should not call the constructor for wrapper classes directly
So, modify the code accordingly:
mBitmapCache.put(Integer.valueOf(R.drawable.bg1),object);
You could do this with MapReduce:
mr = db.runCommand({
"mapreduce" : "my_collection",
"map" : function() {
for (var key in this) { emit(key, null); }
},
"reduce" : function(key, stuff) { return null; },
"out": "my_collection" + "_keys"
})
Then run distinct on the resulting collection so as to find all the keys:
db[mr.result].distinct("_id")
["foo", "bar", "baz", "_id", ...]
I don't think that IDE is relevant here. After all you're running a Maven and Maven doesn't have a source that will allow to compile the diamond operators. So, I think you should configure maven-compiler-plugin itself.
You can read about this here. But in general try to add the following properties:
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
and see whether it compiles now in Maven only.
Rda is just a short name for RData. You can just save(), load(), attach(), etc. just like you do with RData.
Rds stores a single R object. Yet, beyond that simple explanation, there are several differences from a "standard" storage. Probably this R-manual Link to readRDS() function clarifies such distinctions sufficiently.
So, answering your questions:
In some browsers:
flex:1;
does not equal flex:1 1 0;
flex:1;
= flex:1 1 0n;
(where n is a length unit).
The key point here is that flex-basis requires a length unit.
In Chrome for example flex:1
and flex:1 1 0
produce different results. In most circumstances it may appear that flex:1 1 0;
is working but let's examine what really happens:
Flex basis is ignored and only flex-grow and flex-shrink are applied.
flex:1 1 0;
= flex:1 1;
= flex:1;
This may at first glance appear ok however if the applied unit of the container is nested; expect the unexpected!
Try this example in CHROME
.Wrap{_x000D_
padding:10px;_x000D_
background: #333;_x000D_
}_x000D_
.Flex110x, .Flex1, .Flex110, .Wrap {_x000D_
display: -webkit-flex;_x000D_
display: flex;_x000D_
-webkit-flex-direction: column;_x000D_
flex-direction: column;_x000D_
}_x000D_
.Flex110 {_x000D_
-webkit-flex: 1 1 0;_x000D_
flex: 1 1 0;_x000D_
}_x000D_
.Flex1 {_x000D_
-webkit-flex: 1;_x000D_
flex: 1;_x000D_
}_x000D_
.Flex110x{_x000D_
-webkit-flex: 1 1 0%;_x000D_
flex: 1 1 0%;_x000D_
}
_x000D_
FLEX 1 1 0_x000D_
<div class="Wrap">_x000D_
<div class="Flex110">_x000D_
<input type="submit" name="test1" value="TEST 1">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
FLEX 1_x000D_
<div class="Wrap">_x000D_
<div class="Flex1">_x000D_
<input type="submit" name="test2" value="TEST 2">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
FLEX 1 1 0%_x000D_
<div class="Wrap">_x000D_
<div class="Flex110x">_x000D_
<input type="submit" name="test3" value="TEST 3">_x000D_
</div>_x000D_
</div>
_x000D_
It should be noted that this fails because some browsers have failed to adhere to the specification.
Browsers that use the full flex specification:
Latest versions of Chrome seem to have finally rectified this issue but other browsers still have not.
Tested and working in Chrome Ver 74.
it's so easy if you want divide your screen two part vertically ( top30% + bottom70%)
<LinearLayout
android:id="@+id/LinearLayoutTop"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="2">
</LinearLayout>
<LinearLayout
android:id="@+id/LinearLayoutBottom"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
</LinearLayout>
The chrome team has proposed a new way of managing cookies asynchronous with the Cookie Storage API (available in Google Chrome starting from version 87): https://wicg.github.io/cookie-store/
Use it already today with a polyfill for the other browsers: https://github.com/mkay581/cookie-store
// load polyfill
import 'cookie-store';
// set a cookie
await cookieStore.set('name', 'value');
// get a cookie
const savedValue = await cookieStore.get('name');
The documentation says:
class (Optional) String
One or more CSS classes to remove from the elements, these are separated by spaces.
Example:
Remove the class 'blue' and 'under' from the matched elements.
$("p:odd").removeClass("blue under");
below is code for displaying a frame at top-centre of existing window.
public class SwingContainerDemo {
private JFrame mainFrame;
private JPanel controlPanel;
private JLabel msglabel;
Frame.setLayout(new FlowLayout());
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
//headerLabel = new JLabel("", JLabel.CENTER);
/* statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
*/ msglabel = new JLabel("Welcome to TutorialsPoint SWING Tutorial.", JLabel.CENTER);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
//mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
// mainFrame.add(statusLabel);
mainFrame.setUndecorated(true);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
mainFrame.setVisible(true);
centreWindow(mainFrame);
}
public static void centreWindow(Window frame) {
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
frame.setLocation(x, 0);
}
public void showJFrameDemo(){
/* headerLabel.setText("Container in action: JFrame"); */
final JFrame frame = new JFrame();
frame.setSize(300, 300);
frame.setLayout(new FlowLayout());
frame.add(msglabel);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
frame.dispose();
}
});
JButton okButton = new JButton("Capture");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// statusLabel.setText("A Frame shown to the user.");
// frame.setVisible(true);
mainFrame.setState(Frame.ICONIFIED);
Robot robot = null;
try {
robot = new Robot();
} catch (AWTException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
final Dimension screenSize = Toolkit.getDefaultToolkit().
getScreenSize();
final BufferedImage screen = robot.createScreenCapture(
new Rectangle(screenSize));
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ScreenCaptureRectangle(screen);
}
});
mainFrame.setState(Frame.NORMAL);
}
});
controlPanel.add(okButton);
mainFrame.setVisible(true);
} public static void main(String[] args) throws Exception {
new SwingContainerDemo().showJFrameDemo();
}
System.setProperty("gate.home", "/some/directory");
For more information, see:
System.setProperty( String key , String value )
.You can use org.json.JSONObject and org.json.JSONTokener. you don't need any external libraries since these classes come with Android SDK
In my Jenkins instance (version 1.548) the configuration file is at:
/var/lib/jenkins/jobs/-the-project-name-/config.xml
Owned by jenkins user and jenkins group with 644 permissions. Copying the file to and from here should work. I haven't tried changing it directly but have backed-up the config from this spot in case the project needs to be setup again.
You're applying transitions only to the :hover
pseudo-class, and not to the element itself.
.item {
height:200px;
width:200px;
background:red;
-webkit-transition: opacity 1s ease-in-out;
-moz-transition: opacity 1s ease-in-out;
-ms-transition: opacity 1s ease-in-out;
-o-transition: opacity 1s ease-in-out;
transition: opacity 1s ease-in-out;
}
.item:hover {
zoom: 1;
filter: alpha(opacity=50);
opacity: 0.5;
}
Demo: http://jsfiddle.net/7uR8z/6/
If you don't want the transition to affect the mouse-over
event, but only mouse-out
, you can turn transitions off for the :hover
state :
.item:hover {
-webkit-transition: none;
-moz-transition: none;
-ms-transition: none;
-o-transition: none;
transition: none;
zoom: 1;
filter: alpha(opacity=50);
opacity: 0.5;
}
Here is a dplyr
based option:
newV = df %>% slice(1) %>% unlist(use.names = FALSE)
# or slightly different:
newV = df %>% slice(1) %>% unlist() %>% unname()
Go to the package.json
file, check the "@angular/core"
version. It is an actual project version.
<meta http-equiv="refresh" content="5;URL='form2.html'">
I agree with Brainstorm's approach: assuming that you're passing a machine-friendly binary representation, use the encoding/binary
library. The OP suggests that binary.Write()
might have some overhead. Looking at the source for the implementation of Write()
, I see that it does some runtime decisions for maximum flexibility.
func Write(w io.Writer, order ByteOrder, data interface{}) error {
// Fast path for basic types.
var b [8]byte
var bs []byte
switch v := data.(type) {
case *int8:
bs = b[:1]
b[0] = byte(*v)
case int8:
bs = b[:1]
b[0] = byte(v)
case *uint8:
bs = b[:1]
b[0] = *v
...
Right? Write() takes in a very generic data
third argument, and that's imposing some overhead as the Go runtime then is forced into encoding type information. Since Write()
is doing some runtime decisions here that you simply don't need in your situation, maybe you can just directly call the encoding functions and see if it performs better.
Something like this:
package main
import (
"encoding/binary"
"fmt"
)
func main() {
bs := make([]byte, 4)
binary.LittleEndian.PutUint32(bs, 31415926)
fmt.Println(bs)
}
Let us know how this performs.
Otherwise, if you're just trying to get an ASCII representation of the integer, you can get the string representation (probably with strconv.Itoa
) and cast that string to the []byte
type.
package main
import (
"fmt"
"strconv"
)
func main() {
bs := []byte(strconv.Itoa(31415926))
fmt.Println(bs)
}
In Python 3, TemporaryDirectory in the tempfile module can be used.
This is straight from the examples:
import tempfile
with tempfile.TemporaryDirectory() as tmpdirname:
print('created temporary directory', tmpdirname)
# directory and contents have been removed
If you would like to keep the directory a bit longer, you could do something like this:
import tempfile
temp_dir = tempfile.TemporaryDirectory()
print(temp_dir.name)
# use temp_dir, and when done:
temp_dir.cleanup()
The documentation also says that "On completion of the context or destruction of the temporary directory object the newly created temporary directory and all its contents are removed from the filesystem." So at the end of the program, for example, Python will clean up the directory if it wasn't explicitly removed. Python's unittest
may complain of ResourceWarning: Implicitly cleaning up <TemporaryDirectory...
if you rely on this, though.
The accepted answer doesn't cut it because if a user de-selects a row the list is not updated accordingly.
Here is what I suggest instead:
Private Sub CommandButton2_Click()
Dim lItem As Long
For lItem = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(lItem) = True Then
MsgBox(ListBox1.List(lItem))
End If
Next
End Sub
Courtesy of http://www.ozgrid.com/VBA/multi-select-listbox.htm
In oracle an empty varchar2 and null are treated the same, and your observations show that.
when you write:
select * from table where a = '';
its the same as writing
select * from table where a = null;
and not a is null
which will never equate to true, so never return a row. same on the insert, a NOT NULL means you cant insert a null or an empty string (which is treated as a null)
my solution:
; (function ($) {
$.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = $.fn[ name ];
$.fn[ name ] = function( speed, easing, callback ) {
if(speed == null || typeof speed === "boolean"){
var ret=cssFn.apply( this, arguments )
$.fn.triggerVisibleEvent.apply(this,arguments)
return ret
}else{
var that=this
var new_callback=function(){
callback.call(this)
$.fn.triggerVisibleEvent.apply(that,arguments)
}
var ret=this.animate( genFx( name, true ), speed, easing, new_callback )
return ret
}
};
});
$.fn.triggerVisibleEvent=function(){
this.each(function(){
if($(this).is(':visible')){
$(this).trigger('visible')
$(this).find('[data-trigger-visible-event]').triggerVisibleEvent()
}
})
}
})(jQuery);
for example:
if(!$info_center.is(':visible')){
$info_center.attr('data-trigger-visible-event','true').one('visible',processMoreLessButton)
}else{
processMoreLessButton()
}
function processMoreLessButton(){
//some logic
}
You need to include the path of the libraries inside /etc/ld.so.conf, and rerun ldconfig to upate the list
Other possibility is to include in the env variable LD_LIBRARY_PATH the path to your library, and rerun the executable.
check the symbolic links if they point to a valid library ...
You can add the path directly in /etc/ld.so.conf, without include...
run ldconfig -p
to see whether your library is well included in the cache.
You need to handle two scenarios:
If you just need a base class you can use, here's a Swift 3 version:
import UIKit
final class SwipeNavigationController: UINavigationController {
// MARK: - Lifecycle
override init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
delegate = self
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
delegate = self
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
// This needs to be in here, not in init
interactivePopGestureRecognizer?.delegate = self
}
deinit {
delegate = nil
interactivePopGestureRecognizer?.delegate = nil
}
// MARK: - Overrides
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
duringPushAnimation = true
super.pushViewController(viewController, animated: animated)
}
// MARK: - Private Properties
fileprivate var duringPushAnimation = false
}
// MARK: - UINavigationControllerDelegate
extension SwipeNavigationController: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
guard let swipeNavigationController = navigationController as? SwipeNavigationController else { return }
swipeNavigationController.duringPushAnimation = false
}
}
// MARK: - UIGestureRecognizerDelegate
extension SwipeNavigationController: UIGestureRecognizerDelegate {
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard gestureRecognizer == interactivePopGestureRecognizer else {
return true // default value
}
// Disable pop gesture in two situations:
// 1) when the pop animation is in progress
// 2) when user swipes quickly a couple of times and animations don't have time to be performed
return viewControllers.count > 1 && duringPushAnimation == false
}
}
If you end up needing to act as a UINavigationControllerDelegate
in another class, you can write a delegate forwarder similar to this answer.
Adapted from source in Objective-C: https://github.com/fastred/AHKNavigationController
OK so I think i know the issue you're having.
Basically, because Composer can't see the migration files you are creating, you are having to run the dump-autoload command which won't download anything new, but looks for all of the classes it needs to include again. It just regenerates the list of all classes that need to be included in the project (autoload_classmap.php), and this is why your migration is working after you run that command.
How to fix it (possibly) You need to add some extra information to your composer.json file.
"autoload": {
"classmap": [
"PATH TO YOUR MIGRATIONS FOLDER"
],
}
You need to add the path to your migrations folder to the classmap array. Then run the following three commands...
php artisan clear-compiled
composer dump-autoload
php artisan optimize
This will clear the current compiled files, update the classes it needs and then write them back out so you don't have to do it again.
Ideally, you execute composer dump-autoload -o
, for a faster load of your webpages. The only reason it is not default, is because it takes a bit longer to generate (but is only slightly noticable).
Hope you can manage to get this sorted, as its very annoying indeed :(
Another simple solution with +=
:
$y = 1;
for ($x = $y; $x <= 15; $y++) {
printf("The number of first paragraph is: $y <br>");
printf("The number of second paragraph is: $x+=2 <br>");
}
No need for external plugins. In the Export JAR dialog, make sure you select all the necessary resources you want to export. By default, there should be no problem exporting other resource files as well (pictures, configuration files, etc...), see screenshot below.
This if an Info message that could pop in your LogCat on many situations.
In my case, it happened when I was inflating several views from XML layout files programmatically. The message is harmless by itself, but could be the sign of a later problem that would use all the RAM your App is allowed to use and cause the mega-evil Force Close to happen. I have grown to be the kind of Developer that likes to see his Log WARN/INFO/ERROR Free. ;)
So, this is my own experience:
I got the message:
10-09 01:25:08.373: I/Choreographer(11134): Skipped XXX frames! The application may be doing too much work on its main thread.
... when I was creating my own custom "super-complex multi-section list" by inflating a view from XML and populating its fields (images, text, etc...) with the data coming from the response of a REST/JSON web service (without paging capabilities) this views would act as rows, sub-section headers and section headers by adding all of them in the correct order to a LinearLayout (with vertical orientation inside a ScrollView). All of that to simulate a listView with clickable elements... but well, that's for another question.
As a responsible Developer you want to make the App really efficient with the system resources, so the best practice for lists (when your lists are not so complex) is to use a ListActivity or ListFragment with a Loader and fill the ListView with an Adapter, this is supposedly more efficient, in fact it is and you should do it all the time, again... if your list is not so complex.
Solution: I implemented paging on my REST/JSON web service to prevent "big response sizes" and I wrapped the code that added the "rows", "section headers" and "sub-section headers" views on an AsyncTask to keep the Main Thread cool.
So... I hope my experience helps someone else that is cracking their heads open with this Info message.
Happy hacking!
I would say that J2EE experience = in-depth experience with a few J2EE technologies, general knowledge about most J2EE technologies, and general experience with enterprise software in general.
You are dealing with the raw DOM element .. need to wrap it in a jquery object
console.info("cat_id: ",$(value).attr('cat_id'));
If you want to avoid fencepost errors and avoid moving and deleting items in an array, here is a somewhat verbose solution that uses List
:
import java.util.ArrayList;
import java.util.List;
public class RemoveNullValue {
public static void main( String args[] ) {
String[] firstArray = {"test1", "", "test2", "test4", "", null};
List<String> list = new ArrayList<String>();
for(String s : firstArray) {
if(s != null && s.length() > 0) {
list.add(s);
}
}
firstArray = list.toArray(new String[list.size()]);
}
}
Added null
to show the difference between an empty String instance (""
) and null
.
Since this answer is around 4.5 years old, I'm adding a Java 8 example:
import java.util.Arrays;
import java.util.stream.Collectors;
public class RemoveNullValue {
public static void main( String args[] ) {
String[] firstArray = {"test1", "", "test2", "test4", "", null};
firstArray = Arrays.stream(firstArray)
.filter(s -> (s != null && s.length() > 0))
.toArray(String[]::new);
}
}
For Travers an String you can also use charAt()
with the string.
like :
String str = "xyz"; // given String
char st = str.charAt(0); // for example we take 0 index element
System.out.println(st); // print the char at 0 index
charAt()
is method of string handling in java which help to Travers the string for specific character.
M2Eclipse sometimes does that. Select Project > Clean ...
from the Menu and everything will be fine after the rebuild
You should only have 1 UIViewController active at any time. Any subviews you want to manipulate should be exactly that - subVIEWS - i.e. UIView.
I use a simlple technique for managing my view hierarchy and have yet to run into a problem since I started doing things this way. There are 2 key points:
What do I mean by "a screen's worth"? It's a bit vague on purpose, but generally it's a feature or section of your app. If you've got a few screens with the same background image but different overlays/popups etc., that should be 1 view controller and several child views. You should never find yourself working with 2 view controllers. Note you can still instantiate a UIView in one view controller and add it as a subview of another view controller if you want certain areas of the screen to be shown in multiple view controllers.
As for UINavigationController - this is your best friend! Turn off the navigation bar and specify NO for animated, and you have an excellent way of switching screens on demand. You can push and pop view controllers if they're in a hierarchy, or you can prepare an array of view controllers (including an array containing a single VC) and set it to be the view stack using setViewControllers. This gives you total freedom to change VC's, while gaining all the advantages of working within Apple's expected model and getting all events etc. fired properly.
Here's what I do every time when I start an app:
(note starting from window-based is just a personal preference - I like to construct things myself so I know exactly how they are built. It should work fine with view-based template)
All events fire correctly and basically life is good. You can then spend all your time writing the important bits of your app and not messing about trying to manually hack view hierarchies into shape.
I did some benchmarks to compare the execution time of COUNT(*)
vs COUNT(id)
(id is the primary key of the table - indexed).
Number of trials: 10 * 1000 queries
Results:
COUNT(*)
is faster 7%
VIEW GRAPH: benchmarkgraph
My advice is to use: SELECT COUNT(*) FROM table
Simply you can do it easy... You just need to get the context of your activity, here, from your View.
//Create intent getting the context of your View and the class where you want to go
Intent intent = new Intent(view.getContext(), YourClass.class);
//start the activity from the view/context
view.getContext().startActivity(intent); //If you are inside activity, otherwise pass context to this funtion
Remember that you need to modify AndroidManifest.xml and place the activity...
<activity
android:name=".YourClass"
android:label="Label for your activity"></activity>
For whatever reason, @AliUmair reverted the edit to his answer that fixes his code that doesn't run as is, so here is the working version that doesn't have the file access error and properly handles null object property values:
/// <summary>
/// Creates the CSV from a generic list.
/// </summary>;
/// <typeparam name="T"></typeparam>;
/// <param name="list">The list.</param>;
/// <param name="csvNameWithExt">Name of CSV (w/ path) w/ file ext.</param>;
public static void CreateCSVFromGenericList<T>(List<T> list, string csvCompletePath)
{
if (list == null || list.Count == 0) return;
//get type from 0th member
Type t = list[0].GetType();
string newLine = Environment.NewLine;
if (!Directory.Exists(Path.GetDirectoryName(csvCompletePath))) Directory.CreateDirectory(Path.GetDirectoryName(csvCompletePath));
using (var sw = new StreamWriter(csvCompletePath))
{
//make a new instance of the class name we figured out to get its props
object o = Activator.CreateInstance(t);
//gets all properties
PropertyInfo[] props = o.GetType().GetProperties();
//foreach of the properties in class above, write out properties
//this is the header row
sw.Write(string.Join(",", props.Select(d => d.Name).ToArray()) + newLine);
//this acts as datarow
foreach (T item in list)
{
//this acts as datacolumn
var row = string.Join(",", props.Select(d => $"\"{item.GetType().GetProperty(d.Name).GetValue(item, null)?.ToString()}\"")
.ToArray());
sw.Write(row + newLine);
}
}
}
Based on Cat Kerr response. This command is working on solaris
awk '{print NF; exit}' stores.dat
Your regex "sentence(.*)"
is right. To retrieve the contents of the group in parenthesis, you would call:
Pattern p = Pattern.compile( "sentence(.*)" );
Matcher m = p.matcher( "some lame sentence that is awesome" );
if ( m.find() ) {
String s = m.group(1); // " that is awesome"
}
Note the use of m.find()
in this case (attempts to find anywhere on the string) and not m.matches()
(would fail because of the prefix "some lame"; in this case the regex would need to be ".*sentence(.*)"
)
The main image manager in PIL
is PIL
's Image
module.
from PIL import Image
import math
foo = Image.open("path\\to\\image.jpg")
x, y = foo.size
x2, y2 = math.floor(x-50), math.floor(y-20)
foo = foo.resize((x2,y2),Image.ANTIALIAS)
foo.save("path\\to\\save\\image_scaled.jpg",quality=95)
You can add optimize=True
to the arguments of you want to decrease the size even more, but optimize only works for JPEG's and PNG's.
For other image extensions, you could decrease the quality of the new saved image.
You could change the size of the new image by just deleting a bit of code and defining the image size and you can only figure out how to do this if you look at the code carefully.
I defined this size:
x, y = foo.size
x2, y2 = math.floor(x-50), math.floor(y-20)
just to show you what is (almost) normally done with horizontal images. For vertical images you might do:
x, y = foo.size
x2, y2 = math.floor(x-20), math.floor(y-50)
. Remember, you can still delete that bit of code and define a new size.
I had the same question but figured it out finally. What you most likely need to do is run the following two git commands (replacing hash with the git commit revision number):
git checkout <hash>
git push -f HEAD:master
Usually there are 2 types of seed data required.
In my experience I was always coming across the need for these two types of data. So I put together a small gem that extends Rails' seeds and lets you add multiple common seed files under db/seeds/ and any environmental seed data under db/seeds/ENV for example db/seeds/development.
I have found this approach is enough to give my seed data some structure and gives me the power to setup my development or staging environment in a known state just by running:
rake db:setup
Fixtures are fragile and flakey to maintain, as are regular sql dumps.
In my case I have two radio buttons in one form and I wanted to know the status of each button. This below worked for me:
// get radio buttons value_x000D_
console.log( "radio1: " + $('input[id=radio1]:checked', '#toggle-form').val() );_x000D_
console.log( "radio2: " + $('input[id=radio2]:checked', '#toggle-form').val() );_x000D_
_x000D_
_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form id="toggle-form">_x000D_
<div id="radio">_x000D_
<input type="radio" id="radio1" name="radio" checked="checked" /><label for="radio1">Plot single</label>_x000D_
<input type="radio" id="radio2" name="radio"/><label for="radio2">Plot all</label>_x000D_
</div>_x000D_
</form>
_x000D_
Edit you AssemblyInfo.cs and #if !NETCOREAPP3_0 ... #endif
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
#if !NETCOREAPP3_0
[assembly: AssemblyTitle(".Net Core Testing")]
[assembly: AssemblyDescription(".Net Core")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct(".Net Core")]
[assembly: AssemblyCopyright("Copyright ©")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("000b119c-2445-4977-8604-d7a736003d34")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
#endif
Use brackets. So to look for 75%
WHERE MyCol LIKE '%75[%]%'
This is simpler than ESCAPE and common to most RDBMSes.
It's the same origin policy, you have to use a JSON-P interface or a proxy running on the same host.
Although you were offered a good solution by others I think it is helpful to point out what is really happening. As per the Anaconda 4.4 changelog, https://docs.anaconda.com/anaconda/reference/release-notes/#what-s-new-in-anaconda-4-4:
On Windows, the PATH environment variable is no longer changed by default, as this can cause trouble with other software. The recommended approach is to instead use Anaconda Navigator or the Anaconda Command Prompt (located in the Start Menu under “Anaconda”) when you wish to use Anaconda software.
(Note: recent Win 10 does not assume you have privileges to install or update. If the command fails, right-click on the Anaconda Command Prompt, choose "More", chose "Run as administrator")
This is a change from previous installations. It is suggested to use Navigator or the Anaconda Prompt although you can always add it to your PATH as well. During the install the box to add Anaconda to the PATH is now unchecked but you can select it.
BufferedImage is a subclass of Image. You don't need to do any conversion.
You can also use starts_with
and dplyr
's select()
like so:
df <- df %>% dplyr:: select(starts_with("ABC"))
You need to enable "extension=php_openssl.dll" in both files (php and apache). my pc files path are these :
I've just used Deferred in real code. In project jQuery Terminal I have function exec that call commands defined by user (like he was entering it and pressing enter), I've added Deferreds to the API and call exec with arrays. like this:
terminal.exec('command').then(function() {
terminal.echo('command finished');
});
or
terminal.exec(['command 1', 'command 2', 'command 3']).then(function() {
terminal.echo('all commands finished');
});
the commands can run async code, and exec need to call user code in order. My first api use pair of pause/resume calls and in new API I call those automatic when user return promise. So user code can just use
return $.get('/some/url');
or
var d = new $.Deferred();
setTimeout(function() {
d.resolve("Hello Deferred"); // resolve value will be echoed
}, 500);
return d.promise();
I use code like this:
exec: function(command, silent, deferred) {
var d;
if ($.isArray(command)) {
return $.when.apply($, $.map(command, function(command) {
return self.exec(command, silent);
}));
}
// both commands executed here (resume will call Term::exec)
if (paused) {
// delay command multiple time
d = deferred || new $.Deferred();
dalyed_commands.push([command, silent, d]);
return d.promise();
} else {
// commands may return promise from user code
// it will resolve exec promise when user promise
// is resolved
var ret = commands(command, silent, true, deferred);
if (!ret) {
if (deferred) {
deferred.resolve(self);
return deferred.promise();
} else {
d = new $.Deferred();
ret = d.promise();
ret.resolve();
}
}
return ret;
}
},
dalyed_commands is used in resume function that call exec again with all dalyed_commands.
and part of the commands function (I've stripped not related parts)
function commands(command, silent, exec, deferred) {
var position = lines.length-1;
// Call user interpreter function
var result = interpreter.interpreter(command, self);
// user code can return a promise
if (result != undefined) {
// new API - auto pause/resume when using promises
self.pause();
return $.when(result).then(function(result) {
// don't echo result if user echo something
if (result && position === lines.length-1) {
display_object(result);
}
// resolve promise from exec. This will fire
// code if used terminal::exec('command').then
if (deferred) {
deferred.resolve();
}
self.resume();
});
}
// this is old API
// if command call pause - wait until resume
if (paused) {
self.bind('resume.command', function() {
// exec with resume/pause in user code
if (deferred) {
deferred.resolve();
}
self.unbind('resume.command');
});
} else {
// this should not happen
if (deferred) {
deferred.resolve();
}
}
}
I would use DATEFROMPARTS function. It is quite easy and you don't need casting. As an example this query :
Select DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), DAY(GETDATE())) as myNewDate
will return
2021-01-21
The good part you can also create you own date, for example you want first day of a month as a date, than you can just use like below:
Select DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1) as myNewDate
The result will be:
2021-01-01
You can also use Apache's ExceptionUtils.
Example:
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;
public class Test {
static Logger logger = Logger.getLogger(Test.class);
public static void main(String[] args) {
try{
String[] avengers = null;
System.out.println("Size: "+avengers.length);
} catch (NullPointerException e){
logger.info(ExceptionUtils.getFullStackTrace(e));
}
}
}
Console output:
java.lang.NullPointerException
at com.aimlessfist.avengers.ironman.Test.main(Test.java:11)
Update Panel always replaces your Jquery with its inbuilt Scriptmanager's scripts after every load. Its better if you use pageRequestManager's instance methods like this...
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(onEndRequest)
function onEndRequest(sender, args) {
// your jquery code here
});
it will work fine ...
A quick example:
List<List<string>> myList = new List<List<string>>();
myList.Add(new List<string> { "a", "b" });
myList.Add(new List<string> { "c", "d", "e" });
myList.Add(new List<string> { "qwerty", "asdf", "zxcv" });
myList.Add(new List<string> { "a", "b" });
// To iterate over it.
foreach (List<string> subList in myList)
{
foreach (string item in subList)
{
Console.WriteLine(item);
}
}
Is that what you were looking for? Or are you trying to create a new class
that extends List<T>
that has a member that is a `List'?
To change a cell value using a column name, one can use
iris$Sepal.Length[3]=999
Resorting to using .htaccess
to rewrite the URLs for static HTML is generally not only unnecessary, but also bad for you website's performance. Enabling .htaccess
is also an unnecessary security vulnerability - turning it off eliminates a significant number of potential issues. The same rules for each .htaccess
file can instead go in a <Directory>
section for that directory, and it will be more performant if you then set AllowOverride None
because it won't need to check each directory for a .htaccess
file, and more secure because an attacker can't change the vhost config without root access.
If you don't need .htaccess
in a VPS environment, you can disable it entirely and get better performance from your web server.
All you need to do is move your individual files from a structure like this:
index.html
about.html
products.html
terms.html
To a structure like this:
index.html
about/index.html
products/index.html
terms/index.html
Your web server will then render the appropriate pages - if you load /about/
, it will treat that as /about/index.html
.
This won't rewrite the URL if anyone visits the old one, though, so it would need redirects to be in place if it was retroactively applied to an existing site.
without what? do you mean
>>> print 'a' * 20
aaaaaaaaaaaaaaaaaaaa
?
If you have any NamedQueries in your entity classes, then check the stack trace for compilation errors. A malformed query which cannot be compiled can cause failure to load the persistence context.
Methods Where authenticity_token
is required
authenticity_token
is required in case of idempotent methods like post, put and delete, Because Idempotent methods are affecting to data.
Why It is Required
It is required to prevent from evil actions. authenticity_token is stored in session, whenever a form is created on web pages for creating or updating to resources then a authenticity token is stored in hidden field and it sent with form on server. Before executing action user sent authenticity_token is cross checked with
authenticity_token
stored in session. Ifauthenticity_token
is same then process is continue otherwise it does not perform actions.
UITableViewCell
has an attribute multipleSelectionBackgroundView
.
https://developer.apple.com/documentation/uikit/uitableviewcell/1623226-selectedbackgroundview
Just create an UIView
define the .backgroundColor
of your choice and assign it to your cells .multipleSelectionBackgroundView
attribute.
You can do this by subsetting the data you pass into your merge:
merge(x = DF1, y = DF2[ , c("Client", "LO")], by = "Client", all.x=TRUE)
Or you can simply delete the column after your current merge :)
var p=document.getElementById('childId').parentNode;
var c=document.getElementById('childId');
p.removeChild(c);
alert('Deleted');
p is parent node and c is child node
parentNode is a JavaScript variable which contains parent reference
Easy to understand
This might be another solution for those with the latest Windows 10 creator version:
Stack Overflow post Fatal error LNK1104: cannot open file 'gdi32.lib'
I had this error in code that looked like this:
int A = 1;
int B = A;
The fix is to change it to this
int A = 1;
#define B A
The compiler assigns a location in memory to a variable. The second is trying a assign a second variable to the same location as the first - which makes no sense. Using the macro preprocessor solves the problem.
if(/chrom(e|ium)/.test(navigator.userAgent.toLowerCase())){
alert('I am chrome');
}
I have adapted a bit the solution by @steco, switching the dependency from d3
to jquery
and adding the height
of the text element as parameter
function wrap(text, width, height) {
text.each(function(idx,elem) {
var text = $(elem);
text.attr("dy",height);
var words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.1, // ems
y = text.attr("y"),
dy = parseFloat( text.attr("dy") ),
tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (elem.getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
}
}
});
}
x+=y
is shorthand in many languages for set x to x + y
. The sum will be, as hinted by its name, the sum of the numbers in data
.
You can parse all arguments and check if they exist.
file: parse-cli-arguments.js:
module.exports = function(requiredArguments){
var arguments = {};
for (var index = 0; index < process.argv.length; index++) {
var re = new RegExp('--([A-Za-z0-9_]+)=([A/-Za-z0-9_]+)'),
matches = re.exec(process.argv[index]);
if(matches !== null) {
arguments[matches[1]] = matches[2];
}
}
for (var index = 0; index < requiredArguments.length; index++) {
if (arguments[requiredArguments[index]] === undefined) {
throw(requiredArguments[index] + ' not defined. Please add the argument with --' + requiredArguments[index]);
}
}
return arguments;
}
Than just do:
var arguments = require('./parse-cli-arguments')(['foo', 'bar', 'xpto']);
Simplest way to get length of string without bothering about std namespace is as follows
string with/without spaces
#include <iostream>
#include <string>
using namespace std;
int main(){
string str;
getline(cin,str);
cout<<"Length of given string is"<<str.length();
return 0;
}
string without spaces
#include <iostream>
#include <string>
using namespace std;
int main(){
string str;
cin>>str;
cout<<"Length of given string is"<<str.length();
return 0;
}
You will save yourself a heap of trouble (long term) if you store a ZIP Code as a character string, which it is, rather than a number, which it is not.
Have you read this? How do I create an AUTOINCREMENT field.
INSERT INTO people
VALUES (NULL, "John", "Smith");
First and foremost, you should consider calling MimeTypeMap#getMimeTypeFromExtension()
, like this:
// url = file path or whatever suitable URL you want.
public static String getMimeType(String url) {
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) {
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
return type;
}
I ran into a similar problem and stumbled on this question. I got an SMTP Authentication Error but my user name / pass was correct. Here is what fixed it. I read this:
https://support.google.com/accounts/answer/6010255
In a nutshell, google is not allowing you to log in via smtplib because it has flagged this sort of login as "less secure", so what you have to do is go to this link while you're logged in to your google account, and allow the access:
https://www.google.com/settings/security/lesssecureapps
Once that is set (see my screenshot below), it should work.
Login now works:
smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
smtpserver.login('[email protected]', 'me_pass')
Response after change:
(235, '2.7.0 Accepted')
Response prior:
smtplib.SMTPAuthenticationError: (535, '5.7.8 Username and Password not accepted. Learn more at\n5.7.8 http://support.google.com/mail/bin/answer.py?answer=14257 g66sm2224117qgf.37 - gsmtp')
Still not working? If you still get the SMTPAuthenticationError but now the code is 534, its because the location is unknown. Follow this link:
https://accounts.google.com/DisplayUnlockCaptcha
Click continue and this should give you 10 minutes for registering your new app. So proceed to doing another login attempt now and it should work.
UPDATE: This doesn't seem to work right away you may be stuck for a while getting this error in smptlib:
235 == 'Authentication successful'
503 == 'Error: already authenticated'
The message says to use the browser to sign in:
SMTPAuthenticationError: (534, '5.7.9 Please log in with your web browser and then try again. Learn more at\n5.7.9 https://support.google.com/mail/bin/answer.py?answer=78754 qo11sm4014232igb.17 - gsmtp')
After enabling 'lesssecureapps', go for a coffee, come back, and try the 'DisplayUnlockCaptcha' link again. From user experience, it may take up to an hour for the change to kick in. Then try the sign-in process again.
A bit late but this is a solution that worked for me. Perfect if your modal is inside the overlay tag. So, the modal will close when you click anywhere outside the modal content.
HTML
<div class="modal">
<div class="overlay">
<div class="modal-content">
<p>HELLO WORLD!</p>
</div>
</div>
</div>
JS
$(document).on("click", function(event) {
if ($(event.target).has(".modal-content").length) {
$(".modal").hide();
}
});
Here is a working example
Here is a simple example of how it works, best practice to put a try\catch into it but for basic use this should do the trick. For this you have a string and file path and apply thus to the FileWriter and the BufferedWriter. This will write "Hello World"(Data variable) and then make a new line. each time this is run it will add the Data variable to the next line.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
String Data = "Hello World";
File file = new File("C:/Users/stuff.txt");
FileWriter fw = new FileWriter(file,true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(Data);
bw.newLine();
bw.close();
You can use an iterator:
std::vector<char> path;
// ...
for (std::vector<char>::const_iterator i = path.begin(); i != path.end(); ++i)
std::cout << *i << ' ';
If you want to modify the vector's contents in the for loop, then use iterator
rather than const_iterator
.
But there's lots more that can be said about this. If you just want an answer you can use, then you can stop here; otherwise, read on.
This is not another solution, but a supplement to the above iterator
solution. If you are using the C++11 standard (or later), then you can use the auto
keyword to help the readability:
for (auto i = path.begin(); i != path.end(); ++i)
std::cout << *i << ' ';
But the type of i
will be non-const (i.e., the compiler will use std::vector<char>::iterator
as the type of i
).
In this case, you might as well just use a typedef
, which also brings with it its own benefits (which I won't expound upon here):
typedef std::vector<char> Path; // 'Path' now a synonym for the vector
Path path;
// ...
for (Path::const_iterator i = path.begin(); i != path.end(); ++i)
std::cout << *i << ' ';
C++11 also introduced a type alias, which does the same job as a typedef and you may find more readable than using typedef:
using Path = std::vector<char>; // C++11 onwards only
Path path;
// ...
for (Path::const_iterator i = path.begin(); i != path.end(); ++i)
std::cout << *i << ' ';
You can, of course, use a integer type to record your position in the for
loop:
for(int i=0; i<path.size(); ++i)
std::cout << path[i] << ' ';
If you are going to do this, it's better to use the container's member types, if they are available and appropriate. std::vector
has a member type called size_type
for this job: it is the type returned by the size
method.
// Path typedef'd to std::vector<char>
for( Path::size_type i=0; i<path.size(); ++i)
std::cout << path[i] << ' ';
Why not just use this over the iterator
solution? For simple cases you might as well, but the point is that an iterator
is an object designed to do this job for more complicated objects where this solution is not going to be ideal.
See Jefffrey's solution. In C++11 (and later) you can use the new range-based for
loop, which looks like this:
for (auto i: path)
std::cout << i << ' ';
Since path
is a vector of items (explicitly std::vector<char>
), the object i
is of type of the item of the vector (i.e., explicitly, it is of type char
). The object i
has a value that is a copy of the actual item in the path
object. Thus, all changes to i
in the loop are not preserved in path
itself. Additionally, if you would like to enforce the fact that you don't want to be able to change the copied value of i
in the loop, you can force the type of i
to be const char
like this:
for (const auto i: path)
std::cout << i << ' ';
If you would like to modify the items in path
, you can use a reference:
for (auto& i: path)
std::cout << i << ' ';
and even if you don't want to modify path
, if the copying of objects is expensive you should use a const reference instead of copying by value:
for (const auto& i: path)
std::cout << i << ' ';
See Joshua's answer. You can use the STL algorithm std::copy
to copy the vector contents onto the output stream. This is an elegant solution if you are comfortable with it. Getting more familiar with STL algorithms should be encouraged, and they provide a lot of functionality that beginners may fall into reinventing themselves. Read Joshua's post for more info.
See Chris's answer, this is more a complement to the other answers since you will still need to implement one of the solutions above in the overloading. In his example he used a counter in a for
loop. For example, this is how you could quickly use Joshua's solution:
#include <iterator> // needed for std::ostram_iterator
template <typename T>
std::ostream& operator<< (std::ostream& out, const std::vector<T>& v) {
if ( !v.empty() ) {
out << '[';
std::copy (v.begin(), v.end(), std::ostream_iterator<T>(out, ", "));
out << "\b\b]";
}
return out;
}
Using any of the other solutions should be equally straightforward.
Any of the solutions presented here will work. It's up to you and the code on which one is the "best". Anything more detailed than this is probably best left for another question where the pros/cons can be properly evaluated; but as always user preference will always play a part: none of the solutions presented are wrong, but some will look nicer to each individual coder.
This is an expanded solution of an earlier one I posted. Since that post kept getting attention, I decided to expand on it and refer to the other excellent solutions that were posted here. My original post had a remark that mentioned that if you were intending on modifying your vector inside a for
loop then there are two methods provided by std::vector
to access elements: std::vector::operator[]
which does not do bounds checking, and std::vector::at
which does perform bounds checking. In other words, at
will throw if you try to access an element outside the vector and operator[]
wouldn't. I only added this comment, originally, for the sake of mentioning something that it might be useful to know of if anyone already didn't. And I see no difference now. Hence this addendum.
Another thing that people may find useful...make sure to leave off ".py" from your module name. For example, if you are trying to generate documentation for 'original' in 'original.py':
yourcode_dir$ pydoc -w original.py no Python documentation found for 'original.py' yourcode_dir$ pydoc -w original wrote original.html
In node, you can just say
console.log(aa)
and it will format it as it should.
If you need to use the resulting string you should use
JSON.stringify(aa)
This code will enumerate the graphics devices on the system (if multiple monitors are installed), and you can use that information to determine monitor affinity or automatic placement (some systems use a little side monitor for real-time displays while an app is running in the background, and such a monitor can be identified by size, screen colors, etc.):
// Test if each monitor will support my app's window
// Iterate through each monitor and see what size each is
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
Dimension mySize = new Dimension(myWidth, myHeight);
Dimension maxSize = new Dimension(minRequiredWidth, minRequiredHeight);
for (int i = 0; i < gs.length; i++)
{
DisplayMode dm = gs[i].getDisplayMode();
if (dm.getWidth() > maxSize.getWidth() && dm.getHeight() > maxSize.getHeight())
{ // Update the max size found on this monitor
maxSize.setSize(dm.getWidth(), dm.getHeight());
}
// Do test if it will work here
}
This is what has worked for me. I use this to "add" files over to the other drive, with no overwrites.
Batch file: robocopy-missingfiles.bat
@echo off
echo Copying
echo "%1"
echo to "%2"
echo.
echo Press Cntr+C to abort
Pause
echo.
@echo on
robocopy %1 %2 /Xo /XN /XC /J /SL /S /MT:8 /R:1 /W:1 /V /DCOPY:DAT /ETA /COPY:DATO /FFT /A-:SH /XD $RECYCLE.BIN "System Volume Information"
Example:
robocopy-missingfiles.bat f:\Working-folder\ E:\Backup-folder\
Do test before implementation.
img {
-webkit-filter: drop-shadow(5px 5px 5px #222222);
filter: drop-shadow(5px 5px 5px #222222);
}
That worked great for me. One thing to note tho in IE you need the full color (#222222) three characters don't work.
If you are using ajax as a function remember it expects JSON data to be returned to it, with the parameters set.
$('#example').dataTable({
"ajax" : function (data, callback, settings) {
callback({
data: [...],
recordsTotal: 40,
recordsFiltered: 40}
));
}
})
You can use either of Keys.ENTER
or Keys.RETURN
. Here are some details:
Java:
Using Keys.ENTER
:
import org.openqa.selenium.Keys;
driver.findElement(By.id("element_id")).sendKeys(Keys.ENTER);
Using Keys.RETURN
import org.openqa.selenium.Keys;
driver.findElement(By.id("element_id")).sendKeys(Keys.RETURN);
Python:
Using Keys.ENTER
:
from selenium.webdriver.common.keys import Keys
driver.find_element_by_id("element_id").send_keys(Keys.ENTER)
Using Keys.RETURN
from selenium.webdriver.common.keys import Keys
driver.find_element_by_id("element_id").send_keys(Keys.RETURN)
Keys.ENTER
and Keys.RETURN
both are from org.openqa.selenium.Keys
, which extends java.lang.Enum<Keys>
and implements java.lang.CharSequence
Enum Keys is the representations of pressable keys that aren't text. These are stored in the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF.
The special keys codes
for them are as follows:
u'\ue006'
u'\ue007'
The implementation of all the Enum Keys
are handled the same way.
Hence these is No Functional
or Operational
difference while working with either sendKeys(Keys.ENTER);
or WebElement.sendKeys(Keys.RETURN);
through Selenium.
On computer keyboards, the Enter (or the Return on Mac OS X) in most cases causes a command line, window form, or dialog box to operate its default function. This is typically to finish an "entry" and begin the desired process and is usually an alternative to pressing an OK button.
The Return is often also referred as the Enter and they usually perform identical functions; however in some particular applications (mainly page layout) Return operates specifically like the Carriage Return key from which it originates. In contrast, the Enter is commonly labelled with its name in plain text on generic PC keyboards.
I found a pretty simple way to do this. Use a button to open it using an on click
listener to start the function openc()
, like this:
String fileloc;
private void openc()
{
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = null;
try
{
f = File.createTempFile("temppic",".jpg",getApplicationContext().getCacheDir());
if (takePictureIntent.resolveActivity(getPackageManager()) != null)
{
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,FileProvider.getUriForFile(profile.this, BuildConfig.APPLICATION_ID+".provider",f));
fileloc = Uri.fromFile(f)+"";
Log.d("texts", "openc: "+fileloc);
startActivityForResult(takePictureIntent, 3);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 3 && resultCode == RESULT_OK) {
Log.d("texts", "onActivityResult: "+fileloc);
// fileloc is the uri of the file so do whatever with it
}
}
You can do whatever you want with the uri
location string. For instance, I send it to an image cropper to crop the image.
When the servlet container (like Apache Tomcat) starts up, it will read from the web.xml file (only one per application) if anything goes wrong or shows up an error at container side console, otherwise, it will deploy and load all web applications by using web.xml (so named it as deployment descriptor).
During instantiation phase of the servlet, servlet instance is ready but it cannot serve the client request because it is missing with two pieces of information:
1: context information
2: initial configuration information
Servlet engine creates servletConfig interface object encapsulating the above missing information into it servlet engine calls init() of the servlet by supplying servletConfig object references as an argument. Once init() is completely executed servlet is ready to serve the client request.
A)only once (for every client request a new thread is created) only one instance of the servlet serves any number of the client request ie, after serving one client request server does not die. It waits for other client requests ie what CGI (for every client request a new process is created) limitation is overcome with the servlet (internally servlet engine creates the thread).
A)whenever getSession() is called on HttpServletRequest object
Step 1: request object is evaluated for incoming session ID.
Step 2: if ID not available a brand new HttpSession object is created and its corresponding session ID is generated (ie of HashTable) session ID is stored into httpservlet response object and the reference of HttpSession object is returned to the servlet (doGet/doPost).
Step 3: if ID available brand new session object is not created session ID is picked up from the request object search is made in the collection of sessions by using session ID as the key.
Once the search is successful session ID is stored into HttpServletResponse and the existing session object references are returned to the doGet() or doPost() of UserDefineservlet.
1)when control leaves from servlet code to client don't forget that session object is being held by servlet container ie, the servlet engine
2)multithreading is left to servlet developers people for implementing ie., handle the multiple requests of client nothing to bother about multithread code
A servlet is created when the application starts (it is deployed on the servlet container) or when it is first accessed (depending on the load-on-startup setting) when the servlet is instantiated, the init() method of the servlet is called then the servlet (its one and only instance) handles all requests (its service() method being called by multiple threads). That's why it is not advisable to have any synchronization in it, and you should avoid instance variables of the servlet when the application is undeployed (the servlet container stops), the destroy() method is called.
You actually got it. Just forgot some quotes.
$(this).css({backgroundColor: 'red'});
or
$(this).css('background-color', 'red');
You don't need to pass over a map/object to set only one property. You can just put pass it as string. Note that if passing an object you cannot use a -
. All CSS properties which have such a character are mapped with capital letters.
Reference: .css()
You can't have private
class but you can have second
class:
public class App14692708 {
public static void main(String[] args) {
PC pc = new PC();
System.out.println(pc);
}
}
class PC {
@Override
public String toString() {
return "I am PC instance " + super.toString();
}
}
Also remember that static
inner class is indistinguishable of separate class except it's name is OuterClass.InnerClass
. So if you don't want to use "closures", use static inner class.
Request and response.
To understand the req
, try out console.log(req);
.
In Linux, this information is available in the /proc file system. I'm not a big fan of the text file format used, as each Linux distribution seems to customize at least one important file. A quick look as the source to 'ps' reveals the mess.
But here is where to find the information you seek:
/proc/meminfo contains the majority of the system-wide information you seek. Here it looks like on my system; I think you are interested in MemTotal, MemFree, SwapTotal, and SwapFree:
Anderson cxc # more /proc/meminfo
MemTotal: 4083948 kB
MemFree: 2198520 kB
Buffers: 82080 kB
Cached: 1141460 kB
SwapCached: 0 kB
Active: 1137960 kB
Inactive: 608588 kB
HighTotal: 3276672 kB
HighFree: 1607744 kB
LowTotal: 807276 kB
LowFree: 590776 kB
SwapTotal: 2096440 kB
SwapFree: 2096440 kB
Dirty: 32 kB
Writeback: 0 kB
AnonPages: 523252 kB
Mapped: 93560 kB
Slab: 52880 kB
SReclaimable: 24652 kB
SUnreclaim: 28228 kB
PageTables: 2284 kB
NFS_Unstable: 0 kB
Bounce: 0 kB
CommitLimit: 4138412 kB
Committed_AS: 1845072 kB
VmallocTotal: 118776 kB
VmallocUsed: 3964 kB
VmallocChunk: 112860 kB
HugePages_Total: 0
HugePages_Free: 0
HugePages_Rsvd: 0
Hugepagesize: 2048 kB
For CPU utilization, you have to do a little work. Linux makes available overall CPU utilization since system start; this probably isn't what you are interested in. If you want to know what the CPU utilization was for the last second, or 10 seconds, then you need to query the information and calculate it yourself.
The information is available in /proc/stat, which is documented pretty well at http://www.linuxhowtos.org/System/procstat.htm; here is what it looks like on my 4-core box:
Anderson cxc # more /proc/stat
cpu 2329889 0 2364567 1063530460 9034 9463 96111 0
cpu0 572526 0 636532 265864398 2928 1621 6899 0
cpu1 590441 0 531079 265949732 4763 351 8522 0
cpu2 562983 0 645163 265796890 682 7490 71650 0
cpu3 603938 0 551790 265919440 660 0 9040 0
intr 37124247
ctxt 50795173133
btime 1218807985
processes 116889
procs_running 1
procs_blocked 0
First, you need to determine how many CPUs (or processors, or processing cores) are available in the system. To do this, count the number of 'cpuN' entries, where N starts at 0 and increments. Don't count the 'cpu' line, which is a combination of the cpuN lines. In my example, you can see cpu0 through cpu3, for a total of 4 processors. From now on, you can ignore cpu0..cpu3, and focus only on the 'cpu' line.
Next, you need to know that the fourth number in these lines is a measure of idle time, and thus the fourth number on the 'cpu' line is the total idle time for all processors since boot time. This time is measured in Linux "jiffies", which are 1/100 of a second each.
But you don't care about the total idle time; you care about the idle time in a given period, e.g., the last second. Do calculate that, you need to read this file twice, 1 second apart.Then you can do a diff of the fourth value of the line. For example, if you take a sample and get:
cpu 2330047 0 2365006 1063853632 9035 9463 96114 0
Then one second later you get this sample:
cpu 2330047 0 2365007 1063854028 9035 9463 96114 0
Subtract the two numbers, and you get a diff of 396, which means that your CPU had been idle for 3.96 seconds out of the last 1.00 second. The trick, of course, is that you need to divide by the number of processors. 3.96 / 4 = 0.99, and there is your idle percentage; 99% idle, and 1% busy.
In my code, I have a ring buffer of 360 entries, and I read this file every second. That lets me quickly calculate the CPU utilization for 1 second, 10 seconds, etc., all the way up to 1 hour.
For the process-specific information, you have to look in /proc/pid; if you don't care abut your pid, you can look in /proc/self.
CPU used by your process is available in /proc/self/stat. This is an odd-looking file consisting of a single line; for example:
19340 (whatever) S 19115 19115 3084 34816 19115 4202752 118200 607 0 0 770 384 2
7 20 0 77 0 266764385 692477952 105074 4294967295 134512640 146462952 321468364
8 3214683328 4294960144 0 2147221247 268439552 1276 4294967295 0 0 17 0 0 0 0
The important data here are the 13th and 14th tokens (0 and 770 here). The 13th token is the number of jiffies that the process has executed in user mode, and the 14th is the number of jiffies that the process has executed in kernel mode. Add the two together, and you have its total CPU utilization.
Again, you will have to sample this file periodically, and calculate the diff, in order to determine the process's CPU usage over time.
Edit: remember that when you calculate your process's CPU utilization, you have to take into account 1) the number of threads in your process, and 2) the number of processors in the system. For example, if your single-threaded process is using only 25% of the CPU, that could be good or bad. Good on a single-processor system, but bad on a 4-processor system; this means that your process is running constantly, and using 100% of the CPU cycles available to it.
For the process-specific memory information, you ahve to look at /proc/self/status, which looks like this:
Name: whatever
State: S (sleeping)
Tgid: 19340
Pid: 19340
PPid: 19115
TracerPid: 0
Uid: 0 0 0 0
Gid: 0 0 0 0
FDSize: 256
Groups: 0 1 2 3 4 6 10 11 20 26 27
VmPeak: 676252 kB
VmSize: 651352 kB
VmLck: 0 kB
VmHWM: 420300 kB
VmRSS: 420296 kB
VmData: 581028 kB
VmStk: 112 kB
VmExe: 11672 kB
VmLib: 76608 kB
VmPTE: 1244 kB
Threads: 77
SigQ: 0/36864
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: fffffffe7ffbfeff
SigIgn: 0000000010001000
SigCgt: 20000001800004fc
CapInh: 0000000000000000
CapPrm: 00000000ffffffff
CapEff: 00000000fffffeff
Cpus_allowed: 0f
Mems_allowed: 1
voluntary_ctxt_switches: 6518
nonvoluntary_ctxt_switches: 6598
The entries that start with 'Vm' are the interesting ones:
The only item I'm not sure about is Swapspace currently used by my process. I don't know if this is available.
There is a vcvars32.bat in your Visual Studio installation directory. You can add call cmd.exe at the end of that batch program and launch it. From that shell you can use CMake or cmake-gui and cl.exe would be known to CMake.
It is possible and is deceptively easy:
bin\Debug
folder below the project file (.csproj).app.publish
folder (they are not needed), and the .pdb files unless you foresee debugging directly on your user's system (for example, by remote control)), and provide it to the users.An added advantage is that, as a ClickOnce application, it does not require administrative privileges to run (if your application follows the normal guidelines for which folders to use for application data, etc.).
As for .NET, you can check for the minimum required version of .NET being installed (or at all) in the application (most users will already have it installed) and present a dialog with a link to the download page on the Microsoft website (or point to one of your pages that could redirect to the Microsoft page - this makes it more robust if the Microsoft URL change). As it is a small utility, you could target .NET 2.0 to reduce the probability of a user to have to install .NET.
It works. We use this method during development and test to avoid having to constantly uninstall and install the application and still being quite close to how the final application will run.
In newer versions of typescript you can use:
type Customers = Record<string, Customer>
In older versions you can use:
var map: { [email: string]: Customer; } = { };
map['[email protected]'] = new Customer(); // OK
map[14] = new Customer(); // Not OK, 14 is not a string
map['[email protected]'] = 'x'; // Not OK, 'x' is not a customer
You can also make an interface if you don't want to type that whole type annotation out every time:
interface StringToCustomerMap {
[email: string]: Customer;
}
var map: StringToCustomerMap = { };
// Equivalent to first line of above
There are three options for it using setBackgroundTintList
int myColor = Color.BLACK;
button.setBackgroundTintList(new ColorStateList(EMPTY, new int[] { myColor }));
button.setBackgroundTintList(ColorStateList.valueOf(myColor));
button.setBackgroundTintList(contextInstance.getResources().getColorStateList(R.color.my_color));
I don't think you can "legally" load only part of an XML file, since then it would be malformed (there would be a missing closing element somewhere).
Using LINQ-to-XML, you can do var doc = XDocument.Load("yourfilepath")
. From there its just a matter of querying the data you want, say like this:
var authors = doc.Root.Elements().Select( x => x.Element("Author") );
HTH.
EDIT:
Okay, just to make this a better sample, try this (with @JWL_'s suggested improvement):
using System;
using System.Xml.Linq;
namespace ConsoleApplication1 {
class Program {
static void Main( string[] args ) {
XDocument doc = XDocument.Load( "XMLFile1.xml" );
var authors = doc.Descendants( "Author" );
foreach ( var author in authors ) {
Console.WriteLine( author.Value );
}
Console.ReadLine();
}
}
}
You will need to adjust the path in XDocument.Load()
to point to your XML file, but the rest should work. Ask questions about which parts you don't understand.
Error 150 means you have a problem with your foreign key. Possibly the key on the foreign table isn't the exact same type?