A one-liner:
var encodedMsg = $('<div />').text(message).html();
See it work:
Might not be so related to the issue above. However if you are looking for a way to serialize Java object as string, this could come in hand
package pt.iol.security;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.codec.binary.Base64;
public class ObjectUtil {
static final Base64 base64 = new Base64();
public static String serializeObjectToString(Object object) throws IOException {
try (
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(arrayOutputStream);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(gzipOutputStream);) {
objectOutputStream.writeObject(object);
objectOutputStream.flush();
return new String(base64.encode(arrayOutputStream.toByteArray()));
}
}
public static Object deserializeObjectFromString(String objectString) throws IOException, ClassNotFoundException {
try (
ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(base64.decode(objectString));
GZIPInputStream gzipInputStream = new GZIPInputStream(arrayInputStream);
ObjectInputStream objectInputStream = new ObjectInputStream(gzipInputStream)) {
return objectInputStream.readObject();
}
}
}
In Jenkins , we have the format is as:
Minute(0-59) Hour(0-23) Day(1-7) Month(1-12) Day of the Week
Netscape ANSI encoded files use 0D 0D 0A for their line breaks.
updateValue(data){
// retriving index from array
let indexValue = this.items.indexOf(data);
// changing specific element in array
this.items[indexValue].isShow = !this.items[indexValue].isShow;
}
Whilst you can of course use the base64
module, you can also to use the codecs
module (referred to in your error message) for binary encodings (meaning non-standard & non-text encodings).
For example:
import codecs
my_bytes = b"Hello World!"
codecs.encode(my_bytes, "base64")
codecs.encode(my_bytes, "hex")
codecs.encode(my_bytes, "zip")
codecs.encode(my_bytes, "bz2")
This can come in useful for large data as you can chain them to get compressed and json-serializable values:
my_large_bytes = my_bytes * 10000
codecs.decode(
codecs.encode(
codecs.encode(
my_large_bytes,
"zip"
),
"base64"),
"utf8"
)
Refs:
Note: I updated this answer based on comments and other answers, so comments prior to May 22nd 2020 may no longer apply. Also I noticed today that some IDE's like VS Code and PyCharm do not recognize a HEREDOC marker that contains spaces, whereas bash has no problem with it, so I'm updating this answer again.
Bash does not provide a builtin syntax for multi-line comment but there are hacks using existing bash syntax that "happen to work now".
Personally I think the simplest (ie least noisy, least weird, easiest to type, most explicit) is to use a quoted HEREDOC, but make it obvious what you are doing, and use the same HEREDOC marker everywhere:
<<'###BLOCK-COMMENT'
line 1
line 2
line 3
line 4
###BLOCK-COMMENT
Single-quoting the HEREDOC marker avoids some shell parsing side-effects, such as weird subsitutions that would cause crash or output, and even parsing of the marker itself. So the single-quotes give you more freedom on the open-close comment marker.
For example the following uses a triple hash which kind of suggests multi-line comment in bash. This would crash the script if the single quotes were absent. Even if you remove ###
, the FOO{}
would crash the script (or cause bad substitution to be printed if no set -e
) if it weren't for the single quotes:
set -e
<<'###BLOCK-COMMENT'
something something ${FOO{}} something
more comment
###BLOCK-COMMENT
ls
You could of course just use
set -e
<<'###'
something something ${FOO{}} something
more comment
###
ls
but the intent of this is definitely less clear to a reader unfamiliar with this trickery.
Note my original answer used '### BLOCK COMMENT'
, which is fine if you use vanilla vi/vim but today I noticed that PyCharm and VS Code don't recognize the closing marker if it has spaces.
Nowadays any good editor allows you to press ctrl-/ or similar, to un/comment the selection. Everyone definitely understands this:
# something something ${FOO{}} something
# more comment
# yet another line of comment
although admittedly, this is not nearly as convenient as the block comment above if you want to re-fill your paragraphs.
There are surely other techniques, but there doesn't seem to be a "conventional" way to do it. It would be nice if ###>
and ###<
could be added to bash to indicate start and end of comment block, seems like it could be pretty straightforward.
You can read an article i have written for joins in LINQ here
var query =
from u in Repo.T_Benutzer
join bg in Repo.T_Benutzer_Benutzergruppen
on u.BE_ID equals bg.BEBG_BE
into temp
from j in temp.DefaultIfEmpty()
select new
{
BE_User = u.BE_User,
BEBG_BG = (int?)j.BEBG_BG// == null ? -1 : j.BEBG_BG
//, bg.Name
}
The following is the equivalent using extension methods:
var query =
Repo.T_Benutzer
.GroupJoin
(
Repo.T_Benutzer_Benutzergruppen,
x=>x.BE_ID,
x=>x.BEBG_BE,
(o,i)=>new {o,i}
)
.SelectMany
(
x => x.i.DefaultIfEmpty(),
(o,i) => new
{
BE_User = o.o.BE_User,
BEBG_BG = (int?)i.BEBG_BG
}
);
You want to look at the patch() function, and sneak in points for the start and end of the horizontal line:
x = 0:.1:2*pi;
y = sin(x)+rand(size(x))/2;
x2 = [0 x 2*pi];
y2 = [.1 y .1];
patch(x2, y2, [.8 .8 .1]);
If you only want the filled in area for a part of the data, you'll need to truncate the x and y vectors to only include the points you need.
You have missed out the field name id
in the second NOT LIKE
. Try:
SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'
The AND
in the where clause joins 2 full condition expressions such as id NOT LIKE '1%'
and can't be used to list multiple values that the id is 'not like'.
Just use the below code. It will shadow surround the entire DIV
-webkit-box-shadow: -1px 1px 5px 9px rgba(0,0,0,0.75);
-moz-box-shadow: -1px 1px 5px 9px rgba(0,0,0,0.75);
box-shadow: -1px 1px 5px 9px rgba(0,0,0,0.75);
Hope this will work
This could help
function exportToExcel(){
var htmls = "";
var uri = 'data:application/vnd.ms-excel;base64,';
var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>';
var base64 = function(s) {
return window.btoa(unescape(encodeURIComponent(s)))
};
var format = function(s, c) {
return s.replace(/{(\w+)}/g, function(m, p) {
return c[p];
})
};
htmls = "YOUR HTML AS TABLE"
var ctx = {
worksheet : 'Worksheet',
table : htmls
}
var link = document.createElement("a");
link.download = "export.xls";
link.href = uri + base64(format(template, ctx));
link.click();
}
MY PREFERRED METHOD is using fopen,fwrite and fclose [it will cost less CPU]
$f=fopen('myfile.txt','w');
fwrite($f,'new content');
fclose($f);
Warning for those using file_put_contents
It'll affect a lot in performance, for example [on the same class/situation] file_get_contents too: if you have a BIG FILE, it'll read the whole content in one shot and that operation could take a long waiting time
If you are interesting in modern api way, avoiding NSSearchPath and filter files in documents directory, before deletion, you can do like:
let fileManager = FileManager.default
let keys: [URLResourceKey] = [.nameKey, .isDirectoryKey]
let options: FileManager.DirectoryEnumerationOptions = [.skipsHiddenFiles, .skipsPackageDescendants]
guard let documentsUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask).last,
let fileEnumerator = fileManager.enumerator(at: documentsUrl,
includingPropertiesForKeys: keys,
options: options) else { return }
let urls: [URL] = fileEnumerator.flatMap { $0 as? URL }
.filter { $0.pathExtension == "exe" }
for url in urls {
do {
try fileManager.removeItem(at: url)
} catch {
assertionFailure("\(error)")
}
}
1 - Treat functions as objects.
2 - The apply method is similar to __call __ in Python, which allows you to use an instance of a given class as a function.
This is easier to read for me:
<input type="radio" name="rWF" id="rWF" value=1 <?php if ($WF == '1') {echo ' checked ';} ?> />Water Fall</label>
<input type="radio" name="rWF" id="rWF" value=0 <?php if ($WF == '0') {echo ' checked ';} ?> />nope</label>
Using flexbox
#parent_div_1{
display:flex;
flex-wrap: wrap;
}
I used pekka's pattern. I think yet another pattern.
<script src="<% = Url.Content("~/Site/Scripts/myjsfile.js") %>?root=<% = Page.ResolveUrl("~/Site/images") %>">
and parsed querystring in myjsfile.js.
Substring is probably what you want, as others pointed out. But just to add another option to the mix...
string result = string.Join(string.Empty, str.Skip(10));
You dont even need to check the length on this! :) If its less than 10 chars, you get an empty string.
For CPython/PyPy 3.6, and any Python 3.7 or higher, this is easily done with:
>>> d = {2:3, 1:89, 4:5, 3:0}
>>> dict(sorted(d.items()))
{1: 89, 2: 3, 3: 0, 4: 5}
Not trying to take any credits here, all credit goes to @theazureshadow for his reply, but I personally had to adapt it for a table that has some <th>
instead of <td>
for it's first row's cells.
I'm just posting the modified version here in case some of you want to use @theazureshadow's solution, but like me, have some <th>
in the first <tr>
. The class "reportTable" only have to be applied to the table itself.:
table.reportTable {
border-collapse: separate;
border-spacing: 0;
}
table.reportTable td {
border: solid gray 1px;
border-style: solid none none solid;
padding: 10px;
}
table.reportTable td:last-child {
border-right: solid gray 1px;
}
table.reportTable tr:last-child td{
border-bottom: solid gray 1px;
}
table.reportTable th{
border: solid gray 1px;
border-style: solid none none solid;
padding: 10px;
}
table.reportTable th:last-child{
border-right: solid gray 1px;
border-top-right-radius: 10px;
}
table.reportTable th:first-child{
border-top-left-radius: 10px;
}
table.reportTable tr:last-child td:first-child{
border-bottom-left-radius: 10px;
}
table.reportTable tr:last-child td:last-child{
border-bottom-right-radius: 10px;
}
Feel free to adjust the paddings, radiuses, etc to fit your needs. Hope that helps people!
I ended up with two changes to the original reply.
document
. This makes it harder to filter only a some of the ajax requests. Soo...This is the code after these changes:
$(document)
.hide() // hide it initially
.ajaxSend(function(event, jqxhr, settings) {
if (settings.url !== "ajax/request.php") return;
$(".spinner").show();
})
.ajaxComplete(function(event, jqxhr, settings) {
if (settings.url !== "ajax/request.php") return;
$(".spinner").hide();
})
You can call [aDictionary description], or anywhere you would need a format string, just use %@ to stand in for the dictionary:
[NSString stringWithFormat:@"my dictionary is %@", aDictionary];
or
NSLog(@"My dictionary is %@", aDictionary);
Oracle SQL Developer 2020-02 support PostgreSQL, but it is just the basics by adding postgreSQL driver under jdbc dir and configure by adding as a 3rd party driver.
The supported functionality:
Not supported functionalities:
The sad thing is Oracle should only change the queries behind this view in case of PostgreSql connections. For example for indexes they need to use this query: select * from pg_catalog.pg_indexes;
Try this in angular 8.0:
@ViewChild('result',{static: false}) resultElement: ElementRef;
What worked for me:
irb(main):027:0> puts ['12','34','35','231'].inspect.to_s[1..-2].gsub('"', "'")
'12', '34', '35', '231'
=> nil
I know it's too late, but in case someone still need help. Here is the working solution.
Setting an error
is pretty straight forward. But it will be displayed to user, when he request Focus
on it. So to do the both thing on your own, User this code
.
firstName.setError("Enter FirstName");
firstName.requestFocus();
Did you recently updated your eclipse android plugin (adt r17)? Then the following link might help:
How to fix the classdefnotfounderror with adt-17
Update: One year has passed since the question arose. I will keep the link, because even in 2013 it seem to help some people to solve the problem. But please take care what you are doing, see Erics comment below. Current ADT-Version is 22, I recommend using the most current version.
Chiming in on this old thread -- the OP stated HH:MM:SS, and many of the solutions work, until you realize you need more than 24 hours listed. And maybe you don't want more than a single line of code. Here you go:
d=(s)=>{f=Math.floor;g=(n)=>('00'+n).slice(-2);return f(s/3600)+':'+g(f(s/60)%60)+':'+g(s%60)}
It returns H+:MM:SS. To use it, simply use:
d(91260); // returns "25:21:00"
d(960); // returns "0:16:00"
...I tried to get it to use the least amount of code possible, for a nice one-liner approach.
I'm not sure if PyQt does have a script like this, but after you install PySide there is a script in pythons script directory "uic.py". You can use this script to convert a .ui file to a .py file:
python uic.py input.ui -o output.py -x
I have the same problem while integrating the Facebook SDK for login.
I'm suggesting below approach for development mode > you can test all things if you are login with same account, which is used for 'developers.facebook.com' and if you want to use another accounts then you need to add Roles for that particular app, for that you can add developer or testers by using fid or facebook username.
Eg: - Select the particular app > Roles and then add developer or testers.
Change the checkboxes so that the name includes the index inside the brackets:
<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>">
The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.
a.button:hover{
background: #383; }
works for me but in my case
#buttonClick:hover {
background-color:green; }
XAMPP is more powerful and resource taking than WAMP.
WAMP provides support for MySQL and PHP.
XAMPP provides support for MYSQL, PHP and PERL
XAMPP also has SSL feature while WAMP doesnt.
If your applications need to deal with native web apps only, Go for WAMP.
If you need advanced features as stated above, go for XAMPP.
As of priority, you cant run both together with default installation as XAMPP gets a higher priority and it takes up ports. So WAMP cant be run in parallel with XAMPP.
I'm able to execute your exact query by just making sure there is a semicolon at the end of my select statement. (Output is actual, connection params removed.)
echo "select 1 from dual;" | sqlplus -s username/password@host:1521/service
Output:
1
----------
1
Note that is should matter but this is running on Mac OS X Snow Leopard and Oracle 11g.
Building off of @Dominic Green's answer using jQuery, here is a solution that should work for images that are either wider than they are high or higher than they are wide.
There is probably a more elegant way of doing the JavaScript, but this does work.
function myTest() {
var imgH = $("#my-img").height();
var imgW = $("#my-img").width();
if(imgW > imgH) {
$(".container img").css("height", "100%");
var conWidth = $(".container").width();
var imgWidth = $(".container img").width();
var gap = (imgWidth - conWidth)/2;
$(".container img").css("margin-left", -gap);
} else {
$(".container img").css("width", "100%");
var conHeight = $(".container").height();
var imgHeight = $(".container img").height();
var gap = (imgHeight - conHeight)/2;
$(".container img").css("margin-top", -gap);
}
}
myTest();
Why don't you use the Notepad++ multiline editing capabilities?
Hold down Alt while selecting text (using your usual click-and-drag approach) to select text across multiple lines. This is sometimes also referred to as column editing.
You could place the cursor at the beginning of the file, Press (and hold) Alt, Shift and then just keep pressing the down-arrow or PageDown to select the lines that you want to prepend with some text :-) Easy. Multiline editing is a very useful feature of Notepad++. It's also possible in Visual Studio, in the same manner, and also in Eclipse by switching to Block Selection Mode by pressing Alt+Shift+A and then use mouse to select text across lines.
Along with the points made by others, the $=
selector is the "ends with" selector. You will want the *=
(contains) selector, like so:
$('a').each(function() {
if ($(this).is('[href*="?"')) {
alert("Contains questionmark");
}
});
As noted by Matt Ball, unless you will need to also manipulate links without a question mark (which may be the case, since you say your example is simplified), it would be less code and much faster to simply select only the links you want to begin with:
$('a[href*="?"]').each(function() {
alert("Contains questionmark");
});
The following works in Firefox and Opera (sorry, I do not have access to other browsers at the moment):
<div class="form-field">
<input id="option1" type="radio" name="opt"/>
<label for="option1">Option 1</label>
</div>
The CSS:
.form-field * {
vertical-align: middle;
}
I did by using pip install <required-library> --ignore-installed enum34
Once your required library is installed, look for warnings during the build.
I got an Error like this:
Using legacy setup.py install for future, since package 'wheel' is not installed
ERROR: pyejabberd 0.2.11 has requirement enum34==1.1.2, but you'll have enum34 1.1.10 which is incompatible.
To fix this issue now run the command: pip freeze | grep enum34
. This will give you the version of the installed enum34. Now uninstall it by pip uninstall enum34
and reinstall the required version as
pip install "enum34==1.1.20"
Don't fuss around with .htaccess files when you can use Apache mass virtual hosting.
From the documentation:
#include part of the server name in the filenames VirtualDocumentRoot /www/hosts/%2/docs
In a way it's the reverse of your question: every 'subdomain' is a user. If the user does not exist, you get an 404.
The only drawback is that the environment variable DOCUMENT_ROOT
is not correctly set to the used subdirectory, but the default document_root in de htconfig.
For those wondering how to implement Garry's solution with more than one header this is it:
#wrapper {_x000D_
width: 235px;_x000D_
}_x000D_
_x000D_
table {_x000D_
border: 1px solid black;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
th,_x000D_
td {_x000D_
width: 100px;_x000D_
border: 1px solid black;_x000D_
}_x000D_
_x000D_
thead>tr {_x000D_
position: relative;_x000D_
display: block;_x000D_
}_x000D_
_x000D_
tbody {_x000D_
display: block;_x000D_
height: 80px;_x000D_
overflow: auto;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th>column1</th>_x000D_
<th>column2</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>row1</td>_x000D_
<td>row1</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>row2</td>_x000D_
<td>row2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>row3</td>_x000D_
<td>row3</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>row4</td>_x000D_
<td>row4</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</div>
_x000D_
You need the data to be in "tall" format instead of "wide" for ggplot2. "wide" means having an observation per row with each variable as a different column (like you have now). You need to convert it to a "tall" format where you have a column that tells you the name of the variable and another column that tells you the value of the variable. The process of passing from wide to tall is usually called "melting". You can use tidyr::gather
to melt your data frame:
library(ggplot2)
library(tidyr)
test_data <-
data.frame(
var0 = 100 + c(0, cumsum(runif(49, -20, 20))),
var1 = 150 + c(0, cumsum(runif(49, -10, 10))),
date = seq(as.Date("2002-01-01"), by="1 month", length.out=100)
)
test_data %>%
gather(key,value, var0, var1) %>%
ggplot(aes(x=date, y=value, colour=key)) +
geom_line()
Just to be clear the data
that ggplot
is consuming after piping it via gather
looks like this:
date key value
2002-01-01 var0 100.00000
2002-02-01 var0 115.16388
...
2007-11-01 var1 114.86302
2007-12-01 var1 119.30996
You have to Select Build Tool Version from your project setting.
Select Project App Folder
Press F4 OR Right Click on Project App
Folder and open Module Settings In The Properties tab select Build
Tool Version from List
This will work on my side i hope it will help you.
You can use Cmd command to run Batch file.
Here is my way =>
cmd /c ""Full_Path_Of_Batch_Here.cmd" "
More information => cmd /?
I have this issue too. I suspect there is an issue with DigitalOcean’s nameservers, so this will likely affect a lot of other people too. Here’s what I’ve done to temporarily get around it - but someone else might be able to advise on a better long-term fix:
Make sure your DNS Resolver config file is writable:
sudo chmod o+r /etc/resolv.conf
Temporarily change your DNS to use Google’s nameservers instead of DigitalOcean’s:
sudo nano /etc/resolv.conf
Change the IP address in the file to: 8.8.8.8
Press CTRL
+
X
to save the file.
This is only a temporary fix as this file is automatically written/updated by the server, however, I’ve not yet worked out what writes to it so that I can update it permanently.
Try this one:
$.fn.extend({
"calendar":function(){
console.log(this);
var methods = {
"add":function(){console.log("add"); return this;},
"init":function(){console.log("init"); return this;},
"sample":function(){console.log("sample"); return this;}
};
methods.init(); // you can call any method inside
return methods;
}});
$.fn.calendar() // caller or
$.fn.calendar().sample().add().sample() ......; // call methods
In case of the absolute value of an integer x without using Math.abs(), conditions or bit-wise operations, below could be a possible solution in Java.
(int)(((long)x*x - 1)%(double)x + 1);
Because Java treats a%b
as a - a/b * b
, the sign of the result will be same as "a" no matter what sign of "b" is; (x*x-1)%x
will equal abs(x)-1
; type casting of "long" is to prevent overflow and double
allows dividing by zero.
Again, x = Integer.MIN_VALUE
will cause overflow due to subtracting 1.
I put commit .gitignore, which is a courtesy to other who may build my project that the following files are derived and should be ignored.
I usually do a hybrid. I like to make makefile generate the .gitignore file since the makefile will know all the files associated with the project -derived or otherwise. Then have a top level project .gitignore that you check in, which would ignore the generated .gitignore files created by the makefile for the various sub directories.
So in my project, I might have a bin sub directory with all the built executables. Then, I'll have my makefile generate a .gitignore for that bin directory. And in the top directory .gitignore that lists bin/.gitignore. The top one is the one I check in.
I was just implementing this actual problem in my current project. i did it for all ajax-POSTs that needed an authenticated user.
First off i decided to hook my jquery ajax calls so i do not to repeat myself too often. this javascript snippet ensures all ajax (post) calls will add my request validation token to the request. Note: the name __RequestVerificationToken is used by the .Net framework so i can utilize the standard Anti-CSRF features as shown below.
$(document).ready(function () {
var securityToken = $('[name=__RequestVerificationToken]').val();
$('body').bind('ajaxSend', function (elm, xhr, s) {
if (s.type == 'POST' && typeof securityToken != 'undefined') {
if (s.data.length > 0) {
s.data += "&__RequestVerificationToken=" + encodeURIComponent(securityToken);
}
else {
s.data = "__RequestVerificationToken=" + encodeURIComponent(securityToken);
}
}
});
});
In your Views where you need the token to be available to the above javascript just use the common HTML-Helper. You can basically add this code whereever you want. I placed it within a if(Request.IsAuthenticated) statement:
@Html.AntiForgeryToken() // you can provide a string as salt when needed which needs to match the one on the controller
In your controller simply use the standard ASP.Net MVC Anti-CSRF mechanism. I did it like this (though i actually used Salt).
[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public JsonResult SomeMethod(string param)
{
// do something
return Json(true);
}
With Firebug or a similar tool you can easily see how your POST requests now have a __RequestVerificationToken parameter appended.
1.On Child Widget : add parameter Function paramter
class ChildWidget extends StatefulWidget {
final Function() notifyParent;
ChildWidget({Key key, @required this.notifyParent}) : super(key: key);
}
2.On Parent Widget : create a Function for the child to callback
refresh() {
setState(() {});
}
3.On Parent Widget : pass parentFunction to Child Widget
new ChildWidget( notifyParent: refresh );
4.On Child Widget : call the Parent Function
widget.notifyParent();
To get the number of selected rows I usually use the following:
cursor.execute(sql)
count = (len(cursor.fetchall))
To me the code coverage configuration in the "Local.testtesttings" file "caused" the problem. I forgot to update the files that were referenced there.
This problem happens when the apache user (www-data) does not have permission to write in the folder. To solver this problem you need to put the user inside the group www-data.
I just made this:
Execute this php code <?php echo exec('whoami'); ?>
to discover the user used by apache. After, execute the commands in the terminal:
user@machine:/# cd /var/www/html
user@machine:/var/www/html# ls -l
It will return something like this:
total of files
drwxr-xr-x 7 user group size date folder
I kept the user but changed the group to www-data
chown -R user:www-data yourprojectfoldername
chmod 775 yourprojectfoldername
When you read()
the file, you may get a newline character '\n'
in your string. Try either
if UserInput.strip() == 'List contents':
or
if 'List contents' in UserInput:
Also note that your second file open
could also use with
:
with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile: if UserInput.strip() == 'List contents': # or if s in f: UserInputFile.write("ls") else: print "Didn't work"
To bypass caching and avoid adding infinite timestamps to the image url, strip the previous timestamp before adding a new one, this is how I've done it.
//refresh the image every 60seconds
var xyro_refresh_timer = setInterval(xyro_refresh_function, 60000);
function xyro_refresh_function(){
//refreshes an image with a .xyro_refresh class regardless of caching
//get the src attribute
source = jQuery(".xyro_refresh").attr("src");
//remove previously added timestamps
source = source.split("?", 1);//turns "image.jpg?timestamp=1234" into "image.jpg" avoiding infinitely adding new timestamps
//prep new src attribute by adding a timestamp
new_source = source + "?timestamp=" + new Date().getTime();
//alert(new_source); //you may want to alert that during developement to see if you're getting what you wanted
//set the new src attribute
jQuery(".xyro_refresh").attr("src", new_source);
}
Try
mysqldump databaseExample > file.sql
Similar, but again a little bit different.
Make the image 100% opacity so it is clear. And then on img hover reduce it to the opacity you want. In this example, I have also added easing for a nice transition.
img {
-webkit-filter: brightness(100%);
}
img:hover {
-webkit-filter: brightness(70%);
-webkit-transition: all 1s ease;
-moz-transition: all 1s ease;
-o-transition: all 1s ease;
-ms-transition: all 1s ease;
transition: all 1s ease;
}
That will do it, Hope that helps.
Thank you Robert Byers for your jsfiddle
A simple, newbie friendly way for looking into a file:
git gui browser <branch>
which lets you explore the contents of any file.
It's also there in the File menu of git gui
. Most other -more advanced- GUI wrappers (Qgit, Egit, etc..) offer browsing/opening files as well.
To dynamically construct the returnUrl in any View, try this:
@{
var formCollection =
new FormCollection
{
new FormCollection(Request.Form),
new FormCollection(Request.QueryString)
};
var parameters = new RouteValueDictionary();
formCollection.AllKeys
.Select(k => new KeyValuePair<string, string>(k, formCollection[k])).ToList()
.ForEach(p => parameters.Add(p.Key, p.Value));
}
<!-- Option #1 -->
@Html.ActionLink("Option #1", "Action", "Controller", parameters, null)
<!-- Option #2 -->
<a href="/Controller/Action/@[email protected](ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString(), parameters)">Option #2</a>
<!-- Option #3 -->
<a href="@Url.Action("Action", "Controller", new { object.ID, returnUrl = Url.Action(ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString(), parameters) }, null)">Option #3</a>
This also works in Layout Pages, Partial Views and Html Helpers
Related: MVC3 Dynamic Return URL (Same but from within any Controller/Action)
Try the PowerShell PowerToy... It adds a context menu item for Open PowerShell Here.
Or you could create a shortcut that opens PowerShell with the Start In folder being your Projects folder.
just copy " _CRT_SECURE_NO_WARNINGS " paste it on projects->properties->c/c++->preprocessor->preprocessor definitions click ok.it will work
This happens to me when I do not clean solution before build new .edmx designer. So just don’t forget to clean solution before you build new .edmx designer. This helps me to skip lot more issues with this one. Bellow the navigation details provided incase you are new in visual studio.
Click->Build->Clean Solution
Then Click->Build->Rebuild Solution
Hope this helps. Thanks everyone
it turns out that I got this error because my requested module is not bundled in the minification prosses
due to path misspelling
so make sure that your module exists in minified js file (do search for a word within it to be sure)
As Roland mentioned in their answer, it's a warning that the ssh-agent
doesn't understand the format of the public key and even then, the public key will not be used locally.
However, I can also elaborate and answer why the warning is there. It simply boils down to the fact that the PuTTY Key Generator generates two different public key formats depending on what you do in the program.
Note: Throughout my explanation, the key files I will be using/generating will be named id_rsa
with their appropriate extensions. Furthermore, for copy-paste convenience, the parent folder of the keys will be assumed to be ~/.ssh/
. Adjust these details to suit your needs as desired.
Link to the relevant PuTTY documentation
When you save a key using the PuTTY Key Generator using the "Save public key" button, it will be saved in the format defined by RFC 4716.
Example:
---- BEGIN SSH2 PUBLIC KEY ----
Comment: "github-example-key"
AAAAB3NzaC1yc2EAAAABJQAAAQEAhl/CNy9wI1GVdiHAJQV0CkHnMEqW7+Si9WYF
i2fSBrsGcmqeb5EwgnhmTcPgtM5ptGBjUZR84nxjZ8SPmnLDiDyHDPIsmwLBHxcp
pY0fhRSGtWL5fT8DGm9EfXaO1QN8c31VU/IkD8niWA6NmHNE1qEqpph3DznVzIm3
oMrongEjGw7sDP48ZTZp2saYVAKEEuGC1YYcQ1g20yESzo7aP70ZeHmQqI9nTyEA
ip3mL20+qHNsHfW8hJAchaUN8CwNQABJaOozYijiIUgdbtSTMRDYPi7fjhgB3bA9
tBjh7cOyuU/c4M4D6o2mAVYdLAWMBkSoLG8Oel6TCcfpO/nElw==
---- END SSH2 PUBLIC KEY ----
Contrary to popular belief, this format doesn't get saved by the generator. However it is generated and shown in the text box titled "Public key for pasting into OpenSSH authorized_keys file". To save it as a file, you have to manually copy it from the text box and paste it into a new text file.
For the key shown above, this would be:
ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAQEAhl/CNy9wI1GVdiHAJQV0CkHnMEqW7+Si9WYFi2fSBrsGcmqeb5EwgnhmTcPgtM5ptGBjUZR84nxjZ8SPmnLDiDyHDPIsmwLBHxcppY0fhRSGtWL5fT8DGm9EfXaO1QN8c31VU/IkD8niWA6NmHNE1qEqpph3DznVzIm3oMrongEjGw7sDP48ZTZp2saYVAKEEuGC1YYcQ1g20yESzo7aP70ZeHmQqI9nTyEAip3mL20+qHNsHfW8hJAchaUN8CwNQABJaOozYijiIUgdbtSTMRDYPi7fjhgB3bA9tBjh7cOyuU/c4M4D6o2mAVYdLAWMBkSoLG8Oel6TCcfpO/nElw== github-example-key
The format of the key is simply ssh-rsa <signature> <comment>
and can be created by rearranging the SSH-2 formatted file.
If you are making use of ssh-agent
, you will likely also have access to ssh-keygen
.
If you have your OpenSSH Private Key (id_rsa
file), you can generate the OpenSSH Public Key File using:
ssh-keygen -f ~/.ssh/id_rsa -y > ~/.ssh/id_rsa.pub
If you only have the PUTTY Private Key (id_rsa.ppk
file), you will need to convert it first.
id_rsa.ppk
fileid_rsa
(without an extension)Now that you have an OpenSSH Private Key, you can use the ssh-keygen
tool as above to perform manipulations on the key.
To be honest, I don't know what this key is used for as I haven't needed it. But I have it in my notes I've collated over the years and I'll include it here for wholesome goodness. The file will look like this:
-----BEGIN RSA PUBLIC KEY-----
MIIBCAKCAQEAhl/CNy9wI1GVdiHAJQV0CkHnMEqW7+Si9WYFi2fSBrsGcmqeb5Ew
gnhmTcPgtM5ptGBjUZR84nxjZ8SPmnLDiDyHDPIsmwLBHxcppY0fhRSGtWL5fT8D
Gm9EfXaO1QN8c31VU/IkD8niWA6NmHNE1qEqpph3DznVzIm3oMrongEjGw7sDP48
ZTZp2saYVAKEEuGC1YYcQ1g20yESzo7aP70ZeHmQqI9nTyEAip3mL20+qHNsHfW8
hJAchaUN8CwNQABJaOozYijiIUgdbtSTMRDYPi7fjhgB3bA9tBjh7cOyuU/c4M4D
6o2mAVYdLAWMBkSoLG8Oel6TCcfpO/nElwIBJQ==
-----END RSA PUBLIC KEY-----
This file can be generated using an OpenSSH Private Key (as generated in "Regenerating Public Keys" above) using:
ssh-keygen -f ~/.ssh/id_rsa -y -e -m pem > ~/.ssh/id_rsa.pem
Alternatively, you can use an OpenSSH Public Key using:
ssh-keygen -f ~/.ssh/id_rsa.pub -e -m pem > ~/.ssh/id_rsa.pem
CSS, HTML:
div.mydiv {width: 200px; margin: 0 auto}
_x000D_
<div class="mydiv">_x000D_
_x000D_
I am in the middle_x000D_
_x000D_
</div>
_x000D_
Your diagram shows a block level element also (which a div usually is), not an inline one.
Of the top of my head, min-width
is supported in FF2+/Safari3+/IE7+. Can be done for IE6 using hackety CSS, or a simple bit of JS.
Quick answer
On src, you can always specify files to ignore using "!".
Example (you want to exclude all *.min.js files on your js folder and subfolder:
gulp.src(['js/**/*.js', '!js/**/*.min.js'])
You can do it as well for individual files.
Expanded answer:
Extracted from gulp documentation:
gulp.src(globs[, options])
Emits files matching provided glob or an array of globs. Returns a stream of Vinyl files that can be piped to plugins.
glob refers to node-glob syntax or it can be a direct file path.
So, looking to node-glob documentation we can see that it uses the minimatch library to do its matching.
On minimatch documentation, they point out the following:
if the pattern starts with a ! character, then it is negated.
And that is why using ! symbol will exclude files / directories from a gulp task
This topic is well covered but I still would like to propose another approach in a slightly different philosophy.
It is a bit more complex to set-up but it allow (in my opinion) a bit more flexibility. For example, one can play with the respective ratios of each subplots / colorbar:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.gridspec import GridSpec
# Define number of rows and columns you want in your figure
nrow = 2
ncol = 3
# Make a new figure
fig = plt.figure(constrained_layout=True)
# Design your figure properties
widths = [3,4,5,1]
gs = GridSpec(nrow, ncol + 1, figure=fig, width_ratios=widths)
# Fill your figure with desired plots
axes = []
for i in range(nrow):
for j in range(ncol):
axes.append(fig.add_subplot(gs[i, j]))
im = axes[-1].pcolormesh(np.random.random((10,10)))
# Shared colorbar
axes.append(fig.add_subplot(gs[:, ncol]))
fig.colorbar(im, cax=axes[-1])
plt.show()
The easiest way would be to create a new (simple) Maven project using the "new project" wizard. You can then migrate your source into the Maven folder structure + the auto generated POM file.
Have you seen this question and its answer?
You can set a globally valid value for you app like this:
app.value('key', 'value');
and then use it in your services. You could move this code to a config.js file and execute it on page load or another convenient moment.
I know this question is a bit old, but I'd use a jQuery template and a $.ajax call:
ASPX:
<select id="mySelect" name="mySelect>
<option value="0">-select-</option>
</select>
<script id="mySelectTemplate" type="text/x-jquery-tmpl">
<option value="${CityId}">${CityName}</option>
</script>
JS:
$.ajax({
url: location.pathname + '/GetCities',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
$('#mySelectTemplate').tmpl(response.d).appendTo('#mySelect');
}
});
In addition to the above you'll need a web method (GetCities) that returns a list of objects that include the data elements you're using in your template. I often use Entity Framework and my web method will call a manager class that is getting values from the database using linq. By doing that you can have your input save to the database and refreshing your select list is as simple as calling the databind in JS in the success of your save.
Variable definitions are meant to be used in tasks. But if you want to include them in tasks probably use the register
directive. Like this:
- name: Define variable in task.
shell: echo "http://www.my.url.com"
register: url
- name: Download apache
shell: wget {{ item }}
with_items: url.stdout
You can also look at roles as a way of separating tasks depending on the different roles roles. This way you can have separate variables for each of one of your roles. For example you may have a url
variable for apache1
and a separate url
variable for the role apache2
.
Use this code in your button action (Swift 3.0.1):
let vc = self.storyboard?.instantiateViewController(
withIdentifier: "YourSecondVCIdentifier") as! SecondVC
navigationController?.pushViewController(vc, animated: true)
either
bin\Iris.exe
(no leading slash - because that means start right from the root)
or \Program\bin\Iris.exe
(full path)
I have handled this as below:
try {
response = restTemplate.postForEntity(requestUrl, new HttpEntity<>(requestBody, headers), String.class);
} catch (HttpStatusCodeException ex) {
response = new ResponseEntity<String>(ex.getResponseBodyAsString(), ex.getResponseHeaders(), ex.getStatusCode());
}
Your question is based on a false premise.
Arrays are not a primitive type in Java, but they are not objects either ... "
In fact, all arrays in Java are objects1. Every Java array type has java.lang.Object
as its supertype, and inherits the implementation of all methods in the Object
API.
... so are they passed by value or by reference? Does it depend on what the array contains, for example references or a primitive type?
Short answers: 1) pass by value, and 2) it makes no difference.
Longer answer:
Like all Java objects, arrays are passed by value ... but the value is the reference to the array. So, when you assign something to a cell of the array in the called method, you will be assigning to the same array object that the caller sees.
This is NOT pass-by-reference. Real pass-by-reference involves passing the address of a variable. With real pass-by-reference, the called method can assign to its local variable, and this causes the variable in the caller to be updated.
But not in Java. In Java, the called method can update the contents of the array, and it can update its copy of the array reference, but it can't update the variable in the caller that holds the caller's array reference. Hence ... what Java is providing is NOT pass-by-reference.
Here are some links that explain the difference between pass-by-reference and pass-by-value. If you don't understand my explanations above, or if you feel inclined to disagree with the terminology, you should read them.
Related SO question:
Historical background:
The phrase "pass-by-reference" was originally "call-by-reference", and it was used to distinguish the argument passing semantics of FORTRAN (call-by-reference) from those of ALGOL-60 (call-by-value and call-by-name).
In call-by-value, the argument expression is evaluated to a value, and that value is copied to the called method.
In call-by-reference, the argument expression is partially evaluated to an "lvalue" (i.e. the address of a variable or array element) that is passed to the calling method. The calling method can then directly read and update the variable / element.
In call-by-name, the actual argument expression is passed to the calling method (!!) which can evaluate it multiple times (!!!). This was complicated to implement, and could be used (abused) to write code that was very difficult to understand. Call-by-name was only ever used in Algol-60 (thankfully!).
UPDATE
Actually, Algol-60's call-by-name is similar to passing lambda expressions as parameters. The wrinkle is that these not-exactly-lambda-expressions (they were referred to as "thunks" at the implementation level) can indirectly modify the state of variables that are in scope in the calling procedure / function. That is part of what made them so hard to understand. (See the Wikipedia page on Jensen's Device for example.)
1. Nothing in the linked Q&A (Arrays in Java and how they are stored in memory) either states or implies that arrays are not objects.
You can also produce array by using file:
$array = file('/path/to/text.txt');
I think this covers just about all of the browsers. I have used it successfully in the past.
#div {
filter: alpha(opacity=50); /* internet explorer */
-khtml-opacity: 0.5; /* khtml, old safari */
-moz-opacity: 0.5; /* mozilla, netscape */
opacity: 0.5; /* fx, safari, opera */
}
One use case for optimistic locking is to have your application use the database to allow one of your threads / hosts to 'claim' a task. This is a technique that has come in handy for me on a regular basis.
The best example I can think of is for a task queue implemented using a database, with multiple threads claiming tasks concurrently. If a task has status 'Available', 'Claimed', 'Completed', a db query can say something like "Set status='Claimed' where status='Available'. If multiple threads try to change the status in this way, all but the first thread will fail because of dirty data.
Note that this is a use case involving only optimistic locking. So as an alternative to saying "Optimistic locking is used when you don't expect many collisions", it can also be used where you expect collisions but want exactly one transaction to succeed.
Elements that are not being rendered (be it through visibility: hidden
, display: none
, opacity: 0.0
, whatever) will not indicate focus. The browser will not draw a focus border around nothing.
If you want the text to be focusable, that's completely doable. You can wrap the whole thing in an element that can receive focus (for example, a hyperlink), or allow another tag to have focus using the tabindex
property:
<label tabindex="0" class="checkbox">
<input type="checkbox" value="valueofcheckbox" style="display:none" checked="checked" />Option Text
</label>
In this case, the <label>
tag above is actually receiving focus and everything within it will have a focus border when it's in focus.
I do question what your goal is. If you're using a hidden checkbox to internally track some sort of state, you might be better off using a <input type="hidden" />
tag instead.
http://www.viemu.com/a_vi_vim_graphical_cheat_sheet_tutorial.html
This is the greatest thing ever for learning VIM.
You should do a one-time setup of creating an "App password" in Bitbucket web UI with permissions to at least read your repositories and then use it in the command line.
How-to:
Use java.util.Calendar
if you have extensive date related processing.
Date has before()
, after()
methods. you could use them as well.
I had a similar problem, when I wanted to create a command, \dx
, to abbreviate \;\mathrm{d}x
(i.e. put an extra space before the differential of the integral and have the "d" upright as well). But then I also wanted to make it flexible enough to include the variable of integration as an optional argument. I put the following code in the preamble.
\usepackage{ifthen}
\newcommand{\dx}[1][]{%
\ifthenelse{ \equal{#1}{} }
{\ensuremath{\;\mathrm{d}x}}
{\ensuremath{\;\mathrm{d}#1}}
}
Then
\begin{document}
$$\int x\dx$$
$$\int t\dx[t]$$
\end{document}
Old Q, but for posterity...it also also happens (.NET Core 2.1) if you have a self-referencing navigation property ("Parent" or "Children" of the same type) but the Id property name isn't what EF expects. That is, I had an "Id" property on my class called WorkflowBase
, and it had an array of related child steps, which were also of type WorkflowBase
, and it kept trying to associate them with a non-existent "WorkflowBaseId" (the name i suppose it prefers as a natural/conventional default). I had to explicitly configure it using HasMany()
, WithOne()
, and HasConstraintName()
to tell it how to traverse. But I spent a few hours thinking the problem was in 'locally' mapping the object's primary key, which i attempted to fix a bunch of different ways but which was probably always working.
I wonder why "amend" is not suggest and have been crossed out by @damkrat, as amend appears to me as just the right way to resolve the most efficiently the underlying problem of fixing the wrong commit since there is no purpose of having no initial commit. As some stressed out you should only modify "public" branch like master if no one has clone your repo...
git add <your different stuff>
git commit --amend --author="author name <[email protected]>"-m "new message"
If you have trouble with caching ajax you can turn it off:
$.ajaxSetup({cache: false});
To call a function inside a same controller in any laravel version follow as bellow
$role = $this->sendRequest('parameter');
// sendRequest is a public function
IN SWIFT 3. Here are the NSURLErrorDomain error codes description in a Swift 3 enum: (copied from answer above and converted what i can).
enum NSURLError: Int {
case unknown = -1
case cancelled = -999
case badURL = -1000
case timedOut = -1001
case unsupportedURL = -1002
case cannotFindHost = -1003
case cannotConnectToHost = -1004
case connectionLost = -1005
case lookupFailed = -1006
case HTTPTooManyRedirects = -1007
case resourceUnavailable = -1008
case notConnectedToInternet = -1009
case redirectToNonExistentLocation = -1010
case badServerResponse = -1011
case userCancelledAuthentication = -1012
case userAuthenticationRequired = -1013
case zeroByteResource = -1014
case cannotDecodeRawData = -1015
case cannotDecodeContentData = -1016
case cannotParseResponse = -1017
//case NSURLErrorAppTransportSecurityRequiresSecureConnection NS_ENUM_AVAILABLE(10_11, 9_0) = -1022
case fileDoesNotExist = -1100
case fileIsDirectory = -1101
case noPermissionsToReadFile = -1102
//case NSURLErrorDataLengthExceedsMaximum NS_ENUM_AVAILABLE(10_5, 2_0) = -1103
// SSL errors
case secureConnectionFailed = -1200
case serverCertificateHasBadDate = -1201
case serverCertificateUntrusted = -1202
case serverCertificateHasUnknownRoot = -1203
case serverCertificateNotYetValid = -1204
case clientCertificateRejected = -1205
case clientCertificateRequired = -1206
case cannotLoadFromNetwork = -2000
// Download and file I/O errors
case cannotCreateFile = -3000
case cannotOpenFile = -3001
case cannotCloseFile = -3002
case cannotWriteToFile = -3003
case cannotRemoveFile = -3004
case cannotMoveFile = -3005
case downloadDecodingFailedMidStream = -3006
case downloadDecodingFailedToComplete = -3007
/*
case NSURLErrorInternationalRoamingOff NS_ENUM_AVAILABLE(10_7, 3_0) = -1018
case NSURLErrorCallIsActive NS_ENUM_AVAILABLE(10_7, 3_0) = -1019
case NSURLErrorDataNotAllowed NS_ENUM_AVAILABLE(10_7, 3_0) = -1020
case NSURLErrorRequestBodyStreamExhausted NS_ENUM_AVAILABLE(10_7, 3_0) = -1021
case NSURLErrorBackgroundSessionRequiresSharedContainer NS_ENUM_AVAILABLE(10_10, 8_0) = -995
case NSURLErrorBackgroundSessionInUseByAnotherProcess NS_ENUM_AVAILABLE(10_10, 8_0) = -996
case NSURLErrorBackgroundSessionWasDisconnected NS_ENUM_AVAILABLE(10_10, 8_0)= -997
*/
}
Direct link to URLError.Code
in the Swift github repository, which contains the up to date list of error codes being used (github link).
Maybe I'm late, but this helped me accept SDK licenses for OSX,
If you have android SDK tools installed, run the following command
~/Library/Android/sdk/tools/bin/sdkmanager --licenses
Accept all licenses by pressing y
Voila! You have accepted SDK licenses and are good to go..
Using lxml:
from lxml import etree
# create XML
root = etree.Element('root')
root.append(etree.Element('child'))
# another child with text
child = etree.Element('child')
child.text = 'some text'
root.append(child)
# pretty string
s = etree.tostring(root, pretty_print=True)
print s
Output:
<root>
<child/>
<child>some text</child>
</root>
See the tutorial for more information.
appHelper.validateDates = function (start, end) {
var returnval = false;
var fd = new Date(start);
var fdms = fd.getTime();
var ed = new Date(end);
var edms = ed.getTime();
var cd = new Date();
var cdms = cd.getTime();
if (fdms >= edms) {
returnval = false;
console.log("step 1");
}
else if (cdms >= edms) {
returnval = false;
console.log("step 2");
}
else {
returnval = true;
console.log("step 3");
}
console.log("vall", returnval)
return returnval;
}
A .NET Core version for replacing a defined set of string chars to a specific char. It leverages the recently introduced Span
type and string.Create
method.
The idea is to prepare a replacement array, so no actual comparison operations would be required for the each string char. Thus, the replacement process reminds the way a state machine works. In order to avoid initialization of all items of the replacement array, let's store oldChar ^ newChar
(XOR'ed) values there, what gives the following benefits:
ch ^ ch = 0
- no need to initialize non-changing itemsch ^ repl[ch]
:
ch ^ 0 = ch
- not changed chars casech ^ (ch ^ newChar) = newChar
- replaced charSo the only requirement would be to ensure that the replacement array is zero-ed when initialized. We'll be using ArrayPool<char>
to avoid allocations each time the ReplaceAll
method is called. And, in order to ensure that the arrays are zero-ed without expensive call to Array.Clear
method, we'll be maintaining a pool dedicated for the ReplaceAll
method. We'll be clearing the replacement array (exact items only) before returning it to the pool.
public static class StringExtensions
{
private static readonly ArrayPool<char> _replacementPool = ArrayPool<char>.Create();
public static string ReplaceAll(this string str, char newChar, params char[] oldChars)
{
// If nothing to do, return the original string.
if (string.IsNullOrEmpty(str) ||
oldChars is null ||
oldChars.Length == 0)
{
return str;
}
// If only one character needs to be replaced,
// use the more efficient `string.Replace`.
if (oldChars.Length == 1)
{
return str.Replace(oldChars[0], newChar);
}
// Get a replacement array from the pool.
var replacements = _replacementPool.Rent(char.MaxValue + 1);
try
{
// Intialize the replacement array in the way that
// all elements represent `oldChar ^ newChar`.
foreach (var oldCh in oldChars)
{
replacements[oldCh] = (char)(newChar ^ oldCh);
}
// Create a string with replaced characters.
return string.Create(str.Length, (str, replacements), (dst, args) =>
{
var repl = args.replacements;
foreach (var ch in args.str)
{
dst[0] = (char)(repl[ch] ^ ch);
dst = dst.Slice(1);
}
});
}
finally
{
// Clear the replacement array.
foreach (var oldCh in oldChars)
{
replacements[oldCh] = char.MinValue;
}
// Return the replacement array back to the pool.
_replacementPool.Return(replacements);
}
}
}
EAGER
loading of collections means that they are fetched fully at the time their parent is fetched. So if you have Course
and it has List<Student>
, all the students are fetched from the database at the time the Course
is fetched.
LAZY
on the other hand means that the contents of the List
are fetched only when you try to access them. For example, by calling course.getStudents().iterator()
. Calling any access method on the List
will initiate a call to the database to retrieve the elements. This is implemented by creating a Proxy around the List
(or Set
). So for your lazy collections, the concrete types are not ArrayList
and HashSet
, but PersistentSet
and PersistentList
(or PersistentBag
)
I got the same problem and this is how i solved. :
"How to attach url link to an image?"
You do it like this:
<a href="http://www.google.com"><img src="http://www.google.com/intl/en_ALL/images/logo.gif"/></a>
See it in action.
here follows my 2 cents. You can also use native queries, like:
@Modifying
@Query(value="delete from rreo r where r.cod_ibge = ?1 and r.exercicio= ?2", nativeQuery = true)
void deleteByParameters(Integer codIbge, Integer exercicio);
Not sure if this is more concise, but this function will also find and allow replacement of NAs (or any value you like) in selected columns of a data.table:
update.mat <- function(dt, cols, criteria) {
require(data.table)
x <- as.data.frame(which(criteria==TRUE, arr.ind = TRUE))
y <- as.matrix(subset(x, x$col %in% which((names(dt) %in% cols), arr.ind = TRUE)))
y
}
To apply it:
y[update.mat(y, c("a", "b"), is.na(y))] <- 0
The function creates a matrix of the selected columns and rows (cell coordinates) that meet the input criteria (in this case is.na == TRUE).
You may try removing the table from the model and adding it again. You can do this visually by opening the .edmx file from the Solution Explorer.
Steps:
Create a git clone of that includes your Subversion trunk, tags, and branches with
git svn clone http://svn.example.com/project -T trunk -b branches -t tags
The --stdlayout
option is a nice shortcut if your Subversion repository uses the typical structure:
git svn clone http://svn.example.com/project --stdlayout
Make your git repository ignore everything the subversion repo does:
git svn show-ignore >> .git/info/exclude
You should now be able to see all the Subversion branches on the git side:
git branch -r
Say the name of the branch in Subversion is waldo
. On the git side, you'd run
git checkout -b waldo-svn remotes/waldo
The -svn suffix is to avoid warnings of the form
warning: refname 'waldo' is ambiguous.
To update the git branch waldo-svn
, run
git checkout waldo-svn git svn rebase
To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config
to contain
[svn-remote "svn-mybranch"] url = http://svn.example.com/project/branches/mybranch fetch = :refs/remotes/mybranch
You'll need to develop the habit of running
git svn fetch --fetch-all
to update all of what git svn
thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run
git checkout -b mybranch-svn remotes/mybranch
For the branches from which you intend to git svn dcommit
, keep their histories linear!
You may also be interested in reading an answer to a related question.
To describe model I use following snippet
Model.columns.collect { |c| "#{c.name} (#{c.type})" }
Again this is if you are looking pretty print to describe you ActiveRecord
without you going trough migrations or hopping that developer before you was nice enough to comment in attributes.
Rather than using a proxy, I'm using the Firefox plugin "Modify Headers" to insert headers (in my case, to fake a login using the Single Sign On so I can test as different people).
After wasting an hour on complex and hacky solutions, I've found both simple and valid solution for commenting my bulky dependencies section in package.json
. Just like this:
{
"name": "package name",
"version": "1.0",
"description": "package description",
"scripts": {
"start": "npm install && node server.js"
},
"scriptsComments": {
"start": "Runs development build on a local server configured by server.js"
},
"dependencies": {
"ajv": "^5.2.2"
},
"dependenciesComments": {
"ajv": "JSON-Schema Validator for validation of API data"
}
}
When sorted the same way, it's now very easy for me to track these pairs of dependencies/comments either in Git commit diffs or in an editor while working with file package.json
.
And no extra tools are involved, just plain and valid JSON.
Try Eclipse PDT to setup an Eclipse environment that has debugging features like you mentioned. The ability to step into the code is a much better way to debug then the old method of var_dump and print at various points to see where your flow goes wrong. When all else fails though and all I have is SSH and vim I still var_dump()
/die()
to find where the code goes south.
Just for the record, you can filter on data with jquery (this question is quite old, and jQuery evolved since then, so it's right to write this solution as well):
$('.navlink[data-selected="true"]');
or, better (for performance):
$('.navlink').filter('[data-selected="true"]');
or, if you want to get all the elements with data-selected
set:
$('[data-selected]')
Note that this method will only work with data that was set via html-attributes. If you set or change data with the .data()
call, this method will no longer work.
It's quite possible to do this in JavaScript as long as your fallback is another applink. Building on Nathan's suggestion:
<html>
<head>
<meta name="viewport" content="width=device-width" />
</head>
<body>
<h2><a id="applink1" href="fb://profile/116201417">open facebook with fallback to appstore</a></h2>
<h2><a id="applink2" href="unknown://nowhere">open unknown with fallback to appstore</a></h2>
<p><i>Only works on iPhone!</i></p>
<script type="text/javascript">
// To avoid the "protocol not supported" alert, fail must open another app.
var appstorefail = "itms://itunes.apple.com/us/app/facebook/id284882215?mt=8&uo=6";
function applink(fail){
return function(){
var clickedAt = +new Date;
// During tests on 3g/3gs this timeout fires immediately if less than 500ms.
setTimeout(function(){
// To avoid failing on return to MobileSafari, ensure freshness!
if (+new Date - clickedAt < 2000){
window.location = fail;
}
}, 500);
};
}
document.getElementById("applink1").onclick = applink(appstorefail);
document.getElementById("applink2").onclick = applink(appstorefail);
</script>
</body>
</html>
Each app.use(middleware) is called every time a request is sent to the server.
Here's a utility class I use to convert the newer java.time
classes to java.util.Date
objects and vice versa:
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public class DateUtils {
public static Date asDate(LocalDate localDate) {
return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
}
public static Date asDate(LocalDateTime localDateTime) {
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
public static LocalDate asLocalDate(Date date) {
return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
}
public static LocalDateTime asLocalDateTime(Date date) {
return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
}
}
Edited based on @Oliv comment.
I got this error using Maven, and I discovered the solution.
Error: Could not find or load main class com.mycompany.testapifactory.Main
I'm using java JDK version 1.7 on Linux, my pom.xml
file was the default generated by Netbeans and I was using these commands to compile, which do work fine with a normal hello-world java application:
mvn clean compile
java -jar target/TestAPIFactory-1.0-SNAPSHOT.jar com.mycompany.testapifactory.Main
What happened:
It turns out my problem was that my Main method was extending something Exotic like this:
public class Main extends SomeExoticLibraryClass{
public static void main(String[] args){
//...
}
}
It was this extending of the main class that caused the above error.
TLDR solution:
Make sure your main class isn't extending any 3rd party classes. Refactor those out and away into their own classes. That error message is awful, and requires process of elimination to find out what to do.
comdlg32.dll is not really a COM dll (you can't register it).
What you need is comdlg32.ocx which contains the MSComDlg.CommonDialog COM class (and indeed relies on comdlg32.dll to work). Once you get ahold on a comdlg32.ocx, then you will be able to do regsvr32 comdlg32.ocx
.
Powershell Solution:
If you're running windows, you can use PowerShell to remove multiple branches at once...
git branch -D ((git branch | Select-String -Pattern '^\s*3\.2\..*') | foreach{$_.ToString().Trim()})
//this will remove all branches starting with 3.2.
git branch -D ((git branch | Select-String -Pattern 'feature-*') | foreach{$_.ToString().Trim()})
// this will delete all branches that contains the word "feature-" as a substring.
You can also fine tune how the pattern matching should work using Powershell's Select-String command. Take a look at powershell docs.
Using typescript, I use a custom interface that only applies to my function. Example use case.
handleChange(event: { target: HTMLInputElement; }) {
this.setState({ value: event.target.value });
}
In this case, the handleChange will receive an object with target field that is of type HTMLInputElement.
Later in my code I can use
<input type='text' value={this.state.value} onChange={this.handleChange} />
A cleaner approach would be to put the interface to a separate file.
interface HandleNameChangeInterface {
target: HTMLInputElement;
}
then later use the following function definition:
handleChange(event: HandleNameChangeInterface) {
this.setState({ value: event.target.value });
}
In my usecase, it's expressly defined that the only caller to handleChange is an HTML element type of input text.
I had the same problem on Windows. I used to read the file in scala line by line with
Source.fromFile(path).getLines()
Now I read it as a whole with
import org.apache.commons.io.FileUtils._
// encoding is null for platform default
val content=readFileToString(new File(path),null.asInstanceOf[String])
which closes the file properly after reading and now
new File(path).delete
works.
I found that the best way it to add always the +trace option:
dig SOA +trace stackoverflow.com
It works also with recursive CNAME hosted in different provider. +trace trace imply +norecurse so the result is just for the domain you specify.
i also appear this problem,and my code below
storeFile file(properties.getProperty("filepath"))
storePassword properties.getProperty("keypassword")
keyAlias properties.getProperty("keyAlias")
keyPassword properties.getProperty("keypassword")
the reason is property name error,it should be keyPassword not keypassword
For purely html @isherwood has a great solution. For jQuery, give your select drop down an ID then select it with jQuery:
<form>
<select id="myDropDown">
<option value="0">aaaa</option>
<option value="1">bbbb</option>
</select>
</form>
Then use this jQuery to clear the drop down on page load:
$(document).ready(function() {
$('#myDropDown').val('');
});
Or put it inside a function by itself:
$('#myDropDown').val('');
accomplishes what you're looking for and it is easy to put this in functions that may get called on your page if you need to blank out the drop down without reloading the page.
Use top
or htop
and pay attention to the "RES" (resident memory size) column.
Rename the solution's corresponding .SUO file. The SUO file contains the TFS status (online/offline), amongst a host of other goodies.
Do this only if the "right-click on the solution name right at the top of the Solution Explorer and select the Go Online option" fails (because e.g. you installed VS2015 preview).
Don't know if this will work for the situation given in the original post (never mind the fact that this is two years later), but this example works for me:
Hashtable htImageTypes = new Hashtable();
htImageTypes.Add("JPEG", "*.jpg");
htImageTypes.Add("GIF", "*.gif");
htImageTypes.Add("BMP", "*.bmp");
foreach (DictionaryEntry ImageType in htImageTypes)
{
cmbImageType.Items.Add(ImageType);
}
cmbImageType.DisplayMember = "key";
cmbImageType.ValueMember = "value";
To read your value back out, you'll have to cast the SelectedItem property to a DictionaryEntry object, and you can then evaluate the Key and Value properties of that. For instance:
DictionaryEntry deImgType = (DictionaryEntry)cmbImageType.SelectedItem;
MessageBox.Show(deImgType.Key + ": " + deImgType.Value);
Normal Class
: A Java class
Java Beans
:
Pojo
:
Plain Old Java Object is a Java object not bound by any restriction other than those forced by the Java Language Specification. I.e., a POJO should not have to
This seems to work for me.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DropDownList1.DataBind(); // get the data into the list you can set it
DropDownList1.Items.FindByValue("SOMECREDITPROBLEMS").Selected = true;
}
}
.length
is a one-off property of Java. It's used to find the size of a single dimensional array.
.length()
is a method. It's used to find the length of a String
. It avoids duplicating the value.
I had this problem when installing Heroku Toolbelt
This is how I solved the problem
$ ls -l /bin/sh
lrwxrwxrwx 1 root root 4 ago 15 2012 /bin/sh -> dash
As you can see, /bin/sh is a link to "dash" (not bash), and [[
is bash syntactic sugarness. So I just replaced the link to /bin/bash. Careful using rm like this in your system!
$ sudo rm /bin/sh
$ sudo ln -s /bin/bash /bin/sh
JPanel testPanel = new JPanel();
testPanel.setLayout(new BoxLayout(testPanel, BoxLayout.Y_AXIS));
/*add variables here and add them to testPanel
e,g`enter code here`
testPanel.add(nameLabel);
testPanel.add(textName);
*/
testPanel.setVisible(true);
It appears the default setting for Adobe Reader X is for the toolbars not to be shown by default unless they are explicitly turned on by the user. And even when I turn them back on during a session, they don't show up automatically next time. As such, I suspect you have a preference set contrary to the default.
The state you desire, with the top and left toolbars not shown, is called "Read Mode". If you right-click on the document itself, and then click "Page Display Preferences" in the context menu that is shown, you'll be presented with the Adobe Reader Preferences dialog. (This is the same dialog you can access by opening the Adobe Reader application, and selecting "Preferences" from the "Edit" menu.) In the list shown in the left-hand column of the Preferences dialog, select "Internet". Finally, on the right, ensure that you have the "Display in Read Mode by default" box checked:
You can also turn off the toolbars temporarily by clicking the button at the right of the top toolbar that depicts arrows pointing to opposing corners:
Finally, if you have "Display in Read Mode by default" turned off, but want to instruct the page you're loading not to display the toolbars (i.e., override the user's current preferences), you can append the following to the URL:
#toolbar=0&navpanes=0
So, for example, the following code will disable both the top toolbar (called "toolbar") and the left-hand toolbar (called "navpane"). However, if the user knows the keyboard combination (F8, and perhaps other methods as well), they will still be able to turn them back on.
string url = @"http://www.domain.com/file.pdf#toolbar=0&navpanes=0";
this._WebBrowser.Navigate(url);
You can read more about the parameters that are available for customizing the way PDF files open here on Adobe's developer website.
NOTE if you're using PostgreSQL 9.1 or later, and you are ok with making changes outside of a transaction, see this answer for a simpler approach.
I had the same problem few days ago and found this post. So my answer can be helpful for someone who is looking for solution :)
If you have only one or two columns which use the enum type you want to change, you can try this. Also you can change the order of values in the new type.
-- 1. rename the enum type you want to change
alter type some_enum_type rename to _some_enum_type;
-- 2. create new type
create type some_enum_type as enum ('old', 'values', 'and', 'new', 'ones');
-- 3. rename column(s) which uses our enum type
alter table some_table rename column some_column to _some_column;
-- 4. add new column of new type
alter table some_table add some_column some_enum_type not null default 'new';
-- 5. copy values to the new column
update some_table set some_column = _some_column::text::some_enum_type;
-- 6. remove old column and type
alter table some_table drop column _some_column;
drop type _some_enum_type;
3-6 should be repeated if there is more than 1 column.
What you want cannot be done, because plt.legend()
places a legend in the current axes, in your case in the last one.
If, on the other hand, you can be content with placing a comprehensive legend in the last subplot, you can do like this
f, (ax1, ax2, ax3) = plt.subplots(3, sharex=True, sharey=True)
l1,=ax1.plot(x,y, color='r', label='Blue stars')
l2,=ax2.plot(x,y, color='g')
l3,=ax3.plot(x,y, color='b')
ax1.set_title('2012/09/15')
plt.legend([l1, l2, l3],["HHZ 1", "HHN", "HHE"])
plt.show()
Note that you pass to legend
not the axes, as in your example code, but the lines as returned by the plot
invocation.
Of course you can invoke legend
after each subplot, but in my understanding you already knew that and were searching for a method for doing it at once.
Here is a solution that also makes it easy to show a loading view in the end of the ListView while it's loading.
You can see the classes here:
https://github.com/CyberEagle/OpenProjects/blob/master/android-projects/widgets/src/main/java/br/com/cybereagle/androidwidgets/helper/ListViewWithLoadingIndicatorHelper.java - Helper to make it possible to use the features without extending from SimpleListViewWithLoadingIndicator.
https://github.com/CyberEagle/OpenProjects/blob/master/android-projects/widgets/src/main/java/br/com/cybereagle/androidwidgets/listener/EndlessScrollListener.java - Listener that starts loading data when the user is about to reach the bottom of the ListView.
https://github.com/CyberEagle/OpenProjects/blob/master/android-projects/widgets/src/main/java/br/com/cybereagle/androidwidgets/view/SimpleListViewWithLoadingIndicator.java - The EndlessListView. You can use this class directly or extend from it.
You can use the below method to store the timestamp in database specific to your desired zone/zone Id.
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Asia/Calcutta")) ;
Timestamp timestamp = Timestamp.valueOf(zdt.toLocalDateTime());
A common mistake people do is use LocaleDateTime
to get the timestamp of that instant which discards any information specif to your zone even if you try to convert it later. It does not understand the Zone.
Please note Timestamp
is of the class java.sql.Timestamp
.
Swift 2.0:
Add this method to VC or to Extension of UIColor.
func colorWithHexString (hex:String) -> UIColor {
var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
if (cString.hasPrefix("#")) {
cString = (cString as NSString).substringFromIndex(1)
}
if (cString.characters.count != 6) {
return UIColor.grayColor()
}
let rString = (cString as NSString).substringToIndex(2)
let gString = ((cString as NSString).substringFromIndex(2) as NSString).substringToIndex(2)
let bString = ((cString as NSString).substringFromIndex(4) as NSString).substringToIndex(2)
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
NSScanner(string: rString).scanHexInt(&r)
NSScanner(string: gString).scanHexInt(&g)
NSScanner(string: bString).scanHexInt(&b)
return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
}
Usage :
loginButton.tintColor = self.colorWithHexString("#be1337")
OR
let hexColor = self.colorWithHexString("#be1337")
Complementing a few points to many of the previous answers:
Code coverage means, how well your test set is covering your source code. i.e. to what extent is the source code covered by the set of test cases.
As mentioned in above answers, there are various coverage criteria, like paths, conditions, functions, statements, etc. But additional criteria to be covered are
Note: Static code analysis will find if there are any unreachable code or hanging code, i.e. code not covered by any other function call. And also other static coverage. Even if static code analysis reports that 100% code is covered, it does not give reports about your testing set if all possible code coverage is tested.
I believe this problem is coming from the .svn file. It's either incorrect in the old parent, the new parent or the old one. I would try reverting back to your starting point. Use an export to get a clean copy of the folder. Move the clean copy to the new location, and use an add and delete to do the move. That's manually doing what SVN does, but it might work.
Go to edit Android Virtual Devices and change the 1024 Under Memory Options to 768. If it still doesn't work, keep going lower and lower.
As of February 2019, the solution given by @sylvain (at least on my setup) does not work without a small modification: xObject[obj]['/Filter']
is not a value, but a list, thus in order to make the script work, I had to modify the format checking as follows:
import PyPDF2, traceback
from PIL import Image
input1 = PyPDF2.PdfFileReader(open(src, "rb"))
nPages = input1.getNumPages()
print nPages
for i in range(nPages) :
print i
page0 = input1.getPage(i)
try :
xObject = page0['/Resources']['/XObject'].getObject()
except : xObject = []
for obj in xObject:
if xObject[obj]['/Subtype'] == '/Image':
size = (xObject[obj]['/Width'], xObject[obj]['/Height'])
data = xObject[obj].getData()
try :
if xObject[obj]['/ColorSpace'] == '/DeviceRGB':
mode = "RGB"
elif xObject[obj]['/ColorSpace'] == '/DeviceCMYK':
mode = "CMYK"
# will cause errors when saving
else:
mode = "P"
fn = 'p%03d-%s' % (i + 1, obj[1:])
print '\t', fn
if '/FlateDecode' in xObject[obj]['/Filter'] :
img = Image.frombytes(mode, size, data)
img.save(fn + ".png")
elif '/DCTDecode' in xObject[obj]['/Filter']:
img = open(fn + ".jpg", "wb")
img.write(data)
img.close()
elif '/JPXDecode' in xObject[obj]['/Filter'] :
img = open(fn + ".jp2", "wb")
img.write(data)
img.close()
elif '/LZWDecode' in xObject[obj]['/Filter'] :
img = open(fn + ".tif", "wb")
img.write(data)
img.close()
else :
print 'Unknown format:', xObject[obj]['/Filter']
except :
traceback.print_exc()
The way to start new activities is to broadcast an intent, and there is a specific kind of intent that you can use to pass data from one activity to another. My recommendation is that you check out the Android developer docs related to intents; it's a wealth of info on the subject, and has examples too.
If it's in a class, you can use getattr:
class MyClass(object):
def install(self):
print "In install"
method_name = 'install' # set by the command line options
my_cls = MyClass()
method = None
try:
method = getattr(my_cls, method_name)
except AttributeError:
raise NotImplementedError("Class `{}` does not implement `{}`".format(my_cls.__class__.__name__, method_name))
method()
or if it's a function:
def install():
print "In install"
method_name = 'install' # set by the command line options
possibles = globals().copy()
possibles.update(locals())
method = possibles.get(method_name)
if not method:
raise NotImplementedError("Method %s not implemented" % method_name)
method()
Also, to note - the Active Record Class also has a $this->db->where_in()
method.
EhCache provides a SizeOf class that will try to use the Instrumentation agent and will fall back to a different approach if the agent is not loaded or cannot be loaded (details here).
Also see the agent from Heinz Kabutz.
std::cout <<
and std::to_string
std::vector
, std::array
and std::tuple
As printing a vector in cpp turned out to be surprisingly much work (at least compared to how basic this task is) and as one steps over the same problem again, when working with other container, here a more general solution ...
This template collection handles 3 container types:
std::vector
, std::array
and std::tuple
.
It defines std::to_string()
for those and makes it possible to directly print them out by std::cout << container;
.
Further it defines the << operator for std::string << container
.
With this it gets possible to construct strings containig these container types in a compact way.
From
std::string s1 = "s1: " + std::to_string(arr) + "; " + std::to_string(vec) + "; " + std::to_string(tup);
we get to
std::string s2 = STR() << "s2: " << arr << "; " << vec << "; " << tup;
You can test this code interactively: here.
#include <iostream>
#include <string>
#include <tuple>
#include <vector>
#include <array>
namespace std
{
// declations: needed for std::to_string(std::vector<std::tuple<int, float>>)
std::string to_string(std::string str);
std::string to_string(const char *str);
template<typename T, size_t N>
std::string to_string(std::array<T, N> const& arr);
template<typename T>
std::string to_string(std::vector<T> const& vec);
template<typename... Args>
std::string to_string(const std::tuple<Args...>& tup);
std::string to_string(std::string str)
{
return std::string(str);
}
std::string to_string(const char *str)
{
return std::string(str);
}
template<typename T, size_t N>
std::string to_string(std::array<T, N> const& arr)
{
std::string s="{";
for (std::size_t t = 0; t != N; ++t)
s += std::to_string(arr[t]) + (t+1 < N ? ", ":"");
return s + "}";
}
template<typename T>
std::string to_string(std::vector<T> const& vec)
{
std::string s="[";
for (std::size_t t = 0; t != vec.size(); ++t)
s += std::to_string(vec[t]) + (t+1 < vec.size() ? ", ":"");
return s + "]";
}
// to_string(tuple)
// https://en.cppreference.com/w/cpp/utility/tuple/operator%3D
template<class Tuple, std::size_t N>
struct TupleString
{
static std::string str(const Tuple& tup)
{
std::string out;
out += TupleString<Tuple, N-1>::str(tup);
out += ", ";
out += std::to_string(std::get<N-1>(tup));
return out;
}
};
template<class Tuple>
struct TupleString<Tuple, 1>
{
static std::string str(const Tuple& tup)
{
std::string out;
out += std::to_string(std::get<0>(tup));
return out;
}
};
template<typename... Args>
std::string to_string(const std::tuple<Args...>& tup)
{
std::string out = "(";
out += TupleString<decltype(tup), sizeof...(Args)>::str(tup);
out += ")";
return out;
}
} // namespace std
/**
* cout: cout << continer
*/
template <typename T, std::size_t N> // cout << array
std::ostream& operator <<(std::ostream &out, std::array<T, N> &con)
{
out << std::to_string(con);
return out;
}
template <typename T, typename A> // cout << vector
std::ostream& operator <<(std::ostream &out, std::vector<T, A> &con)
{
out << std::to_string(con);
return out;
}
template<typename... Args> // cout << tuple
std::ostream& operator <<(std::ostream &out, std::tuple<Args...> &con)
{
out << std::to_string(con);
return out;
}
/**
* Concatenate: string << continer
*/
template <class C>
std::string operator <<(std::string str, C &con)
{
std::string out = str;
out += std::to_string(con);
return out;
}
#define STR() std::string("")
int main()
{
std::array<int, 3> arr {1, 2, 3};
std::string sArr = std::to_string(arr);
std::cout << "std::array" << std::endl;
std::cout << "\ttest to_string: " << sArr << std::endl;
std::cout << "\ttest cout <<: " << arr << std::endl;
std::cout << "\ttest string <<: " << (std::string() << arr) << std::endl;
std::vector<std::string> vec {"a", "b"};
std::string sVec = std::to_string(vec);
std::cout << "std::vector" << std::endl;
std::cout << "\ttest to_string: " << sVec << std::endl;
std::cout << "\ttest cout <<: " << vec << std::endl;
std::cout << "\ttest string <<: " << (std::string() << vec) << std::endl;
std::tuple<int, std::string> tup = std::make_tuple(5, "five");
std::string sTup = std::to_string(tup);
std::cout << "std::tuple" << std::endl;
std::cout << "\ttest to_string: " << sTup << std::endl;
std::cout << "\ttest cout <<: " << tup << std::endl;
std::cout << "\ttest string <<: " << (std::string() << tup) << std::endl;
std::vector<std::tuple<int, float>> vt {std::make_tuple(1, .1), std::make_tuple(2, .2)};
std::string sVt = std::to_string(vt);
std::cout << "std::vector<std::tuple>" << std::endl;
std::cout << "\ttest to_string: " << sVt << std::endl;
std::cout << "\ttest cout <<: " << vt << std::endl;
std::cout << "\ttest string <<: " << (std::string() << vt) << std::endl;
std::cout << std::endl;
std::string s1 = "s1: " + std::to_string(arr) + "; " + std::to_string(vec) + "; " + std::to_string(tup);
std::cout << s1 << std::endl;
std::string s2 = STR() << "s2: " << arr << "; " << vec << "; " << tup;
std::cout << s2 << std::endl;
return 0;
}
std::array
test to_string: {1, 2, 3}
test cout <<: {1, 2, 3}
test string <<: {1, 2, 3}
std::vector
test to_string: [a, b]
test cout <<: [a, b]
test string <<: [a, b]
std::tuple
test to_string: (5, five)
test cout <<: (5, five)
test string <<: (5, five)
std::vector<std::tuple>
test to_string: [(1, 0.100000), (2, 0.200000)]
test cout <<: [(1, 0.100000), (2, 0.200000)]
test string <<: [(1, 0.100000), (2, 0.200000)]
s1: {1, 2, 3}; [a, b]; (5, five)
s2: {1, 2, 3}; [a, b]; (5, five)
For HashMap DEFAULT_INITIAL_CAPACITY = 16 and DEFAULT_LOAD_FACTOR = 0.75f it means that MAX number of ALL Entries in the HashMap = 16 * 0.75 = 12. When the thirteenth element will be added capacity (array size) of HashMap will be doubled! Perfect illustration answered this question: image is taken from here:
https://javabypatel.blogspot.com/2015/10/what-is-load-factor-and-rehashing-in-hashmap.html
If you find any security issue then follow steps as well
Thats DONE!
Such kind of error normally happens when you try using functions like php_info() wrongly.
<?php
php_info(); // 500 error
phpinfo(); // Works correctly
?>
A close look at your code will be better.
sleep()
causes the thread to definitely stop executing for a given amount of time; if no other thread or process needs to be run, the CPU will be idle (and probably enter a power saving mode).
yield()
basically means that the thread is not doing anything particularly important and if any other threads or processes need to be run, they should. Otherwise, the current thread will continue to run.
NOTICE: Command php bin/console generate:doctrine:crud
also create TestController
in src/Tests
so it can throw error when you tried to start server if you don't have UnitTests
. Remove the file fix it!
You may use simplehtmldom. Most of the jQuery selectors are supported in simplehtmldom. An example is given below
// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');
// Find all images
foreach($html->find('img') as $element)
echo $element->src . '<br>';
// Find all links
foreach($html->find('a') as $element)
echo $element->href . '<br>';
There is a simple trick for this. After you constructed the frame with all it buttons do this:
frame.getRootPane().setDefaultButton(submitButton);
For each frame, you can set a default button that will automatically listen to the Enter key (and maybe some other event's I'm not aware of). When you hit enter in that frame, the ActionListeners their actionPerformed()
method will be invoked.
And the problem with your code as far as I see is that your dialog pops up every time you hit a key, because you didn't put it in the if-body. Try changing it to this:
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER){
System.out.println("Hello");
JOptionPane.showMessageDialog(null , "You've Submitted the name " + nameInput.getText());
}
}
UPDATE: I found what is wrong with your code. You are adding the key listener to the Submit button instead of to the TextField. Change your code to this:
SubmitButton listener = new SubmitButton(textBoxToEnterName);
textBoxToEnterName.addActionListener(listener);
submit.addKeyListener(listener);
No need for jQuery and lot's of CSS anymore (Note that some browsers need extra CSS)
Kind of what @Abinthaha posted, but pure JS, without the need of jQuery.
let rotateAngle = 90;_x000D_
_x000D_
function rotate(image) {_x000D_
image.setAttribute("style", "transform: rotate(" + rotateAngle + "deg)");_x000D_
rotateAngle = rotateAngle + 90;_x000D_
}
_x000D_
#rotater {_x000D_
transition: all 0.3s ease;_x000D_
border: 0.0625em solid black;_x000D_
border-radius: 3.75em;_x000D_
}
_x000D_
<img id="rotater" onclick="rotate(this)" src="https://upload.wikimedia.org/wikipedia/en/e/e0/Iron_Man_bleeding_edge.jpg"/>
_x000D_
The lxml library includes a very convenient syntax for XML generation, called the E-factory. Here's how I'd make the example you give:
#!/usr/bin/python
import lxml.etree
import lxml.builder
E = lxml.builder.ElementMaker()
ROOT = E.root
DOC = E.doc
FIELD1 = E.field1
FIELD2 = E.field2
the_doc = ROOT(
DOC(
FIELD1('some value1', name='blah'),
FIELD2('some value2', name='asdfasd'),
)
)
print lxml.etree.tostring(the_doc, pretty_print=True)
Output:
<root>
<doc>
<field1 name="blah">some value1</field1>
<field2 name="asdfasd">some value2</field2>
</doc>
</root>
It also supports adding to an already-made node, e.g. after the above you could say
the_doc.append(FIELD2('another value again', name='hithere'))
I have had to unpack a .ab
-file, too and found this post while looking for an answer. My suggested solution is Android Backup Extractor, a free Java tool for Windows, Linux and Mac OS.
Make sure to take a look at the README, if you encounter a problem. You might have to download further files, if your .ab
-file is password-protected.
Usage:java -jar abe.jar [-debug] [-useenv=yourenv] unpack <backup.ab> <backup.tar> [password]
Example:
Let's say, you've got a file test.ab
, which is not password-protected, you're using Windows and want the resulting .tar
-Archive to be called test.tar
. Then your command should be:
java.exe -jar abe.jar unpack test.ab test.tar ""
u can use this:
protected void btnConfirm_Click(object sender, EventArgs e)
{
Response.Redirect("Confirm.aspx");
}
Just to add a non-regex solution:
'(' + $myString.Split('()')[1] + ')'
This splits the string at the parentheses and takes the string from the array with the program name in it.
If you don't need the parentheses, just use:
$myString.Split('()')[1]
std::unique_ptr has no copy constructor. You create an instance and then ask the std::vector to copy that instance during initialisation.
error: deleted function 'std::unique_ptr<_Tp, _Tp_Deleter>::uniqu
e_ptr(const std::unique_ptr<_Tp, _Tp_Deleter>&) [with _Tp = int, _Tp_D
eleter = std::default_delete<int>, std::unique_ptr<_Tp, _Tp_Deleter> =
std::unique_ptr<int>]'
The class satisfies the requirements of MoveConstructible and MoveAssignable, but not the requirements of either CopyConstructible or CopyAssignable.
The following works with the new emplace calls.
std::vector< std::unique_ptr< int > > vec;
vec.emplace_back( new int( 1984 ) );
See using unique_ptr with standard library containers for further reading.
Try this one dude if you're using windows:
1.) Search environment variables at your start menu's search box.
2.) Click it then go to Environment Variables...
3.) Click PATH, click Edit
4.) Click New and try to copy and paste this: C:\Program Files\nodejs\node_modules\npm\bin
If you got an error. Do the number 4.) Click New, then browse the bin folder
Icon with default bootstrap Style
<div class="input-group">
<input type="text" class="form-control" placeholder="From" aria-label="from" aria-describedby="from">
<div class="input-group-append">
<span class="input-group-text"><i class="fas fa-map-marker-alt"></i></span>
</div>
</div>
Icon Inside Input with default bootstrap class
<div class="input-group">
<input type="text" class="form-control border-right-0" placeholder="From" aria-label="from" aria-describedby="from">
<div class="input-group-append">
<span class="input-group-text bg-transparent"><i class="fas fa-map-marker-alt"></i></span>
</div>
</div>
Icon Inside Input with small custom css
<div class="input-group">
<input type="text" class="form-control rounded-right" placeholder="From" aria-label="from" aria-describedby="from">
<span class="icon-inside"><i class="fas fa-map-marker-alt"></i></span>
</div>
Custom Css
.icon-inside {
position: absolute;
right: 10px;
top: calc(50% - 12px);
pointer-events: none;
font-size: 16px;
font-size: 1.125rem;
color: #c4c3c3;
z-index:3;
}
.icon-inside {_x000D_
position: absolute;_x000D_
right: 10px;_x000D_
top: calc(50% - 12px);_x000D_
pointer-events: none;_x000D_
font-size: 16px;_x000D_
font-size: 1.125rem;_x000D_
color: #c4c3c3;_x000D_
z-index:3;_x000D_
}
_x000D_
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" />_x000D_
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">_x000D_
_x000D_
<div class="container">_x000D_
<h5 class="mt-3">Icon <small>with default bootstrap Style</small><h5>_x000D_
<div class="input-group">_x000D_
<input type="text" class="form-control" placeholder="From" aria-label="from" aria-describedby="from">_x000D_
<div class="input-group-append">_x000D_
<span class="input-group-text"><i class="fas fa-map-marker-alt"></i></span>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<h5 class="mt-3">Icon Inside Input <small>with default bootstrap class</small><h5>_x000D_
<div class="input-group">_x000D_
<input type="text" class="form-control border-right-0" placeholder="From" aria-label="from" aria-describedby="from">_x000D_
<div class="input-group-append">_x000D_
<span class="input-group-text bg-transparent"><i class="fas fa-map-marker-alt"></i></span>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<h5 class="mt-3">Icon Inside Input<small> with small custom css</small><h5>_x000D_
<div class="input-group">_x000D_
<input type="text" class="form-control rounded-right" placeholder="From" aria-label="from" aria-describedby="from">_x000D_
<span class="icon-inside"><i class="fas fa-map-marker-alt"></i></span>_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
Laravel 5 uses bcrypt
. So, you can do this as well.
$hashedpassword = bcrypt('plaintextpassword');
output of which you can save to your database table's password field.
Fn Ref: bcrypt
Alternative using VBA's Filter function
As an innovative alternative to @schlebe 's recent answer, I tried to use the Filter
function integrated in VBA, which allows to filter out a given search string setting the third argument to False. All "negative" search strings (e.g. A, B, C) are defined in an array. I read the criteria in column A to a datafield array and basicly execute a subsequent filtering (A - C) to filter these items out.
Code
Sub FilterOut()
Dim ws As Worksheet
Dim rng As Range, i As Integer, n As Long, v As Variant
' 1) define strings to be filtered out in array
Dim a() ' declare as array
a = Array("A", "B", "C") ' << filter out values
' 2) define your sheetname and range (e.g. criteria in column A)
Set ws = ThisWorkbook.Worksheets("FilterOut")
n = ws.Range("A" & ws.Rows.Count).End(xlUp).row
Set rng = ws.Range("A2:A" & n)
' 3) hide complete range rows temporarily
rng.EntireRow.Hidden = True
' 4) set range to a variant 2-dim datafield array
v = rng
' 5) code array items by appending row numbers
For i = 1 To UBound(v): v(i, 1) = v(i, 1) & "#" & i + 1: Next i
' 6) transform to 1-dim array and FILTER OUT the first search string, e.g. "A"
v = Filter(Application.Transpose(Application.Index(v, 0, 1)), a(0), False, False)
' 7) filter out each subsequent search string, i.e. "B" and "C"
For i = 1 To UBound(a): v = Filter(v, a(i), False, False): Next i
' 8) get coded row numbers via split function and unhide valid rows
For i = LBound(v) To UBound(v)
ws.Range("A" & Split(v(i) & "#", "#")(1)).EntireRow.Hidden = False
Next i
End Sub
Remember you can access good old ECMAScript APIs, in this case, JSON.stringify()
.
For simple arrays like the one in your example:
require('fs').writeFile(
'./my.json',
JSON.stringify(myArray),
function (err) {
if (err) {
console.error('Crap happens');
}
}
);
This is because in line
graph(x**3+2*x-4, range(-10, 11))
x is not defined.
The easiest way is to pass the function you want to plot as a string and use eval
to evaluate it as an expression.
So your code with minimal modifications will be
import numpy as np
import matplotlib.pyplot as plt
def graph(formula, x_range):
x = np.array(x_range)
y = eval(formula)
plt.plot(x, y)
plt.show()
and you can call it as
graph('x**3+2*x-4', range(-10, 11))
I just did git reset --hard
and lost all my uncommitted changes. Luckily, I use an editor (IntelliJ) and I was able to recover the changes from the Local History. Eclipse should allow you to do the same.
System properties are set on the Java command line using the -Dpropertyname=value
syntax. They can also be added at runtime
using System.setProperty(String key, String value)
or via the various
System.getProperties().load()
methods.
To get a specific system property you can use System.getProperty(String key)
or System.getProperty(String key, String def)
.
Environment variables are set in the OS, e.g. in Linux export HOME=/Users/myusername
or on Windows SET WINDIR=C:\Windows
etc,
and, unlike properties, may not be set at runtime.
To get a specific environment variable you can use System.getenv(String name)
.
New way of doing this would be using ShareCompat.IntentBuilder like so:
// Create and fire off our Intent in one fell swoop
ShareCompat.IntentBuilder
// getActivity() or activity field if within Fragment
.from(this)
// The text that will be shared
.setText(textToShare)
// most general text sharing MIME type
.setType("text/plain")
.setStream(uriToContentThatMatchesTheArgumentOfSetType)
/*
* [OPTIONAL] Designate a URI to share. Your type that
* is set above will have to match the type of data
* that your designating with this URI. Not sure
* exactly what happens if you don't do that, but
* let's not find out.
*
* For example, to share an image, you'd do the following:
* File imageFile = ...;
* Uri uriToImage = ...; // Convert the File to URI
* Intent shareImage = ShareCompat.IntentBuilder.from(activity)
* .setType("image/png")
* .setStream(uriToImage)
* .getIntent();
*/
.setEmailTo(arrayOfStringEmailAddresses)
.setEmailTo(singleStringEmailAddress)
/*
* [OPTIONAL] Designate the email recipients as an array
* of Strings or a single String
*/
.setEmailTo(arrayOfStringEmailAddresses)
.setEmailTo(singleStringEmailAddress)
/*
* [OPTIONAL] Designate the email addresses that will be
* BCC'd on an email as an array of Strings or a single String
*/
.addEmailBcc(arrayOfStringEmailAddresses)
.addEmailBcc(singleStringEmailAddress)
/*
* The title of the chooser that the system will show
* to allow the user to select an app
*/
.setChooserTitle(yourChooserTitle)
.startChooser();
If you have any more questions about using ShareCompat, I highly recommend this great article from Ian Lake, an Android Developer Advocate at Google, for a more complete breakdown of the API. As you'll notice, I borrowed some of this example from that article.
If that article doesn't answer all of your questions, there is always the Javadoc itself for ShareCompat.IntentBuilder on the Android Developers website. I added more to this example of the API's usage on the basis of clemantiano's comment.
If you have a path for that file in the web server, you can get the real path in the server's file system using ServletContext.getRealPath(). Note that it is not guaranteed to work in every container (as a container is not required to unpack the WAR file and store the content in the file system - most do though). And I guess it won't work with files in /WEB-INF, as they don't have a virtual path.
The alternative would be to use ServletContext.getResource() which returns a URI. This URI may be a 'file:' URL, but there's no guarantee for that.
php curl lib is just a wrapper of cUrl, so, first of all, you should install cUrl. Download the cUrl source to your linux server. Then, use the follow commands to install:
tar zxvf cUrl_src_taz
cd cUrl_src_taz
./configure --prefix=/curl/install/home
make
make test (optional)
make install
ln -s /curl/install/home/bin/curl-config /usr/bin/curl-config
Then, copy the head files in the "/curl/install/home/include/" to "/usr/local/include". After all above steps done, the php curl extension configuration could find the original curl, and you can use the standard php extension method to install php curl.
Hope it helps you, :)
Just use another container to wrap last two divs. Don't forget to use CSS prefixes.
#productShowcaseContainer {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
height: 600px;_x000D_
width: 580px;_x000D_
background-color: rgb(240, 240, 240);_x000D_
}_x000D_
_x000D_
#productShowcaseTitle {_x000D_
height: 100px;_x000D_
background-color: rgb(200, 200, 200);_x000D_
}_x000D_
_x000D_
#anotherContainer{_x000D_
display: flex;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
#productShowcaseDetail {_x000D_
background-color: red;_x000D_
flex: 4;_x000D_
}_x000D_
_x000D_
#productShowcaseThumbnailContainer {_x000D_
background-color: blue;_x000D_
flex: 1;_x000D_
}
_x000D_
<div id="productShowcaseContainer">_x000D_
<div id="productShowcaseTitle">1</div>_x000D_
<div id="anotherContainer">_x000D_
<div id="productShowcaseDetail">2</div>_x000D_
<div id="productShowcaseThumbnailContainer">3</div>_x000D_
</div>_x000D_
</div>
_x000D_
You are creating an array of zero length (no slots to put anything in)
int array[]={/*nothing in here = array with no elements*/};
and then trying to assign values to array elements (which you don't have, because there are no slots)
array[i] = number; //array[i] = element i in the array of length 0
You need to define a larger array to fit your needs
int array[] = new int[4]; //Create an array with 4 elements [0],[1],[2] and [3] each containing an int value
same problem with me. This is not a solution but a workaround, which worked for me: Buildpath->Configure buildpath->Libraries-> Here remove the JRE system library pointing to JRE8 and add JRE system library for JRE7.
You need to use the openssl pkcs12 -export -chain -in server.crt -CAfile ...
File.exist?("directory")
Dir[]
returns an array, so it will never be nil
. If you want to do it your way, you could do
Dir["directory"].empty?
which will return true
if it wasn't found.
I went through the Android Device Monitor
Its simple if you are using express.static(__dirname + 'public')
then don't forget to put a forward slash before public that is express.static(__dirname + '/public')
or use express.static('public')
its also going to work;
and don't change anything in CSS linking.
I have checked the chromedriver source code. That injects some javascript files to the browser.
Every javascript file on this link is injected to the web pages:
https://chromium.googlesource.com/chromium/src/+/master/chrome/test/chromedriver/js/
So I used reverse engineering and obfuscated the js files by Hex editing. Now i was sure that no more javascript variable, function names and fixed strings were used to uncover selenium activity. But still some sites and reCaptcha detect selenium!
Maybe they check the modifications that are caused by chromedriver js execution :)
Edit 1:
I discovered there are some parameters in 'navigator' that briefly uncover using of chromedriver. These are the parameters:
So what i needed was a chrome extension to run javascript on the web pages. I made an extension with the js code provided in the article and used another article to add the zipped extension to my project. I have successfully changed the values; But still nothing changed!
I didn't find other variables like these but it doesn't mean that they don't exist. Still reCaptcha detects chromedriver, So there should be more variables to change. The next step should be reverse engineering of the detector services that i don't want to do.
Now I'm not sure does it worth to spend more time on this automation process or search for alternative methods!
Open a phpsh terminal:
php> $myhashmap = array();
php> $myhashmap['mykey1'] = 'myvalue1';
php> $myhashmap['mykey2'] = 'myvalue2';
php> echo $myhashmap['mykey2'];
myvalue2
The complexity of the $myhashmap['mykey2']
in this case appears to be constant time O(1), meaning that as the size of $myhasmap approaches infinity, the amount of time it takes to retrieve a value given a key stays the same.
Evidence the php array read is constant time:
Run this through the PHP interpreter:
php> for($x = 0; $x < 1000000000; $x++){
... $myhashmap[$x] = $x . " derp";
... }
The loop adds 1 billion key/values, it takes about 2 minutes to add them all to the hashmap which may exhaust your memory.
Then see how long it takes to do a lookup:
php> system('date +%N');echo " " . $myhashmap[10333] . " ";system('date +%N');
786946389 10333 derp 789008364
So how fast is the PHP array map lookup?
The 10333
is the key we looked up. 1 million nanoseconds == 1 millisecond. The amount of time it takes to get a value from a key is 2.06 million nanoseconds or about 2 milliseconds. About the same amount of time if the array were empty. This looks like constant time to me.
To insert all data from all columns, just use this:
SELECT * INTO #TempTable
FROM OriginalTable
Don't forget to DROP
the temporary table after you have finished with it and before you try creating it again:
DROP TABLE #TempTable
//
is floor division, it will always give you the integer floor of the result. The other is 'regular' division.
I required the same functionality as requested in the main question. As I was not allowed to use any 3rd party libraries, I have created my own solution basing on @Archimedes Trajano solution.
Following is my solution.
import java.io.ByteArrayInputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.junit.Assert;
import org.w3c.dom.Document;
/**
* Asserts for asserting XML strings.
*/
public final class AssertXml {
private AssertXml() {
}
private static Pattern NAMESPACE_PATTERN = Pattern.compile("xmlns:(ns\\d+)=\"(.*?)\"");
/**
* Asserts that two XML are of identical content (namespace aliases are ignored).
*
* @param expectedXml expected XML
* @param actualXml actual XML
* @throws Exception thrown if XML parsing fails
*/
public static void assertEqualXmls(String expectedXml, String actualXml) throws Exception {
// Find all namespace mappings
Map<String, String> fullnamespace2newAlias = new HashMap<String, String>();
generateNewAliasesForNamespacesFromXml(expectedXml, fullnamespace2newAlias);
generateNewAliasesForNamespacesFromXml(actualXml, fullnamespace2newAlias);
for (Entry<String, String> entry : fullnamespace2newAlias.entrySet()) {
String newAlias = entry.getValue();
String namespace = entry.getKey();
Pattern nsReplacePattern = Pattern.compile("xmlns:(ns\\d+)=\"" + namespace + "\"");
expectedXml = transletaNamespaceAliasesToNewAlias(expectedXml, newAlias, nsReplacePattern);
actualXml = transletaNamespaceAliasesToNewAlias(actualXml, newAlias, nsReplacePattern);
}
// nomralize namespaces accoring to given mapping
DocumentBuilder db = initDocumentParserFactory();
Document expectedDocuemnt = db.parse(new ByteArrayInputStream(expectedXml.getBytes(Charset.forName("UTF-8"))));
expectedDocuemnt.normalizeDocument();
Document actualDocument = db.parse(new ByteArrayInputStream(actualXml.getBytes(Charset.forName("UTF-8"))));
actualDocument.normalizeDocument();
if (!expectedDocuemnt.isEqualNode(actualDocument)) {
Assert.assertEquals(expectedXml, actualXml); //just to better visualize the diffeences i.e. in eclipse
}
}
private static DocumentBuilder initDocumentParserFactory() throws ParserConfigurationException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(false);
dbf.setCoalescing(true);
dbf.setIgnoringElementContentWhitespace(true);
dbf.setIgnoringComments(true);
DocumentBuilder db = dbf.newDocumentBuilder();
return db;
}
private static String transletaNamespaceAliasesToNewAlias(String xml, String newAlias, Pattern namespacePattern) {
Matcher nsMatcherExp = namespacePattern.matcher(xml);
if (nsMatcherExp.find()) {
xml = xml.replaceAll(nsMatcherExp.group(1) + "[:]", newAlias + ":");
xml = xml.replaceAll(nsMatcherExp.group(1) + "=", newAlias + "=");
}
return xml;
}
private static void generateNewAliasesForNamespacesFromXml(String xml, Map<String, String> fullnamespace2newAlias) {
Matcher nsMatcher = NAMESPACE_PATTERN.matcher(xml);
while (nsMatcher.find()) {
if (!fullnamespace2newAlias.containsKey(nsMatcher.group(2))) {
fullnamespace2newAlias.put(nsMatcher.group(2), "nsTr" + (fullnamespace2newAlias.size() + 1));
}
}
}
}
It compares two XML strings and takes care of any mismatching namespace mappings by translating them to unique values in both input strings.
Can be fine tuned i.e. in case of translation of namespaces. But for my requirements just does the job.
Alt + Shift + Insert - switches to column selection mode, allowing the selection of rectangular text fragments (columns)
Ctrl + Shift + Backspace - go to most recent code edit. Hit again to go even further back. Very useful when coding something, browsing other classes for a while and then wanting to go back where we left our code.
Ctrl+E - recently opened files
Ctrl+Shift+E - recently edited files
Ctrl+Shift+V - paste one of the previous values from clipboard
Put the line
$this->db->order_by("course_name","desc");
at top of your query. Like
$this->db->order_by("course_name","desc");$this->db->select('*');
$this->db->where('tennant_id',$tennant_id);
$this->db->from('courses');
$query=$this->db->get();
return $query->result();
A stream is an object used to transfer data. There is a generic stream class System.IO.Stream
, from which all other stream classes in .NET are derived. The Stream
class deals with bytes.
The concrete stream classes are used to deal with other types of data than bytes. For example:
FileStream
class is used when the outside source is a fileMemoryStream
is used to store data in memorySystem.Net.Sockets.NetworkStream
handles network dataReader/writer streams such as StreamReader
and StreamWriter
are not streams - they are not derived from System.IO.Stream
, they are designed to help to write and read data from and to stream!
package com.mycompany;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Car {
@NotNull
private String manufacturer;
@NotNull
@Size(min = 2, max = 14)
private String licensePlate;
@Min(2)
private int seatCount;
public Car(String manufacturer, String licencePlate, int seatCount) {
this.manufacturer = manufacturer;
this.licensePlate = licencePlate;
this.seatCount = seatCount;
}
//getters and setters ...
}
@NotNull
, @Size
and @Min
are so-called constraint annotations, that we use to declare constraints, which shall be applied to the fields of a Car instance:
manufacturer
shall never be null
licensePlate
shall never be null and must be between 2 and 14 characters long
seatCount
shall be at least 2.
If you really want Jackson to return a date with another time zone than UTC (and I myself have several good arguments for that, especially when some clients just don't get the timezone part) then I usually do:
ObjectMapper mapper = new ObjectMapper();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
dateFormat.setTimeZone(TimeZone.getTimeZone("CET"));
mapper.getSerializationConfig().setDateFormat(dateFormat);
// ... etc
It has no adverse effects on those that understand the timezone-p
You probably want
SELECT sum(bytes)
FROM dba_segments
WHERE owner = <<owner of schema>>
If you are logged in as the schema owner, you can also
SELECT SUM(bytes)
FROM user_segments
That will give you the space allocated to the objects owned by the user in whatever tablespaces they are in. There may be empty space allocated to the tables that is counted as allocated by these queries.
What you want to do is simply x==y
What you do is not a good idea, because the items in a dictionary are not supposed to have any order. You might be comparing [('a',1),('b',1)]
with [('b',1), ('a',1)]
(same dictionaries, different order).
For example, see this:
>>> x = dict(a=2, b=2,c=3, d=4)
>>> x
{'a': 2, 'c': 3, 'b': 2, 'd': 4}
>>> y = dict(b=2,c=3, d=4)
>>> y
{'c': 3, 'b': 2, 'd': 4}
>>> zip(x.iteritems(), y.iteritems())
[(('a', 2), ('c', 3)), (('c', 3), ('b', 2)), (('b', 2), ('d', 4))]
The difference is only one item, but your algorithm will see that all items are different
You need to create the element.
input = jQuery('<input name="myname">');
and then append it to the form.
jQuery('#formID').append(input);
to remove an input you use the remove functionality.
jQuery('#inputid').remove();
This is the basic idea, you may have feildsets that you append it too instead, or maybe append it after a specific element, but this is how to build anything dynamically really.
use the below code.
alert(+(Math.round(number + "e+2") + "e-2"));
Thanks to @Stoive and @vava720 I combined the two in this way, avoiding to use the deprecated BlobBuilder and ArrayBuffer
function dataURItoBlob(dataURI) {
'use strict'
var byteString,
mimestring
if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
byteString = atob(dataURI.split(',')[1])
} else {
byteString = decodeURI(dataURI.split(',')[1])
}
mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]
var content = new Array();
for (var i = 0; i < byteString.length; i++) {
content[i] = byteString.charCodeAt(i)
}
return new Blob([new Uint8Array(content)], {type: mimestring});
}
$( ".selector" ).datepicker({ defaultDate: null });
and return empty string from backend
Here's some meta-knowledge for you - if you want to know what you can do with an Array, check the documentation - here's the Array page for Mozilla
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array
There you'll see reference to indexOf, added in Javascript 1.6
Atom currently does not have a built-in terminal(that I know of), so you would have to install an additional package such as platformio-ide-terminal
.
The following screenshots were taken on a mac.
+
to Install a new packageCreating a new branch solved for me:
git checkout -b <nameOfNewBranch>
As expected no need to merge since previous branch was fully contained in the new one.
I had this error because I hadn't installed ASP.NET through Server Roles and Features. Added that and it all worked as expected
ls -i file #output is for me 68551981
debugfs -R 'stat <68551981>' /dev/sda3 # /dev/sda3 is the disk on which the file exists
#results - crtime value
[root@loft9156 ~]# debugfs -R 'stat <68551981>' /dev/sda3
debugfs 1.41.12 (17-May-2010)
Inode: 68551981 Type: regular Mode: 0644 Flags: 0x80000
Generation: 769802755 Version: 0x00000000:00000001
User: 0 Group: 0 Size: 38973440
File ACL: 0 Directory ACL: 0
Links: 1 Blockcount: 76128
Fragment: Address: 0 Number: 0 Size: 0
ctime: 0x526931d7:1697cce0 -- Thu Oct 24 16:42:31 2013
atime: 0x52691f4d:7694eda4 -- Thu Oct 24 15:23:25 2013
mtime: 0x526931d7:1697cce0 -- Thu Oct 24 16:42:31 2013
**crtime: 0x52691f4d:7694eda4 -- Thu Oct 24 15:23:25 2013**
Size of extra inode fields: 28
EXTENTS:
(0-511): 352633728-352634239, (512-1023): 352634368-352634879, (1024-2047): 288392192-288393215, (2048-4095): 355803136-355805183, (4096-6143): 357941248-357943295, (6144
-9514): 357961728-357965098
Inspired by this answer, this solution works in my case(I needed to check whether the value recieved from API is a date or not):
!isNaN(Date.parse(new Date(YourVariable)))
This way, if it is some random string coming from a client, or any other object, you can find out if it is a Date-like object.
try yum groupinstall "Development Tools"
if the installation is success then you will have a full set of development tools. Such as gcc, g++, make, ld ect. After that you can try the compilation of Code Blocks again.
Since yum
is deprecated you can use dnf
instead:
dnf groupinstall "Development Tools"
Both the verifyNoMoreInteractions()
and verifyZeroInteractions()
method internally have the same implementation as:
public static transient void verifyNoMoreInteractions(Object mocks[])
{
MOCKITO_CORE.verifyNoMoreInteractions(mocks);
}
public static transient void verifyZeroInteractions(Object mocks[])
{
MOCKITO_CORE.verifyNoMoreInteractions(mocks);
}
so we can use any one of them on mock object or array of mock objects to check that no methods have been called using mock objects.
use .css
in Jquery like $('strong').css('background','red');
$('strong').css('background','red');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<strong> Example_x000D_
</strong>
_x000D_
You may use rbind
but in this case you need to have the same number of columns in both tables, so try the following:
b$b<-as.double(NA) #keeping numeric format is essential for further calculations
new<-rbind(a,b)
You can use guava's Sets.newSetFromMap(map)
to get one. Java 6 also has that method in java.util.Collections
Class definitions should be like :
export class Environment {
cId:string;
cName:string;
constructor( id: string, name: string ) {
this.cId = id;
this.cName = name;
}
getMyFields(){
return this.cId + " " + this.cName;
}
}
var environments = new Environment('a','b');
console.log(environments.getMyFields()); // will print a b
Source: https://www.typescriptlang.org/docs/handbook/classes.html