In the rubymine gui, there is an ignore list (settings/version control). Maybe try disabling it there. I got the hint from their support guys.
You should normally be able to run a php file (after a successful installation) just by running this command:
$ /path/to/php myfile.php // unix way
C:\php\php.exe myfile.php // windows way
You can read more about running PHP in CLI mode here.
It's worth adding that PHP from version 5.4 onwards is able to run a web server on its own. You can do it by running this code in a folder which you want to serve the pages from:
$ php -S localhost:8000
You can read more about running a PHP in a Web Server mode here.
Try like this:
if message.value[0] == "/" or message.value[0] == "\\":
do_stuff
You can force IE10 to render in IE9 mode by adding:
<meta http-equiv="X-UA-Compatible" content="IE=9">
in your <head>
tag.
See MSDN for more information...
Took DonkeyKong's example.
The issue is I needed to use a declared variable. This allows for stating your left and right-hand side of what you need to compare. This is for supporting an SSRS report where different fields must be linked based on the selection by the user.
The initial case sets the field choice based on the selection and then I can set the field I need to match on for the join.
A second case statement could be added for the right-hand side if the variable is needed to choose from different fields
LEFT OUTER JOIN Dashboard_Group_Level_Matching ON
case
when @Level = 'lvl1' then cw.Lvl1
when @Level = 'lvl2' then cw.Lvl2
when @Level = 'lvl3' then cw.Lvl3
end
= Dashboard_Group_Level_Matching.Dashboard_Level_Name
Just go to your app/storage/logs
there logs of error
available. Go to filename of today's date time and you will find latest error
in your application.
OR
Open app/config/app.php
and change setting
'debug' => false,
To
'debug' => true,
OR
Go to .env
file to your application and change the configuratuion
APP_LOG_LEVEL=debug
The man
page has very detailed descriptions of all of the various options (the status bar is highly configurable). Your best bet is to read through man tmux
and pay particular attention to those options that begin with status-
.
So, for example, status-bg red
would set the background colour of the bar.
The three components of the bar, the left and right sections and the window-list in the middle, can all be configured to suit your preferences. status-left
and status-right
, in addition to having their own variables (like #S
to list the session name) can also call custom scripts to display, for example, system information like load average or battery time.
The option to rename windows or panes based on what is currently running in them is automatic-rename
. You can set, or disable it globally with:
setw -g automatic-rename [on | off]
The most straightforward way to become comfortable with building your own status bar is to start with a vanilla one and then add changes incrementally, reloading the config as you go.1
You might also want to have a look around on github or bitbucket for other people's conf files to provide some inspiration. You can see mine here2.
1 You can automate this by including this line in your .tmux.conf
:
bind R source-file ~/.tmux.conf \; display-message "Config reloaded..."
You can then test your new functionality with Ctrlb,Shiftr. tmux
will print a helpful error message—including a line number of the offending snippet—if you misconfigure an option.
2 Note: I call a different status bar depending on whether I am in X or the console - I find this quite useful.
Just in case someone is having trouble where they have blank spaces either in the date values or in cells, you will have to handle those bits. Sometimes an empty space is not handled by trim function coming from html it's like "$nbsp;". If you don't handle these, your sorting will not work properly and will break where ever there is a blank space.
I got this bit of code from jquery extensions here too and changed it a little bit to suit my requirement. You should do the same:) cheers!
function trim(str) {
str = str.replace(/^\s+/, '');
for (var i = str.length - 1; i >= 0; i--) {
if (/\S/.test(str.charAt(i))) {
str = str.substring(0, i + 1);
break;
}
}
return str;
}
jQuery.fn.dataTableExt.oSort['uk-date-time-asc'] = function(a, b) {
if (trim(a) != '' && a!=" ") {
if (a.indexOf(' ') == -1) {
var frDatea = trim(a).split(' ');
var frDatea2 = frDatea[0].split('/');
var x = (frDatea2[2] + frDatea2[1] + frDatea2[0]) * 1;
}
else {
var frDatea = trim(a).split(' ');
var frTimea = frDatea[1].split(':');
var frDatea2 = frDatea[0].split('/');
var x = (frDatea2[2] + frDatea2[1] + frDatea2[0] + frTimea[0] + frTimea[1] + frTimea[2]) * 1;
}
} else {
var x = 10000000; // = l'an 1000 ...
}
if (trim(b) != '' && b!=" ") {
if (b.indexOf(' ') == -1) {
var frDateb = trim(b).split(' ');
frDateb = frDateb[0].split('/');
var y = (frDateb[2] + frDateb[1] + frDateb[0]) * 1;
}
else {
var frDateb = trim(b).split(' ');
var frTimeb = frDateb[1].split(':');
frDateb = frDateb[0].split('/');
var y = (frDateb[2] + frDateb[1] + frDateb[0] + frTimeb[0] + frTimeb[1] + frTimeb[2]) * 1;
}
} else {
var y = 10000000;
}
var z = ((x < y) ? -1 : ((x > y) ? 1 : 0));
return z;
};
jQuery.fn.dataTableExt.oSort['uk-date-time-desc'] = function(a, b) {
if (trim(a) != '' && a!=" ") {
if (a.indexOf(' ') == -1) {
var frDatea = trim(a).split(' ');
var frDatea2 = frDatea[0].split('/');
var x = (frDatea2[2] + frDatea2[1] + frDatea2[0]) * 1;
}
else {
var frDatea = trim(a).split(' ');
var frTimea = frDatea[1].split(':');
var frDatea2 = frDatea[0].split('/');
var x = (frDatea2[2] + frDatea2[1] + frDatea2[0] + frTimea[0] + frTimea[1] + frTimea[2]) * 1;
}
} else {
var x = 10000000;
}
if (trim(b) != '' && b!=" ") {
if (b.indexOf(' ') == -1) {
var frDateb = trim(b).split(' ');
frDateb = frDateb[0].split('/');
var y = (frDateb[2] + frDateb[1] + frDateb[0]) * 1;
}
else {
var frDateb = trim(b).split(' ');
var frTimeb = frDateb[1].split(':');
frDateb = frDateb[0].split('/');
var y = (frDateb[2] + frDateb[1] + frDateb[0] + frTimeb[0] + frTimeb[1] + frTimeb[2]) * 1;
}
} else {
var y = 10000000;
}
var z = ((x < y) ? 1 : ((x > y) ? -1 : 0));
return z;
};
You can't catch/handle fatal errors, but you can log/report them. For quick debugging I modified one answer to this simple code
function __fatalHandler()
{
$error = error_get_last();
// Check if it's a core/fatal error, otherwise it's a normal shutdown
if ($error !== NULL && in_array($error['type'],
array(E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING,
E_COMPILE_ERROR, E_COMPILE_WARNING,E_RECOVERABLE_ERROR))) {
echo "<pre>fatal error:\n";
print_r($error);
echo "</pre>";
die;
}
}
register_shutdown_function('__fatalHandler');
No Worries! I have found the solution! I just installed https://msdn.microsoft.com/en-us/windows/desktop/bg162891.aspx and it all worked fine :)
An alternative way to (not dynamically) link a text to activate a worksheet without macros is to make the selected string an actual link. You can do this by selecting the cell that contains the text and press CTRL+K then select the option/tab 'Place in this document' and select the tab you want to activate. If you would click the text (that is now a link) the configured sheet will become active/selected.
Unfortunately, this is not a particularly simple task to accomplish. In my answer here, I detail how to adjust the color of a ListSeparator
by just checking out the parent style used by Android, creating a new image, and creating a new style based on the original. Unfortunately, unlike with the ListSeparator
's style, AlertDialog
themes are internal, and therefore cannot be referenced as parent styles. There is no easy way to change that little blue line! Thus you need to resort to making custom dialogs.
If that just isn't your cup of tea... don't give up! I was very disturbed that there was no easy way to do this so I set up a little project on github for making quickly customized holo-style dialogs (assuming that the phone supports the Holo style). You can find the project here: https://github.com/danoz73/QustomDialog
It should easily enable going from boring blue to exciting orange!
The project is basically an example of using a custom dialog builder, and in the example I created a custom view that seemed to cater to the IP Address example you give in your original question.
With QustomDialog
, in order to create a basic dialog (title, message) with a desired different color for the title or divider, you use the following code:
private String HALLOWEEN_ORANGE = "#FF7F27";
QustomDialogBuilder qustomDialogBuilder = new QustomDialogBuilder(v.getContext()).
setTitle("Set IP Address").
setTitleColor(HALLOWEEN_ORANGE).
setDividerColor(HALLOWEEN_ORANGE).
setMessage("You are now entering the 10th dimension.");
qustomDialogBuilder.show();
And in order to add a custom layout (say, to add the little IP address EditText
), you add
setCustomView(R.layout.example_ip_address_layout, v.getContext())
to the builder with a layout that you have designed (the IP example can be found in the github). I hope this helps. Many thanks to Joseph Earl and his answer here.
Below solved. I have wrongly given the bin /directory/, so faced the issue:
if you installed apache at C:/httpd-2.4.41-o102s-x64-vc14-r2/Apache24
then the modules are at.. C:/httpd-2.4.41-o102s-x64-vc14-r2/Apache24/modules
So, the file C:/httpd-2.4.41-o102s-x64-vc14-r2/Apache24/conf/httpd.conf
should have
Define SRVROOT "C:/httpd-2.4.41-o102s-x64-vc14-r2/Apache24/"
Hope that helps
Bit late on this thread. angular.equals does deep check, however does anyone know that why its behave differently if one of the member contain "$" in prefix ?
You can try this Demo with following input
var obj3 = {}
obj3.a= "b";
obj3.b={};
obj3.b.$c =true;
var obj4 = {}
obj4.a= "b";
obj4.b={};
obj4.b.$c =true;
angular.equals(obj3,obj4);
The second clause does not need a !variable.nil?
check—if evaluation reaches that point, variable.nil
is guaranteed to be false (because of short-circuiting).
This should be sufficient:
variable = id if variable.nil? || variable.empty?
If you're working with Ruby on Rails, Object.blank?
solves this exact problem:
An object is blank if it’s false, empty, or a whitespace string. For example,
""
," "
,nil
,[]
, and{}
are all blank.
Java 8 provides a new way to call the copy constructor or clone method on the element dogs elegantly and compactly: Streams, lambdas and collectors.
Copy constructor:
List<Dog> clonedDogs = dogs.stream().map(Dog::new).collect(toList());
The expression Dog::new
is called a method reference. It creates a function object which calls a constructor on Dog
which takes another dog as argument.
Clone method[1]:
List<Dog> clonedDogs = dogs.stream().map(d -> d.clone()).collect(toList());
ArrayList
as the resultOr, if you have to get an ArrayList
back (in case you want to modify it later):
ArrayList<Dog> clonedDogs = dogs.stream().map(Dog::new).collect(toCollection(ArrayList::new));
If you don't need to keep the original content of the dogs
list you can instead use the replaceAll
method and update the list in place:
dogs.replaceAll(Dog::new);
All examples assume import static java.util.stream.Collectors.*;
.
ArrayList
sThe collector from the last example can be made into a util method. Since this is such a common thing to do I personally like it to be short and pretty. Like this:
ArrayList<Dog> clonedDogs = dogs.stream().map(d -> d.clone()).collect(toArrayList());
public static <T> Collector<T, ?, ArrayList<T>> toArrayList() {
return Collectors.toCollection(ArrayList::new);
}
CloneNotSupportedException
:For this solution to work the clone
method of Dog
must not declare that it throws CloneNotSupportedException
. The reason is that the argument to map
is not allowed to throw any checked exceptions.
Like this:
// Note: Method is public and returns Dog, not Object
@Override
public Dog clone() /* Note: No throws clause here */ { ...
This should not be a big problem however, since that is the best practice anyway. (Effectice Java for example gives this advice.)
Thanks to Gustavo for noting this.
If you find it prettier you can instead use the method reference syntax to do exactly the same thing:
List<Dog> clonedDogs = dogs.stream().map(Dog::clone).collect(toList());
Well if you are doing this in Asp.Net or have access to HttpContext.Current.Request I'd say these are easier and more general ways of getting them:
var scheme = Request.Url.Scheme; // will get http, https, etc.
var host = Request.Url.Host; // will get www.mywebsite.com
var port = Request.Url.Port; // will get the port
var path = Request.Url.AbsolutePath; // should get the /pages/page1.aspx part, can't remember if it only get pages/page1.aspx
I hope this helps. :)
Despite this being against the general SO policy on these matters, this seems to be what the OP genuinely wants:
http://www.google.com/search?btnG=1&pws=0&q=java+executable+wrapper
If you'd like, you could also try creating the appropriate batch or script file containing the single line:
java -jar MyJar.jar
Or in many cases on windows just double clicking the executable jar.
Info on MySQL's full text search. This is restricted to MyISAM tables, so may not be suitable if you wantto use a different table type.
http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
Even if WHERE textcolumn LIKE "%SUBSTRING%"
is going to be slow, I think it is probably better to let the Database handle it rather than have PHP handle it. If it is possible to restrict searches by some other criteria (date range, user, etc) then you may find the substring search is OK (ish).
If you are searching for whole words, you could pull out all the individual words into a separate table and use that to restrict the substring search. (So when searching for "my search string" you look for the the longest word "search" only do the substring search on records containing the word "search")
Chris Fulstow's solution will work (+1), however, it may not be efficient, especially if your collection is very large. Non-rooted regular expressions (those not beginning with ^
, which anchors the regular expression to the start of the string), and those using the i
flag for case insensitivity will not use indexes, even if they exist.
An alternative option you might consider is to denormalize your data to store a lower-case version of the name
field, for instance as name_lower
. You can then query that efficiently (especially if it is indexed) for case-insensitive exact matches like:
db.collection.find({"name_lower": thename.toLowerCase()})
Or with a prefix match (a rooted regular expression) as:
db.collection.find( {"name_lower":
{ $regex: new RegExp("^" + thename.toLowerCase(), "i") } }
);
Both of these queries will use an index on name_lower
.
I see that you are looking for an implementation of the problem more than solving that error. Here you have a possible solution:
from itertools import chain
def involved(courses, person):
courses_info = chain.from_iterable(x.values() for x in courses.values())
return filter(lambda x: x['teacher'] == person, courses_info)
print involved(courses, 'Dave')
The first thing I do is getting the list of the courses and then filter by teacher's name.
to add to John's answer:
what you want to pass to the shuffle
function is a deck of cards from the class deckOfCards
that you've declared in main; however, the deck of cards or vector<Card> deck
that you've declared in your class is private, so not accessible from outside the class. this means you'd want a getter function, something like this:
class deckOfCards
{
private:
vector<Card> deck;
public:
deckOfCards();
static int count;
static int next;
void shuffle(vector<Card>& deck);
Card dealCard();
bool moreCards();
vector<Card>& getDeck() { //GETTER
return deck;
}
};
this will in turn allow you to call your shuffle function from main like this:
deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck.getDeck()); // shuffle the cards in the deck
however, you have more problems, specifically when calling cout
. first, you're calling the dealCard
function wrongly; as dealCard
is a memeber function of a class, you should be calling it like this cardDeck.dealCard();
instead of this dealCard(cardDeck);
.
now, we come to your second problem - print to standard output. you're trying to print your deal card, which is an object of type Card
by using the following instruction:
cout << cardDeck.dealCard();// deal the cards in the deck
yet, the cout
doesn't know how to print it, as it's not a standard type. this means you should overload your <<
operator to print whatever you want it to print when calling with a Card
type.
If you are able to read the excel file correctly and only the integer values are not showing up. you can specify like this.
df = pd.read_excel('my.xlsx',sheetname='Sheet1', engine="openpyxl", dtype=str)
this should change your integer values into a string and show in dataframe
You have two options, either float:left
or display:inline-block
.
Both methods have their caveats. It seems that display:inline-block
is more common nowadays, as it avoids some of the issues of floating.
Read this article http://designshack.net/articles/css/whats-the-deal-with-display-inline-block/ or this one http://www.vanseodesign.com/css/inline-blocks/ for a more in detail discussion.
for item in a:
if 1 in item:
print item
I've been driving myself crazy for days trying to get dex2jar to work on a fedora 31 laptop against an apk that just wasn't going to work. This python 3 script did the trick in minutes and installing jd-gui made class files human readable.
http://java-decompiler.github.io/
https://github.com/Storyyeller/enjarify
specifically, here's what I ran:
# i installed apktool before the rest of the stuff, may not need it but here it is
$> cd /opt
$> sudo mkdir apktool
$> cd apktool/
$> sudo wget https://raw.githubusercontent.com/iBotPeaches/Apktool/master/scripts/linux/apktool
$> sudo wget https://bitbucket.org/iBotPeaches/apktool/downloads/apktool_2.4.1.jar
$> sudo mv apktool_2.4.1.jar apktool.jar
$> sudo mv apktool* /usr/bin/
$> sudo chmod a+x /usr/bin/apktool*
# and enjarify
$> cd /opt
$> sudo git clone https://github.com/Storyyeller/enjarify.git
$> cd enjarify/
$> sudo ln -s /opt/enjarify/enjarify.sh /usr/bin/enjarify
# and finally jd-gui
$> cd /opt
$> sudo git clone https://github.com/java-decompiler/jd-gui.git
$> cd jd-gui/
$> sudo ./gradlew build
# I made an alias to kick of the jd-gui with short commandline rather than long java -jar blahblahblah :)
$> echo "jd-gui='java -jar /opt/jd-gui/build/launch4j/lib/jd-gui-1.6.6.jar'" >> ~/.bashrc
Now one should be able to rum the following to get class files:
$> enjarify yourapkfile.apk
And to start jd-gui:
$> jd-gui
Then just open your class files!
JavaScript, as defined in your question, can't directly work with MySql. This is because it isn't running on the same computer.
JavaScript runs on the client side (in the browser), and databases usually exist on the server side. You'll probably need to use an intermediate server-side language (like PHP, Java, .Net, or a server-side JavaScript stack like Node.js) to do the query.
Here's a tutorial on how to write some code that would bind PHP, JavaScript, and MySql together, with code running both in the browser, and on a server:
http://www.w3schools.com/php/php_ajax_database.asp
And here's the code from that page. It doesn't exactly match your scenario (it does a query, and doesn't store data in the DB), but it might help you start to understand the types of interactions you'll need in order to make this work.
In particular, pay attention to these bits of code from that article.
Bits of Javascript:
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
Bits of PHP code:
mysql_select_db("ajax_demo", $con);
$result = mysql_query($sql);
// ...
$row = mysql_fetch_array($result)
mysql_close($con);
Also, after you get a handle on how this sort of code works, I suggest you use the jQuery JavaScript library to do your AJAX calls. It is much cleaner and easier to deal with than the built-in AJAX support, and you won't have to write browser-specific code, as jQuery has cross-browser support built in. Here's the page for the jQuery AJAX API documentation.
HTML/Javascript code:
<html>
<head>
<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
PHP code:
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'peter', 'abc123');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ajax_demo", $con);
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysql_query($sql);
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
You can also refactor your code to use a generator. But this may not be a solution for all types of nested loops.
Don't code, Xcode !
Instead of using UILabel for this specific matter, I suggest you to take a look at UIButton. It gives, out of the box, the ability to set Content Insets (top, left, bottom, right) in the Size inspector. Set the desired margins, after that disable the button right in Xcode and done.
The difference between text/xml and application/xml is the default character encoding if the charset parameter is omitted:
Text/xml and application/xml behave differently when the charset parameter is not explicitly specified. If the default charset (i.e., US-ASCII) for text/xml is inconvenient for some reason (e.g., bad web servers), application/xml provides an alternative (see "Optional parameters" of application/xml registration in Section 3.2).
For text/xml:
Conformant with [RFC2046], if a text/xml entity is received with the charset parameter omitted, MIME processors and XML processors MUST use the default charset value of "us-ascii"[ASCII]. In cases where the XML MIME entity is transmitted via HTTP, the default charset value is still "us-ascii".
For application/xml:
If an application/xml entity is received where the charset parameter is omitted, no information is being provided about the charset by the MIME Content-Type header. Conforming XML processors MUST follow the requirements in section 4.3.3 of [XML] that directly address this contingency. However, MIME processors that are not XML processors SHOULD NOT assume a default charset if the charset parameter is omitted from an application/xml entity.
So if the charset parameter is omitted, the character encoding of text/xml is US-ASCII while with application/xml the character encoding can be specified in the document itself.
Now a rule of thumb on the internet is: “Be strict with the output but be tolerant with the input.” That means make sure to meet the standards as much as possible when delivering data over the internet. But build in some mechanisms to overlook faults or to guess when receiving and interpreting data over the internet.
So in your case just pick one of the two types (I recommend application/xml) and make sure to specify the used character encoding properly (I recommend to use the respective default character encoding to play safe, so in case of application/xml use UTF-8 or UTF-16).
I'd like to differ with marc_s on this, who wrote:
a XSD describes the DATA aspects e.g. of a webservice - the WSDL describes the FUNCTIONS of the web services (method calls). You cannot typically figure out the method calls from your data alone.
WSDL does not describe functions. WSDL defines a network interface, which itself is comprised of endpoints that get messages and then sometimes reply with messages. WSDL describes the endpoints, and the request and reply messages. It is very much message oriented.
We often think of WSDL as a set of functions, but this is because the web services tools typically generate client-side proxies that expose the WSDL operations as methods or function calls. But the WSDL does not require this. This is a side effect of the tools.
EDIT: Also, in the general case, XSD does not define data aspects of a web service. XSD defines the elements that may be present in a compliant XML document. Such a document may be exchanged as a message over a web service endpoint, but it need not be.
Getting back to the question I would answer the original question a little differently. I woudl say YES, it is possible to generate a WSDL file given a xsd file, in the same way it is possible to generate an omelette using eggs.
EDIT: My original response has been unclear. Let me try again. I do not suggest that XSD is equivalent to WSDL, nor that an XSD is sufficient to produce a WSDL. I do say that it is possible to generate a WSDL, given an XSD file, if by that phrase you mean "to generate a WSDL using an XSD file". Doing so, you will augment the information in the XSD file to generate the WSDL. You will need to define additional things - message parts, operations, port types - none of these are present in the XSD. But it is possible to "generate a WSDL, given an XSD", with some creative effort.
If the phrase "generate a WSDL given an XSD" is taken to imply "mechanically transform an XSD into a WSDL", then the answer is NO, you cannot do that. This much should be clear given my description of the WSDL above.
When generating a WSDL using an XSD file, you will typically do something like this (note the creative steps in this procedure):
Most of the WSDL is more or less boilerplate. It can look daunting, but that is mostly because of those scary and plentiful angle brackets, I've found.
Some have suggested that this is a long-winded manual process. Maybe. But this is how you can build interoperable services. You can also use tools for defining WSDL. Dynamically generating WSDL from code will lead to interop pitfalls.
When you do git status
, Git tells you how to unstage:
Changes to be committed: (use "git reset HEAD <file>..." to unstage).
So git reset HEAD <file>
worked for me and the changes were un-touched.
In git bash, stashing of untracked files is achieved by using the command
git stash --include-untracked
# or
git stash -u
http://git-scm.com/docs/git-stash
git stash removes any untracked or uncommited files from your workspace. And you can revert git stash by using following commands
git stash pop
This will place the file back in your local workspace.
My experience
I had to perform a modification to my gitIgnore file to avoid movement of .classpath and .project files into remote repo. I am not allowed to move this modified .gitIgnore in remote repo as of now.
.classpath and .project files are important for eclipse - which is my java editor.
I first of all selectively added my rest of the files and committed for staging. However, final push cannot be performed unless the modified .gitIgnore fiels and the untracked files viz. .project and .classpath are not stashed.
I used
git stash
for stashing the modified .gitIgnore file.
For stashing .classpath and .project file, I used
git stash --include-untracked
and it removed the files from my workspace. Absence of these files takes away my capability of working on my work location in eclipse. I proceeded on with completing the procedure for pushing the committed files to remote. Once this was done successfully, I used
git stash pop
This pasted the same files back in my workspace. This gave back to me my ability to work on the same project in eclipse. Hope this brushes aside misconceptions.
You should use #!/usr/bin/env bash
for portability: different *nixes put bash
in different places, and using /usr/bin/env
is a workaround to run the first bash
found on the PATH
. And sh
is not bash
.
A better solution than selected answer would be to use border-size rather than border-spacing. The main problem with using border-spacing is that even the first column would have a spacing in the front.
For example,
table {_x000D_
border-collapse: separate;_x000D_
border-spacing: 80px 0;_x000D_
}_x000D_
_x000D_
td {_x000D_
padding: 10px 0;_x000D_
}
_x000D_
<table>_x000D_
<tr>_x000D_
<td>First Column</td>_x000D_
<td>Second Column</td>_x000D_
<td>Third Column</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>1</td>_x000D_
<td>2</td>_x000D_
<td>3</td>_x000D_
</tr>_x000D_
</table>
_x000D_
To avoid this use: border-left: 100px solid #FFF;
and set border:0px
for the first column.
For example,
td,th{_x000D_
border-left: 100px solid #FFF;_x000D_
}_x000D_
_x000D_
tr>td:first-child {_x000D_
border:0px;_x000D_
}
_x000D_
<table id="t">_x000D_
<tr>_x000D_
<td>Column1</td>_x000D_
<td>Column2</td>_x000D_
<td>Column3</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>1000</td>_x000D_
<td>2000</td>_x000D_
<td>3000</td>_x000D_
</tr>_x000D_
</table>
_x000D_
there's a better way
# Larger example
rows = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
('2006-04-06', 'SELL', 'IBM', 500, 53.00)]
c.executemany('insert into stocks values (?,?,?,?,?)', rows)
connection.commit()
Well, to do this one can also use the freopen function provided in C++ - http://www.cplusplus.com/reference/cstdio/freopen/ and read the file line by line as follows -:
#include<cstdio>
#include<iostream>
using namespace std;
int main(){
freopen("path to file", "rb", stdin);
string line;
while(getline(cin, line))
cout << line << endl;
return 0;
}
You can also perform this action via SQL Server Management Studio.
Right click on your selected table -> Modify
Right click on the field you want to set as PK --> Set Primary Key
Under Column Properties set "Identity Specification" to Yes, then specify the starting value and increment value.
Then in the future if you want to be able to just script this kind of thing out you can right click on the table you just modified and select
"SCRIPT TABLE AS" --> CREATE TO
so that you can see for yourself the correct syntax to perform this action.
The right approach is to use setImageViewUri()
(slower) or the setImageViewBitmap()
and recreating RemoteView
s every time you update the notification.
Another option; use invoke-command
:
cls
$cred = Get-Credential
$server = 'MyRemoteComputer'
$service = 'My Service Name'
invoke-command -Credential $cred -ComputerName $server -ScriptBlock {
param(
[Parameter(Mandatory=$True,Position=0)]
[string]$service
)
stop-service $service
} -ArgumentList $service
NB: to use this option you'll need PowerShell to be installed on the remote machine and for the firewall to allow requests through, and for the Windows Remote Management service to be running on the target machine. You can configure the firewall by running the following script directly on the target machine (one off task): Enable-PSRemoting -force
.
With your private key and public certificate, you need to create a PKCS12 keystore first, then convert it into a JKS.
# Create PKCS12 keystore from private key and public certificate.
openssl pkcs12 -export -name myservercert -in selfsigned.crt -inkey server.key -out keystore.p12
# Convert PKCS12 keystore into a JKS keystore
keytool -importkeystore -destkeystore mykeystore.jks -srckeystore keystore.p12 -srcstoretype pkcs12 -alias myservercert
To verify the contents of the JKS, you can use this command:
keytool -list -v -keystore mykeystore.jks
If this was not a self-signed certificate, you would probably want to follow this step with importing the certificate chain leading up to the trusted CA cert.
After doing a git fetch
, do a git log HEAD..origin/master
to show the log entries between your last common commit and the origin's master branch. To show the diffs, use either git log -p HEAD..origin/master
to show each patch, or git diff HEAD...origin/master
(three dots not two) to show a single diff.
There normally isn't any need to undo a fetch, because doing a fetch only updates the remote branches and none of your branches. If you're not prepared to do a pull and merge in all the remote commits, you can use git cherry-pick
to accept only the specific remote commits you want. Later, when you're ready to get everything, a git pull
will merge in the rest of the commits.
Update: I'm not entirely sure why you want to avoid the use of git fetch. All git fetch does is update your local copy of the remote branches. This local copy doesn't have anything to do with any of your branches, and it doesn't have anything to do with uncommitted local changes. I have heard of people who run git fetch in a cron job because it's so safe. (I wouldn't normally recommend doing that, though.)
If you're like me and you don't like the idea of deleting things that were part of the standard system installation (which others have suggested) then you might like the solution I ended up using:
.profile
, or whatever is appropriate, and put /usr/local/bin
at the start
of your PATH
so that Homebrew binaries are found before system binariesbrew install python
- this installs a newer version of python in /usr/local
pip install pandas
This worked for me in OS X 10.8.2, and I can't see any reason it shouldn't work in 10.6.8.
I was also facing the same error. The reason for this is that there is no smtp server on your environment. For creating a fake smtp server I used this fake-smtp.jar file for creating a virtual server and listening to all the requests. If you are facing the same error, I recommend you to use this jar and run it after extracting and then try to run your application.
Another, less convenient, way to do it is to use Decimal
class:
from decimal import Decimal
pos_inf = Decimal('Infinity')
neg_inf = Decimal('-Infinity')
egrep -v "^\s\s+"
egrep already do regex, and the \s is white space.
The + duplicates current pattern.
The ^ is for the start
As of Oct 2019, SQL Server Management Studio, they did not upgraded the SSMS to add create ER Diagram feature.
I would suggest try using DBWeaver from here :
I am using Mac and Windows both and I was able to download the community edition and logged into my SQL server database and was able to create the ER diagram using the DB Weaver.
I faced same issue & it resolved by
ENTRYPOINT ["sh", "/docker-entrypoint.sh"]
For the Dockerfile in the original question it should be like:
ENTRYPOINT ["sh", "/usr/src/app/docker-entrypoint.sh"]
With Java 8, you actually can
List<TestB> variable = collectionOfListA
.stream()
.map(e -> (TestB) e)
.collect(Collectors.toList());
if you want to hold the arguments from Terminal, try the following code:
A = ARGV[0].to_i
B = ARGV[1].to_i
puts "#{A} + #{B} = #{A + B}"
The pid files contains the process id (a number) of a given program. For example, Apache HTTPD may write its main process number to a pid file - which is a regular text file, nothing more than that - and later use the information there contained to stop itself. You can also use that information to kill the process yourself, using cat filename.pid | xargs kill
Usually this happens if something is wrong with the byte array.
File.WriteAllBytes("filename.PDF", Byte[]);
This creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.
Asynchronous implementation of this is also available.
public static System.Threading.Tasks.Task WriteAllBytesAsync
(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = null);
This can also be done through the SSMS GUI. The nice thing about this method is it warns you if there are any relationships on that column and can also automatically delete those as well.
As I stated before, if there are any relationships that would also need to be deleted, it will ask you at this point if you would like to delete those as well. You will likely need to do so to delete the column.
Remove the comma
receipt int(10),
And also AUTO INCREMENT
should be a KEY
double
datatype also requires the precision of decimal places so right syntax is double(10,2)
It looks like you want to define Truck as a Class
with properties NumberOfAxles, AxleWeights & AxleSpacings.
This can be defined in a CLASS MODULE (here named clsTrucks)
Option Explicit
Private tID As String
Private tNumberOfAxles As Double
Private tAxleSpacings As Double
Public Property Get truckID() As String
truckID = tID
End Property
Public Property Let truckID(value As String)
tID = value
End Property
Public Property Get truckNumberOfAxles() As Double
truckNumberOfAxles = tNumberOfAxles
End Property
Public Property Let truckNumberOfAxles(value As Double)
tNumberOfAxles = value
End Property
Public Property Get truckAxleSpacings() As Double
truckAxleSpacings = tAxleSpacings
End Property
Public Property Let truckAxleSpacings(value As Double)
tAxleSpacings = value
End Property
then in a MODULE the following defines a new truck and it's properties and adds it to a collection of trucks and then retrieves the collection.
Option Explicit
Public TruckCollection As New Collection
Sub DefineNewTruck()
Dim tempTruck As clsTrucks
Dim i As Long
'Add 5 trucks
For i = 1 To 5
Set tempTruck = New clsTrucks
'Random data
tempTruck.truckID = "Truck" & i
tempTruck.truckAxleSpacings = 13.5 + i
tempTruck.truckNumberOfAxles = 20.5 + i
'tempTruck.truckID is the collection key
TruckCollection.Add tempTruck, tempTruck.truckID
Next i
'retrieve 5 trucks
For i = 1 To 5
'retrieve by collection index
Debug.Print TruckCollection(i).truckAxleSpacings
'retrieve by key
Debug.Print TruckCollection("Truck" & i).truckAxleSpacings
Next i
End Sub
There are several ways of doing this so it really depends on how you intend to use the data as to whether an a class/collection is the best setup or arrays/dictionaries etc.
Wherever you want vertically center style means you can try display:table-cell
and vertical-align:middle
.
Example:
#box_x000D_
{_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
height: 90px;_x000D_
width: 270px;_x000D_
background: #000;_x000D_
font-size: 48px;_x000D_
font-style: oblique;_x000D_
color: #FFF;_x000D_
text-align: center;_x000D_
margin-top: 20px;_x000D_
margin-left: 5px;_x000D_
}
_x000D_
<div Id="box">_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit._x000D_
</div>
_x000D_
I found a blog article which seems to explain something related:
HTML5 input type=number and decimals/floats in Chrome
In summary:
step
helps to define the domain of valid valuesstep
is 1
min
and max
, inclusive, if given)I would assume that's conflating with the ambiguity of using a comma as a thousand separator vs a comma as a decimal point, and your 51,983
is actually a strangely-parsed fifty-one thousand, nine hundred and eight-three.
Apparently you can use step="any"
to widen the domain to all rational numbers in range, however I've not tried it myself. For latitude and longitude I've successfully used:
<input name="lat" type="number" min="-90.000000" max="90.000000" step="0.000001">
<input name="lon" type="number" min="-180.000000" max="180.000000" step="0.000001">
It might not be pretty, but it works.
Sometimes you can get away with the tee function from itertools, it returns multiple iterators for the same generator that can be used independently.
Stopping the service and killing the daemon are indeed the correct ways to shutdown a node. However, it's not recommended to do so directly if you want to take down a node for maintenance. In fact, if you don't have replicas you will lose data.
When you directly shutdown a node, Elasticsearch will wait for 1m (default time) for it to come back online. If it doesn't, then it will start to allocate the shards from that node to other nodes wasting lots of IO.
A typical approach would be to disable shard allocation temporarily by issuing:
PUT _cluster/settings
{
"persistent": {
"cluster.routing.allocation.enable": "none"
}
}
Now, when you take down a node, ES won't try to allocate shard from that node to other nodes and you can perform you maintenance activity and then once the node is up, you can enable shard allocation again:
PUT _cluster/settings
{
"persistent": {
"cluster.routing.allocation.enable": "all"
}
}
Source: https://www.elastic.co/guide/en/elasticsearch/reference/5.5/restart-upgrade.html
If you don't have replicas for all your indexes, then performing this type of activity will have downtime on some of the indexes. A cleaner way in this case would be to migrate all the shards to other nodes before taking the node down:
PUT _cluster/settings
{
"transient" : {
"cluster.routing.allocation.exclude._ip" : "10.0.0.1"
}
}
This will move all shards from 10.0.0.1
to other nodes (will take time depending on the data). Once everything is done, you can kill the node, perform maintenance and get it back online. This is a slower operation and is not required if you have replicas.
(Instead of _ip, _id, _name with wildcards will work just fine.)
More information: https://www.elastic.co/guide/en/elasticsearch/reference/5.5/allocation-filtering.html
Other answers have explained how to kill a process.
Use string append operator on the serial.read()
. It works better than string.concat()
char r;
string mystring = "";
while(serial.available()){
r = serial.read();
mystring = mystring + r;
}
After you are done saving the stream in a string(mystring, in this case), use SubString functions to extract what you are looking for.
For those who (unlike OP) are using the express lib:
http.get('*',function(req,res){
res.redirect('http://exmple.com'+req.url)
})
Your app is crashing at:
welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");
because mPlayer=null
.
You forgot to initialize Player mPlayer
in your PlayGame Activity.
mPlayer = new Player(context,"");
Lets say your HTML looks something like this:
<div class="box">
<!-- stuff -->
<p class="bet_time">Bet 5 days ago</p>
</div>
Then, with CSS, you can make that text appear in the bottom right like so:
.box {
position:relative;
}
.bet_time {
position:absolute;
bottom:0;
right:0;
}
The way this works is that absolutely positioned elements are always positioned with respect to the first relatively positioned parent element, or the window. Because we set the box's position to relative, .bet_time
positions its right edge to the right edge of .box
and its bottom edge to the bottom edge of .box
Try
This could also be the problem of an incorrect xml layout file for example. If your xml files are not valid (containing errors) the R file will not re-generate after a clean-up. If you fix this, the R file will be generated automatically again.
For people who are still struggling with this error, it can also happen if you accidentally create a duplicate column with the same name. Remove duplicate columns like so:
df = df.loc[:,~df.columns.duplicated()]
$otherController = new OtherController();
$otherController->methodFromOtherController($param1, $param2 ...);
But, doing this, you will have a problem: the other method returns something like response()->json($result), and is not it what you want.
To resolve this problem, define the first parameter of the other controller's method as:
public function methodFromOtherController(Request $request = null, ...
$otherController = new OtherController();
$otherController->methodFromOtherController(null, $param1, $param2 ...);
public function methodFromOtherController(Request $request = null, ...)
{
...
if (is_null($request)) {
return $result;
} else {
return response()->json($result);
}
}
Since I have recently developed an Android application using gyroscope data (steady compass), I tried to collect a list with such devices. This is not an exhaustive list at all, but it is what I have so far:
*** Phones:
*** Tablets:
Hope the list keeps growing and hope that gyros will be soon available on mid and low price smartphones.
The following code reads 4 bytes from array
(a byte[]
) at position index
and returns a int
. I tried out most of the code from the other answers on Java 10 and some other variants I dreamed up.
This code used the least amount of CPU time but allocates a ByteBuffer
until Java 10's JIT gets rid of the allocation.
int result;
result = ByteBuffer.
wrap(array).
getInt(index);
This code is the best performing code that does not allocate anything. Unfortunately, it consumes 56% more CPU time compared to the above code.
int result;
short data0, data1, data2, data3;
data0 = (short) (array[index++] & 0x00FF);
data1 = (short) (array[index++] & 0x00FF);
data2 = (short) (array[index++] & 0x00FF);
data3 = (short) (array[index++] & 0x00FF);
result = (data0 << 24) | (data1 << 16) | (data2 << 8) | data3;
Another solution:
^[1-9]\d*$
\d
equivalent to [0-9]
Open Terminal/command prompt in the respective project directory and type following command.
npm install --save bootstrap
Then open .angular-cli.json file, Look for
"styles": [
"styles.css"
],
change that to
"styles": [
"../node_modules/bootstrap/dist/css/bootstrap.min.css",
"styles.css"
],
All done.
Use position: fixed
on the div
that contains your header, with something like
#header {
position: fixed;
}
#content {
margin-top: 100px;
}
In this example, when #content
starts off 100px below #header
, but as the user scrolls, #header
stays in place. Of course it goes without saying that you'll want to make sure #header
has a background so that its content will actually be visible when the two div
s overlap. Have a look at the position
property here: http://reference.sitepoint.com/css/position
Since the large post above covers many different SQL approaches for Postgres versions (not only non-9.5 as in the question), I would like to add how to do it in SQLAlchemy if you are using Postgres 9.5. Instead of implementing your own upsert, you can also use SQLAlchemy's functions (which were added in SQLAlchemy 1.1). Personally, I would recommend using these, if possible. Not only because of convenience, but also because it lets PostgreSQL handle any race conditions that might occur.
Cross-posting from another answer I gave yesterday (https://stackoverflow.com/a/44395983/2156909)
SQLAlchemy supports ON CONFLICT
now with two methods on_conflict_do_update()
and on_conflict_do_nothing()
:
Copying from the documentation:
from sqlalchemy.dialects.postgresql import insert
stmt = insert(my_table).values(user_email='[email protected]', data='inserted data')
stmt = stmt.on_conflict_do_update(
index_elements=[my_table.c.user_email],
index_where=my_table.c.user_email.like('%@gmail.com'),
set_=dict(data=stmt.excluded.data)
)
conn.execute(stmt)
Hope this will help someone... Here's a little PHP script I wrote in case you need to copy some columns but not others, and/or the columns are not in the same order on both tables. As long as the columns are named the same, this will work. So if table A has [userid, handle, something] and tableB has [userID, handle, timestamp], then you'd "SELECT userID, handle, NOW() as timestamp FROM tableA", then get the result of that, and pass the result as the first parameter to this function ($z). $toTable is a string name for the table you're copying to, and $link_identifier is the db you're copying to. This is relatively fast for small sets of data. Not suggested that you try to move more than a few thousand rows at a time this way in a production setting. I use this primarily to back up data collected during a session when a user logs out, and then immediately clear the data from the live db to keep it slim.
function mysql_multirow_copy($z,$toTable,$link_identifier) {
$fields = "";
for ($i=0;$i<mysql_num_fields($z);$i++) {
if ($i>0) {
$fields .= ",";
}
$fields .= mysql_field_name($z,$i);
}
$q = "INSERT INTO $toTable ($fields) VALUES";
$c = 0;
mysql_data_seek($z,0); //critical reset in case $z has been parsed beforehand. !
while ($a = mysql_fetch_assoc($z)) {
foreach ($a as $key=>$as) {
$a[$key] = addslashes($as);
next ($a);
}
if ($c>0) {
$q .= ",";
}
$q .= "('".implode(array_values($a),"','")."')";
$c++;
}
$q .= ";";
$z = mysql_query($q,$link_identifier);
return ($q);
}
I worked a little bit the method that Rawling posted here to find more than one line in the same file until the end. This is what worked for me:
foreach (var line in File.ReadLines(pathToFile))
{
if (line.Contains("CustomerEN") && current == null)
{
current = new List<string>();
current.Add(line);
}
else if (line.Contains("CustomerEN") && current != null)
{
current.Add(line);
}
}
string s = String.Join(",", current);
MessageBox.Show(s);
I've built upon the answer above - https://stackoverflow.com/a/11155031/2060486 - to create a shadow around ALL sides..
private static final int GRAY_COLOR_FOR_SHADE = Color.argb(50, 79, 79, 79);
// this method takes a bitmap and draws around it 4 rectangles with gradient to create a
// shadow effect.
public static Bitmap addShadowToBitmap(Bitmap origBitmap) {
int shadowThickness = 13; // can be adjusted as needed
int bmpOriginalWidth = origBitmap.getWidth();
int bmpOriginalHeight = origBitmap.getHeight();
int bigW = bmpOriginalWidth + shadowThickness * 2; // getting dimensions for a bigger bitmap with margins
int bigH = bmpOriginalHeight + shadowThickness * 2;
Bitmap containerBitmap = Bitmap.createBitmap(bigW, bigH, Bitmap.Config.ARGB_8888);
Bitmap copyOfOrigBitmap = Bitmap.createScaledBitmap(origBitmap, bmpOriginalWidth, bmpOriginalHeight, false);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
Canvas canvas = new Canvas(containerBitmap); // drawing the shades on the bigger bitmap
//right shade - direction of gradient is positive x (width)
Shader rightShader = new LinearGradient(bmpOriginalWidth, 0, bigW, 0, GRAY_COLOR_FOR_SHADE,
Color.TRANSPARENT, Shader.TileMode.CLAMP);
paint.setShader(rightShader);
canvas.drawRect(bigW - shadowThickness, shadowThickness, bigW, bigH - shadowThickness, paint);
//bottom shade - direction is positive y (height)
Shader bottomShader = new LinearGradient(0, bmpOriginalHeight, 0, bigH, GRAY_COLOR_FOR_SHADE,
Color.TRANSPARENT, Shader.TileMode.CLAMP);
paint.setShader(bottomShader);
canvas.drawRect(shadowThickness, bigH - shadowThickness, bigW - shadowThickness, bigH, paint);
//left shade - direction is negative x
Shader leftShader = new LinearGradient(shadowThickness, 0, 0, 0, GRAY_COLOR_FOR_SHADE,
Color.TRANSPARENT, Shader.TileMode.CLAMP);
paint.setShader(leftShader);
canvas.drawRect(0, shadowThickness, shadowThickness, bigH - shadowThickness, paint);
//top shade - direction is negative y
Shader topShader = new LinearGradient(0, shadowThickness, 0, 0, GRAY_COLOR_FOR_SHADE,
Color.TRANSPARENT, Shader.TileMode.CLAMP);
paint.setShader(topShader);
canvas.drawRect(shadowThickness, 0, bigW - shadowThickness, shadowThickness, paint);
// starting to draw bitmap not from 0,0 to get margins for shade rectangles
canvas.drawBitmap(copyOfOrigBitmap, shadowThickness, shadowThickness, null);
return containerBitmap;
}
Change the color in the const as you see fit.
Here are TypeScript equivalents of some common .NET delegates:
interface Action<T>
{
(item: T): void;
}
interface Func<T,TResult>
{
(item: T): TResult;
}
If you have anaconda, you can just install desired version and conda will automatically downgrade the current package for you.
For example:
conda install tensorflow=1.1
I have added dataType: 'jsonp' and it works!
$.ajax({
type: 'POST',
crossDomain: true,
dataType: 'jsonp',
url: '',
success: function(jsondata){
}
})
JSONP is a method for sending JSON data without worrying about cross-domain issues. Read More
Adding to the answer from @AndroidUniversity. In a single line you can write it like so:
<component (click)="$event.stopPropagation()"></component>
I'm not sure why I couldn't get Kirtan's example to work for me. It seemed to be failing on empty fields or maybe fields with trailing commas...
This one seems to handle both.
I did not write the parser code, just a wrapper around the parser function to make this work for a file. See attribution.
var Strings = {
/**
* Wrapped CSV line parser
* @param s String delimited CSV string
* @param sep Separator override
* @attribution: http://www.greywyvern.com/?post=258 (comments closed on blog :( )
*/
parseCSV : function(s,sep) {
// http://stackoverflow.com/questions/1155678/javascript-string-newline-character
var universalNewline = /\r\n|\r|\n/g;
var a = s.split(universalNewline);
for(var i in a){
for (var f = a[i].split(sep = sep || ","), x = f.length - 1, tl; x >= 0; x--) {
if (f[x].replace(/"\s+$/, '"').charAt(f[x].length - 1) == '"') {
if ((tl = f[x].replace(/^\s+"/, '"')).length > 1 && tl.charAt(0) == '"') {
f[x] = f[x].replace(/^\s*"|"\s*$/g, '').replace(/""/g, '"');
} else if (x) {
f.splice(x - 1, 2, [f[x - 1], f[x]].join(sep));
} else f = f.shift().split(sep).concat(f);
} else f[x].replace(/""/g, '"');
} a[i] = f;
}
return a;
}
}
In addition to Chris B's answer, if you need to use echo
anyway, still want to keep it simple and structured and don't want to spam the code with <?php stuff; ?>
's, you can use the syntax below.
For example you want to display the images of a gallery:
foreach($images as $image)
{
echo
'<li>',
'<a href="', site_url(), 'images/', $image['name'], '">',
'<img ',
'class="image" ',
'title="', $image['title'], '" ',
'src="', site_url(), 'images/thumbs/', $image['filename'], '" ',
'alt="', $image['description'], '"',
'>',
'</a>',
'</li>';
}
Echo takes multiple parameters so with good indenting it looks pretty good. Also using echo
with parameters is more effective than concatenating.
While I would have gone with Piotr's answer (because it's all in one line), I was surprised that your sample is closer to your solution than you think. From what you have, you simply assign the model value before you use the Html helper method.
@{Model.RequiredProperty = "default";}
@Html.HiddenFor(model => model.RequiredProperty)
we can add attribute width directly to th
eg:
<ng-container matColumnDef="position" >
<th mat-header-cell *matHeaderCellDef width ="20%"> No. </th>
<td mat-cell *matCellDef="let element"> {{element.position}} </td>
</ng-container>
For API level 26+
String encodedString = Base64.getEncoder().encodeToString(byteArray);
Ref: https://developer.android.com/reference/java/util/Base64.Encoder.html#encodeToString(byte[])
I think I just ran into a similar issue where I was trying to center a login box (like the gmail login box). When resizing the window, the center box would overflow out of the browser window (top) as soon as the browser window became smaller than the box. Because of this, in a small window, even when scrolling up, the top content was lost.
I was able to fix this by replacing the centering method I used by the "margin: auto" way of centering the box in its container. This prevents the box from overflowing in my case, keeping all content available. (minimum margin seems to be 0).
Good Luck !
edit: margin: auto only works to vertically center something if the parent element has its display property set to "flex".
You can also use array_keys for number of occurrences
<?php
$array=array('1','2','6','6','6','5');
$i=count(array_keys($array, 6));
if($i>0)
echo "Element exists in Array";
?>
In this Eclipse Preferences panel you can change the compiler compatibility from 1.7 to 1.6. This solved the similar message I was getting. For Eclipse, it is under: Preferences -> Java -> Compiler: 'Compiler compliance level'
We can handle the different windows by moving between named windows using the “switchTo” method:
driver.switch_to.window("windowName")
<a href="somewhere.html" target="windowName">Click here to open a new window</a>
Alternatively, you can pass a “window handle” to the “switchTo().window()” method. Knowing this, it’s possible to iterate over every open window like so:
for handle in driver.window_handles:
driver.switch_to.window(handle)
Building upon @Mark D's answer I would use web.config transforms to set all the various cookies to Secure. This includes setting anonymousIdentification cookieRequireSSL
and httpCookies requireSSL
.
To that end you'd setup your web.Release.config as:
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<system.web>
<httpCookies xdt:Transform="SetAttributes(httpOnlyCookies)" httpOnlyCookies="true" />
<httpCookies xdt:Transform="SetAttributes(requireSSL)" requireSSL="true" />
<anonymousIdentification xdt:Transform="SetAttributes(cookieRequireSSL)" cookieRequireSSL="true" />
</system.web>
</configuration>
If you're using Roles and Forms Authentication with the ASP.NET Membership Provider
(I know, it's ancient) you'll also want to set the roleManager cookieRequireSSL
and the forms requireSSL
attributes as secure too. If so, your web.release.config might look like this (included above plus new tags for membership API):
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<system.web>
<httpCookies xdt:Transform="SetAttributes(httpOnlyCookies)" httpOnlyCookies="true" />
<httpCookies xdt:Transform="SetAttributes(requireSSL)" requireSSL="true" />
<anonymousIdentification xdt:Transform="SetAttributes(cookieRequireSSL)" cookieRequireSSL="true" />
<roleManager xdt:Transform="SetAttributes(cookieRequireSSL)" cookieRequireSSL="true" />
<authentication>
<forms xdt:Transform="SetAttributes(requireSSL)" requireSSL="true" />
</authentication>
</system.web>
</configuration>
Background on web.config transforms here: http://go.microsoft.com/fwlink/?LinkId=125889
Obviously this goes beyond the original question of the OP but if you don't set them all to secure you can expect that a security scanning tool will notice and you'll see red flags appear on the report. Ask me how I know. :)
Re: aku, izb, John Topley...
Watch out for mutability issues...
It may seem sensible to omit getters/setters. It actually may be ok in some cases. The real problem with the proposed pattern shown here is mutability.
The problem is once you pass an object reference out containing non-final, public fields. Anything else with that reference is free to modify those fields. You no longer have any control over the state of that object. (Think what would happen if Strings were mutable.)
It gets bad when that object is an important part of the internal state of another, you've just exposed internal implementation. To prevent this, a copy of the object must be returned instead. This works, but can cause massive GC pressure from tons of single-use copies created.
If you have public fields, consider making the class read-only. Add the fields as parameters to the constructor, and mark the fields final. Otherwise make sure you're not exposing internal state, and if you need to construct new instances for a return value, make sure it won't be called excessively.
See: "Effective Java" by Joshua Bloch -- Item #13: Favor Immutability.
PS: Also keep in mind, all JVMs these days will optimize away the getMethod if possible, resulting in just a single field-read instruction.
For me I had to specify path in my NodeJS file.
// did not work!!!!!
require('dotenv').config()
instead
// DID WORK!!
require('dotenv').config({ path: '/full/custom/path/to/your/.env' })
You can use int casting which allows the base specification.
int(b, 2) # Convert a binary string to a decimal int.
Use the other encode
method in URLEncoder:
URLEncoder.encode(String, String)
The first parameter is the text to encode; the second is the name of the character encoding to use (e.g., UTF-8
). For example:
System.out.println(
URLEncoder.encode(
"urlParameterString",
java.nio.charset.StandardCharsets.UTF_8.toString()
)
);
You can pass an array as the first AutoFilter argument and use the xlFilterValues operator.
This will display PDF, DOC and DOCX filetypes.
Criteria1:=Array(".pdf", ".doc", ".docx"), Operator:=xlFilterValues
Change <button type="button"
to <button type="submit"
. Remove the onClick
. Instead do <form className="commentForm" onSubmit={this.onFormSubmit}>
. This should catch clicking the button and pressing the return key.
onFormSubmit = e => {
e.preventDefault();
const { name, email } = this.state;
// send to server with e.g. `window.fetch`
}
...
<form onSubmit={this.onFormSubmit}>
...
<button type="submit">Submit</button>
</form>
This task can be accomplished without blueprints and tricky imports using Centralized URL Map
app.py
import views
from flask import Flask
app = Flask(__name__)
app.add_url_rule('/', view_func=views.index)
app.add_url_rule('/other', view_func=views.other)
if __name__ == '__main__':
app.run(debug=True, use_reloader=True)
views.py
from flask import render_template
def index():
return render_template('index.html')
def other():
return render_template('other.html')
If you know the parameters that are being passed and if you don't have access to make sp_configure, then edit the stored procedure with these parameters and the same can be stored in a ##global table.
For passing both a function, and any arguments to the function:
from typing import Callable
def looper(fn: Callable, n:int, *args, **kwargs):
"""
Call a function `n` times
Parameters
----------
fn: Callable
Function to be called.
n: int
Number of times to call `func`.
*args
Positional arguments to be passed to `func`.
**kwargs
Keyword arguments to be passed to `func`.
Example
-------
>>> def foo(a:Union[float, int], b:Union[float, int]):
... '''The function to pass'''
... print(a+b)
>>> looper(foo, 3, 2, b=4)
6
6
6
"""
for i in range(n):
fn(*args, **kwargs)
Depending on what you are doing, it could make sense to define a decorator
, or perhaps use functools.partial
.
Regarding the width and height:
var img = document.getElementById('imageId');
var width = img.clientWidth;
var height = img.clientHeight;
Regarding the filesize you can use performance
var size = performance.getEntriesByName(url)[0];
console.log(size.transferSize); // or decodedBodySize might differ if compression is used on server side
There is BrockSoft VSAid. This is mainly used for finding files in a solution.
Bootstrap provides the following function:
| This event is fired immediately when the hide instance method hide.bs.dropdown | has been called. The toggling anchor element is available as the | relatedTarget property of the event.
Therefore, implementing this function should be able to disable the dropdown from closing.
$('#myDropdown').on('hide.bs.dropdown', function (e) {
var target = $(e.target);
if(target.hasClass("keepopen") || target.parents(".keepopen").length){
return false; // returning false should stop the dropdown from hiding.
}else{
return true;
}
});
You can only use the window.close
function when you have opened the window using window.open()
, so I use the following function:
function close_window(url){
var newWindow = window.open('', '_self', ''); //open the current window
window.close(url);
}
dex2jar with jd-gui will give all the java source files but they are not exactly the same. They are almost equivalent .class files (not 100%). So if you want to change the code for an apk file:
decompile using apktool
apktool will generate smali(Assembly version of dex) file for every java file with same name.
smali is human understandable, make changes in the relevant file,
recompile using same apktool(apktool b Nw.apk <Folder Containing Modified Files>
)
The 487 Response indicates that the previous request was terminated by user/application action. The most common occurrence is when the CANCEL happens as explained above. But it is also not limited to CANCEL. There are other cases where such responses can be relevant. So it depends on where you are seeing this behavior and whether its a user or application action that caused it.
15.1.2 UAS Behavior==> BYE Handling in RFC 3261
The UAS MUST still respond to any pending requests received for that dialog. It is RECOMMENDED that a 487 (Request Terminated) response be generated to those pending requests.
I experienced same issue on MAC catalina 10.15 what you add in .bash_profile is not recognised when you echo it on terminal, it is stored temporarily. It is recommended to use .zprofile for permanent and add all environment variables in it.After trying for 5hours i found out this solution. Hope it will be useful for someone.
vi .zprofile
insert(press i)
export ANDROID_HOME=/Users/mypc/Library/Android/sdk
export PATH=$ANDROID_HOME/platform-tools:${PATH}
after adding environment variables press esc
then enter :wq!
try echo $ANDROID_HOME in new tab(it will not be empty) path will be
printed
In addition to the solution you accepted, you could also implement the special __lt__()
("less than") method on the class. The sort()
method (and the sorted()
function) will then be able to compare the objects, and thereby sort them. This works best when you will only ever sort them on this attribute, however.
class Foo(object):
def __init__(self, score):
self.score = score
def __lt__(self, other):
return self.score < other.score
l = [Foo(3), Foo(1), Foo(2)]
l.sort()
model.find({Branch:branch},function (err, docs){
if (err) res.send(err)
res.send(JSON.parse(JSON.stringify(docs)))
});
No magic involved, just subtract from the offset top of the element
$('html, body').animate({scrollTop: $('#contact').offset().top -100 }, 'slow');
Based on what I read from different sources:
An await
expression does not block the thread on which it is executing. Instead, it causes the compiler to sign up the rest of the async
method as a continuation on the awaited task. Control then returns to the caller of the async
method. When the task completes, it invokes its continuation, and execution of the async
method resumes where it left off.
To wait for a single task
to complete, you can call its Task.Wait
method. A call to the Wait
method blocks the calling thread until the single class instance has completed execution. The parameterless Wait()
method is used to wait unconditionally until a task completes. The task simulates work by calling the Thread.Sleep
method to sleep for two seconds.
This article is also a good read.
Let's go over the basics: "Accessor" and "Mutator" are just fancy names fot a getter and a setter. A getter, "Accessor", returns a class's variable or its value. A setter, "Mutator", sets a class variable pointer or its value.
So first you need to set up a class with some variables to get/set:
public class IDCard
{
private String mName;
private String mFileName;
private int mID;
}
But oh no! If you instantiate this class the default values for these variables will be meaningless. B.T.W. "instantiate" is a fancy word for doing:
IDCard test = new IDCard();
So - let's set up a default constructor, this is the method being called when you "instantiate" a class.
public IDCard()
{
mName = "";
mFileName = "";
mID = -1;
}
But what if we do know the values we wanna give our variables? So let's make another constructor, one that takes parameters:
public IDCard(String name, int ID, String filename)
{
mName = name;
mID = ID;
mFileName = filename;
}
Wow - this is nice. But stupid. Because we have no way of accessing (=reading) the values of our variables. So let's add a getter, and while we're at it, add a setter as well:
public String getName()
{
return mName;
}
public void setName( String name )
{
mName = name;
}
Nice. Now we can access mName
. Add the rest of the accessors and mutators and you're now a certified Java newbie.
Good luck.
You can use Getfv.co :
To retrieve a favicon you can hotlink it at... http://g.etfv.co/[URL]
Example for this page : http://g.etfv.co/https://stackoverflow.com/questions/5119041/how-can-i-get-a-web-sites-favicon
Download content and let's go !
Edit :
Getfv.co and fvicon.com look dead. If you want I found a non free alternative : grabicon.com.
According to @zombat's answer, it's better to validate the Anonymous Functions first:
function exampleMethod($anonFunc) {
//execute anonymous function
if (is_callable($anonFunc)) {
$anonFunc();
}
}
Or validate argument type since PHP 5.4.0:
function exampleMethod(callable $anonFunc) {}
I've found another easy way to deal with this problem, you just need the attribute " connectToSortable:" to draggable like as below code:
$("#a1,#a2").draggable({
connectToSortable: "#b,#a",
revert: 'invalid',
});
PS: More detail and example
How to move Draggable objects between source area and target area with jQuery
def xstr(s):
return {None:''}.get(s, s)
Here's a quick example on how to use the Selector
class on Swift:
override func viewDidLoad() {
super.viewDidLoad()
var rightButton = UIBarButtonItem(title: "Title", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("method"))
self.navigationItem.rightBarButtonItem = rightButton
}
func method() {
// Something cool here
}
Note that if the method passed as a string doesn't work, it will fail at runtime, not compile time, and crash your app. Be careful
Miss Clone: I get a fresh copy to local.
Mr Pull: I already have it locally, I just update it.
Miss Clone: I can do what you do! You are just my subset.
Mr Pull: Ditto!
Miss Clone: No, you don't create. This is what I do:
You only do #3, and then you merge, which I do not need to do(mine is fresh).
Mr Pull: Smarty pants, no big deal, I will do a "git init" first! Then we are the same.
Miss Clone: No dear, don't you need a 'checked-out branch'... the git checkout
? Who will do it? me!
Mr Pull: Oh right, that is needed. I need a default branch to act on. But..but I have the extra 'merge' capability on existing repo! Which makes me the most used command in Git ;)
Git creators: Hold your horses Mr Pull, if --bare or --mirror is used with clone or init, your merge won't happen. It remains read-only. And for you Miss Clone, git checkout
can be replaced with a git fetch <remote> <srcBranch>:<destBranch>
unless you want to use a -s <strategy>
with pull which is missing in fetch.
Miss Clone: Somehow I feel like a winner already but let me drop this too: my command applies to all the branches in the repository. Are you that broad minded Mr. Pull?
Mr. Pull: I am broad minded when it comes to fetching all the branch names from the repo. But the merge will happen only on the current checked out branch. Exclusivity is the name! And in your case too, you only check-out one branch.
Lea Verous solution is good but i wanted more control over the position of the bullets so this is my approach:
.entry ul {
list-style: none;
padding: 0;
margin: 0;
/* hide overflow in the case of floating elements around ... */
overflow: hidden;
}
.entry li {
position: relative;
padding-left: 24px;
}
.entry li:before {
/* with absolute position you can move this around or make it bigger without getting unwanted scrollbars */
position: absolute;
content: "• ";
color: #E94E24;
font-size: 30px;
left: 0;
/* use fonts like "arial" or use "sans-serif" to make the dot perfect round */
font-family: Arial, sans-serif;
}
I'd suggest using the request module. Downloading a file is as simple as the following code:
var fs = require('fs'),
request = require('request');
var download = function(uri, filename, callback){
request.head(uri, function(err, res, body){
console.log('content-type:', res.headers['content-type']);
console.log('content-length:', res.headers['content-length']);
request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
});
};
download('https://www.google.com/images/srpr/logo3w.png', 'google.png', function(){
console.log('done');
});
concat()
, of course, can be used with 2 dimensional arrays as well. No looping required.
var a = [ [1, 2], [3, 4] ];
var b = [ ["a", "b"], ["c", "d"] ];
b = b.concat(a);
alert(b[2][1]); // result 2
I was getting the same error but solved it finally,actually i was not setting the Object Entity which is already saved to the other entity and hence the Object value it was getting for foreeign key was null.
I know this question has already been answered. However, for those using spring boot, this link helped me - https://smarterco.de/java-load-file-classpath-spring-boot/
However, the resourceLoader.getResource("classpath:file.txt").getFile();
was causing this problem and sbk's comment:
That's it. A java.io.File represents a file on the file system, in a directory structure. The Jar is a java.io.File. But anything within that file is beyond the reach of java.io.File. As far as java is concerned, until it is uncompressed, a class in jar file is no different than a word in a word document.
helped me understand why to use getInputStream()
instead. It works for me now!
Thanks!
You can use the LIKE operator to compare the content of a T-SQL string, e.g.
SELECT * FROM [table] WHERE [field] LIKE '%stringtosearchfor%'.
The percent character '%' is a wild card- in this case it says return any records where [field] at least contains the value "stringtosearchfor".
In addition to the answers above:
If you created/edited your .sh script file in Windows, make sure it was saved with line ending in Unix format. By default many editors in Windows will convert Unix line endings to Windows format and Linux will not recognize shebang (#!/bin/sh) at the beginning of the file. So Linux will produce the error message like if there is no shebang.
Tips:
The problem is that Xcode, especially Xcode 10.x, has not installed everything, so ensure the command line tools are installed, type this in a terminal shell:
xcode-select --install
also start Xcode and ensure all the required installation is installed ( you should get prompted if it is not.) and since Xcode 10 does not install the full Mac OS SDK, run the installer at
/Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
as this package is not installed by Xcode 10.
If you work with developers, often get a sliver of code that is formatted as one long line of code, then sql pretty printer add-on for SQL Server management Studio may helps a lot with more than 60+ formatter options. http://www.dpriver.com/sqlpp/ssmsaddin.html
Swift 2.0:
Make constant enum values in a empty Swift file.
// AppRef.swift
import UIKit
import Foundation
enum UILabelTextPositions : String {
case VERTICAL_ALIGNMENT_TOP = "VerticalAlignmentTop"
case VERTICAL_ALIGNMENT_MIDDLE = "VerticalAlignmentMiddle"
case VERTICAL_ALIGNMENT_BOTTOM = "VerticalAlignmentBottom"
}
Using UILabel Extension:
Make a empty Swift class and name it. Add the following
// AppExtensions.swift
import Foundation
import UIKit
extension UILabel{
func makeLabelTextPosition (sampleLabel :UILabel?, positionIdentifier : String) -> UILabel
{
let rect = sampleLabel!.textRectForBounds(bounds, limitedToNumberOfLines: 0)
switch positionIdentifier
{
case "VerticalAlignmentTop":
sampleLabel!.frame = CGRectMake(bounds.origin.x+5, bounds.origin.y, rect.size.width, rect.size.height)
break;
case "VerticalAlignmentMiddle":
sampleLabel!.frame = CGRectMake(bounds.origin.x+5,bounds.origin.y + (bounds.size.height - rect.size.height) / 2,
rect.size.width, rect.size.height);
break;
case "VerticalAlignmentBottom":
sampleLabel!.frame = CGRectMake(bounds.origin.x+5, bounds.origin.y + (bounds.size.height - rect.size.height),rect.size.width, rect.size.height);
break;
default:
sampleLabel!.frame = bounds;
break;
}
return sampleLabel!
}
}
Usage :
myMessageLabel.makeLabelTextPosition(messageLabel, positionIdentifier: UILabelTextPositions.VERTICAL_ALIGNMENT_TOP.rawValue)
If you want to submit a form using Javascript FormData API with uploading files you need to set below two options:
processData: false,
contentType: false
You can try as follows:
//Ajax Form Submission
$(document).on("click", ".afs", function (e) {
e.preventDefault();
e.stopPropagation();
var thisBtn = $(this);
var thisForm = thisBtn.closest("form");
var formData = new FormData(thisForm[0]);
//var formData = thisForm.serializeArray();
$.ajax({
type: "POST",
url: "<?=base_url();?>assignment/createAssignment",
data: formData,
processData: false,
contentType: false,
success:function(data){
if(data=='yes')
{
alert('Success! Record inserted successfully');
}
else if(data=='no')
{
alert('Error! Record not inserted successfully')
}
else
{
alert('Error! Try again');
}
}
});
});
For those who reached this post for Answer:
This happens mainly because the InputStream
the DOM parser is consuming is empty
So in what I ran across, there might be two situations:
InputStream
you passed into the parser has been used and thus emptied.File
or whatever you created the InputStream
from may be an empty file or string or whatever. The emptiness might be the reason caused the problem. So you need to check your source of the InputStream
.The Law of Leaky Abstractions by Joel Spolsky
http://www.joelonsoftware.com/articles/LeakyAbstractions.html
On Windows ngrok.cmd works well from Git Bash, not ngrok
This is way late but in-case someone finds this helpful.
You could use list comprehension.
rand = [random.randint(0, 100) for x in range(1, 11)]
print(rand)
Output:
[974, 440, 305, 102, 822, 128, 205, 362, 948, 751]
Cheers!
You have an error in your syntax here:
this._possessions = new Thing[100]();
This doesn't create an "array of things". To create an array of things, you can simply use the array literal expression:
this._possessions = [];
Of the array constructor if you want to set the length:
this._possessions = new Array(100);
I have created a brief working example you can try in the playground.
module Entities {
class Thing {
}
export class Person {
private _name: string;
private _possessions: Thing[];
private _mostPrecious: Thing;
constructor (name: string) {
this._name = name;
this._possessions = [];
this._possessions.push(new Thing())
this._possessions[100] = new Thing();
}
}
}
Not that I know of. But you can configure Firefox to automatically start the download and save the file in a specific place. Your test could then check that the file actually arrived.
Both Redirect::to()
and Redirect::away()
should work.
Difference
Redirect::to() does additional URL checks and generations. Those additional steps are done in Illuminate\Routing\UrlGenerator and do the following, if the passed URL is not a fully valid URL (even with protocol):
Determines if URL is secure rawurlencode() the URL trim() URL
src : https://medium.com/@zwacky/laravel-redirect-to-vs-redirect-away-dd875579951f
One approach is to do that using the String class itself. Let's say that your string is something like that:
String s = "some text";
boolean hasNonAlpha = s.matches("^.*[^a-zA-Z0-9 ].*$");
one other is to use an external library, such as Apache commons:
String s = "some text";
boolean hasNonAlpha = !StringUtils.isAlphanumeric(s);
In my case, I fixed by the following:
* run git config --edit
* In the git config file:
[branch "master"]
remote = origin # <--- change the default origin here
If the div has some content inside, this will be the best practice to have a line over or under the div and maintaining the content spacing with the div
.div_line_bottom{
border-bottom: 1px solid #ff0000;
padding-bottom:20px;
}
.div_line_top{
border-top: 1px solid #ff0000;
padding-top:20px;
}
Following on from @Ryan Reich's answer, I thought I'd offer my cleaned up version. The first bounds check isn't required given the second bounds check, and I've made it iterative rather than recursive. It returns values in the range [min, max], where max >= min
and 1+max-min < RAND_MAX
.
unsigned int rand_interval(unsigned int min, unsigned int max)
{
int r;
const unsigned int range = 1 + max - min;
const unsigned int buckets = RAND_MAX / range;
const unsigned int limit = buckets * range;
/* Create equal size buckets all in a row, then fire randomly towards
* the buckets until you land in one of them. All buckets are equally
* likely. If you land off the end of the line of buckets, try again. */
do
{
r = rand();
} while (r >= limit);
return min + (r / buckets);
}
No it is not possible, hence your runtime error.
But you can assign an instance of a derived class to a variable of base class type.
Way late, but I just ran into a similar issue.
My solution was pseudo elements - no additional markup, and you get to draw the border without affecting the width.
Position the pseudo element absolutely (with the main positioned relatively) and whammo.
See below, JSFiddle here.
.hello {
position: relative;
/* Styling not important */
background: black;
color: white;
padding: 20px;
width: 200px;
height: 200px;
}
.hello::before {
content: "";
position: absolute;
display: block;
top: 0;
left: -5px;
right: -5px;
bottom: 0;
border-left: 5px solid red;
border-right: 5px solid red;
z-index: -1;
}
best solution
install aria2c in system &
echo exec("aria2c \"$url\"")
In v2.0 of the Graph API, calling /me/friends
returns the person's friends who also use the app.
In addition, in v2.0, you must request the user_friends
permission from each user. user_friends
is no longer included by default in every login. Each user must grant the user_friends
permission in order to appear in the response to /me/friends
. See the Facebook upgrade guide for more detailed information, or review the summary below.
The /me/friendlists
endpoint and user_friendlists
permission are not what you're after. This endpoint does not return the users friends - its lets you access the lists a person has made to organize their friends. It does not return the friends in each of these lists. This API and permission is useful to allow you to render a custom privacy selector when giving people the opportunity to publish back to Facebook.
If you want to access a list of non-app-using friends, there are two options:
If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends
API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.
If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends
endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.
In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends
permission).
For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.
MySQL will also report "Column count doesn't match value count at row 1" if you try to insert multiple rows without delimiting the row sets in the VALUES section with parentheses, like so:
INSERT INTO `receiving_table`
(id,
first_name,
last_name)
VALUES
(1002,'Charles','Babbage'),
(1003,'George', 'Boole'),
(1001,'Donald','Chamberlin'),
(1004,'Alan','Turing'),
(1005,'My','Widenius');
The brackets that are commonly used in the mysql documentation for examples should be ommitted in a 'real' query.
It also doesn't appear that you're echoing the result of the mysql query anywhere. mysql_query returns a mysql resource on success. The php manual page also includes instructions on how to load the mysql result resource into an array for echoing and other manipulation.
<asp:Label ID="ServiceBeginDate" runat="server" Text='<%# (DataBinder.Eval(Container.DataItem, "ServiceBeginDate", "{0:yyyy}") == "0001") ? "" : DataBinder.Eval(Container.DataItem, "ServiceBeginDate", "{0:MM/dd/yyyy}") %>'>
</asp:Label>
I quite like the improved objects function developed by Dirk. Much of the time though, a more basic output with the object name and size is sufficient for me. Here's a simpler function with a similar objective. Memory use can be ordered alphabetically or by size, can be limited to a certain number of objects, and can be ordered ascending or descending. Also, I often work with data that are 1GB+, so the function changes units accordingly.
showMemoryUse <- function(sort="size", decreasing=FALSE, limit) {
objectList <- ls(parent.frame())
oneKB <- 1024
oneMB <- 1048576
oneGB <- 1073741824
memoryUse <- sapply(objectList, function(x) as.numeric(object.size(eval(parse(text=x)))))
memListing <- sapply(memoryUse, function(size) {
if (size >= oneGB) return(paste(round(size/oneGB,2), "GB"))
else if (size >= oneMB) return(paste(round(size/oneMB,2), "MB"))
else if (size >= oneKB) return(paste(round(size/oneKB,2), "kB"))
else return(paste(size, "bytes"))
})
memListing <- data.frame(objectName=names(memListing),memorySize=memListing,row.names=NULL)
if (sort=="alphabetical") memListing <- memListing[order(memListing$objectName,decreasing=decreasing),]
else memListing <- memListing[order(memoryUse,decreasing=decreasing),] #will run if sort not specified or "size"
if(!missing(limit)) memListing <- memListing[1:limit,]
print(memListing, row.names=FALSE)
return(invisible(memListing))
}
And here is some example output:
> showMemoryUse(decreasing=TRUE, limit=5)
objectName memorySize
coherData 713.75 MB
spec.pgram_mine 149.63 kB
stoch.reg 145.88 kB
describeBy 82.5 kB
lmBandpass 68.41 kB
The $
is just a function. It is actually an alias for the function called jQuery
, so your code can be written like this with the exact same results:
jQuery('#Text').click(function () {
jQuery('#Text').css('color', 'red');
});
Go to "Tomcat Directory"/bin directory
if Linux then create setenv.sh else if Windows then create setenv.bat
content of setenv.* file :
export CATALINA_OPTS="$CATALINA_OPTS -Xms512m"
export CATALINA_OPTS="$CATALINA_OPTS -Xmx8192m"
export CATALINA_OPTS="$CATALINA_OPTS -XX:MaxPermSize=256m"
after this restart tomcat with new params.
explanation and full information is here
http://crunchify.com/how-to-change-jvm-heap-setting-xms-xmx-of-tomcat/
Find the below code to make visible the view in Circuler reveal, if you send true, it'll get Invisible/Gone. If you send false, it'll get visible. anyView is the view you're going to visible/hide, it could be any view (Layouts, Buttons etc)
private fun toggle(flag: Boolean, anyView: View) {
if (flag) {
val cx = anyView.width / 2
val cy = anyView.height / 2
val initialRadius = Math.hypot(cx.toDouble(), cy.toDouble()).toFloat()
val anim = ViewAnimationUtils.createCircularReveal(anyView, cx, cy, initialRadius, 0f)
anim.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
super.onAnimationEnd(animation)
anyView.visibility = View.INVISIBLE
}
})
anim.start()
} else {
val cx = anyView.width / 2
val cy = anyView.height / 2
val finalRadius = Math.hypot(cx.toDouble(), cy.toDouble()).toFloat()
val anim = ViewAnimationUtils.createCircularReveal(anyView, cx, cy, 0f, finalRadius)
anyView.visibility = View.VISIBLE
anim.start()
}
}
If you need to add two strings you have to use the '+' operator
hence
msg['Subject'] = 'your string' + sys.argv[1]
and also you have to import sys in the beginning
as
import sys
msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]
Java supports shallow(not deep) copy concept
You can archive it using:
clone()
putAll()
It seems to me that your Hibernate libraries are not found (NoClassDefFoundError: org/hibernate/boot/archive/scan/spi/ScanEnvironment
as you can see above).
Try checking to see if Hibernate core is put in as dependency:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.11.Final</version>
<scope>compile</scope>
</dependency>
In eclipse go to
Window-> Java -> Installed JREs
You can remove your current installed jre and add the jdk by specifying the path to where the jdk is installed.
All you'd need in your case is:
return expression;
The reason why is that the expression itself evaluates to a boolean value of true
or false
, so it's redundant to have an if
block (or even a ?:
operator).
You can subscribe to the event:
ie)
FB.Event.subscribe('auth.login', function(response) {
FB.api('/me', function(response) {
alert(response.name);
});
});
From Oracle DB 12c Release 2
you could use VALIDATE_CONVERSION function:
VALIDATE_CONVERSION determines whether expr can be converted to the specified data type. If expr can be successfully converted, then this function returns 1; otherwise, this function returns 0. If expr evaluates to null, then this function returns 1. If an error occurs while evaluating expr, then this function returns the error.
IF (VALIDATE_CONVERSION(value AS NUMBER) = 1) THEN
...
END IF;
Another option would be to simply copy & drop the column:
df = pd.DataFrame(d)
df['new_name'] = df['two']
df = df.drop('two', axis=1)
df.head()
After that you get the result:
one three new_name
0 1 a 9
1 2 b 8
2 3 c 7
3 4 d 6
4 5 e 5
You use xsi:nil
when your schema semantics indicate that an element has a default value, and that the default value should be used if the element isn't present. I have to assume that there are smart people to whom the preceding sentence is not a self-evidently terrible idea, but it sounds like nine kinds of bad to me. Every XML format I've ever worked with represents null values by omitting the element. (Or attribute, and good luck marking an attribute with xsi:nil
.)
How to do through Source Tree
1: Open SourceTree, click on Repository -> Checkout
2: Click on Create New Branch
3: Select the branch where you want to get code for new branch
4: Give your branch name
5: Push the branch (by click on Push-button)
Write the telnet session inside a BAT Dos file and execute.
On a current netcat (v0.7.1) you have a -c switch:
-c, --close close connection on EOF from stdin
Hence,
echo "hi" | nc -cu localhost 8000
should do the trick.
Set to true android:layout_alignParentTop="true"
and android:layout_centerHorizontal="true"
in the Button, like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="@+id/switch_flashlight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/turn_on_flashlight"
android:textColor="@android:color/black"
android:onClick="action_trn"
android:background="@android:color/holo_green_light"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:padding="5dp" />
</RelativeLayout>
To do this via TSQL (ssms query window or sqlcmd.exe) just run:
RESTORE DATABASE MyDatabase FROM DISK='c:\backups\MyDataBase1.bak'
To do it via GUI - open SSMS, right click on Databases and follow the steps below
That is exactly what you do with an advanced filter. If it's a one shot, you don't even need a macro, it is available in the Data menu.
Sheets("Sheet1").Range("A1:D17").AdvancedFilter Action:=xlFilterCopy, _
CriteriaRange:=Sheets("Sheet1").Range("G1:G2"), CopyToRange:=Range("A1:D1") _
, Unique:=False
For more explanation read THIS LINK
, it is option of Babel compiler
that commands to not include superfluous whitespace characters and line terminators. some times ago its threshold was 100KB
but now is 500KB
.
I proffer you disable this option in your development environment, with this code in .babelrc
file.
{
"env": {
"development" : {
"compact": false
}
}
}
For production environment Babel
use the default config which is auto
.
If you are using a GUI and you are still getting the same problem. Just leave the size value empty, the primary key defaults the value to 11, you should be fine with this. Worked with Bitnami phpmyadmin.
I've just spent a while trying to get this to work an have a written a Ruby gem that accesses the API. You can read more on it's project page.
This is working code in Ruby:
require 'savon'
client = Savon::Client.new do
wsdl.document = "http://realtime.nationalrail.co.uk/LDBWS/wsdl.aspx"
end
response = client.request 'http://thalesgroup.com/RTTI/2012-01-13/ldb/GetDepartureBoard' do
namespaces = {
"xmlns:soap" => "http://schemas.xmlsoap.org/soap/envelope/",
"xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance",
"xmlns:xsd" => "http://www.w3.org/2001/XMLSchema"
}
soap.xml do |xml|
xml.soap(:Envelope, namespaces) do |xml|
xml.soap(:Header) do |xml|
xml.AccessToken do |xml|
xml.TokenValue('ENTER YOUR TOKEN HERE')
end
end
xml.soap(:Body) do |xml|
xml.GetDepartureBoardRequest(xmlns: "http://thalesgroup.com/RTTI/2012-01-13/ldb/types") do |xml|
xml.numRows(10)
xml.crs("BHM")
xml.filterCrs("BHM")
xml.filterType("to")
end
end
end
end
end
p response.body
Hope that's helpful for someone!
.NET is seeing an invalid SSL certificate on the other end of the connection. There is a workaround for it, but obviously not recommended for production code:
// Put this somewhere that is only once - like an initialization method
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateCertificate);
...
static bool ValidateCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
in PHP-Fusion Open Source CMS, http://www.php-fusion.co.uk, we do it this way at core -
<?php
ob_start();
// Your PHP codes here
?>
YOUR HTML HERE
<?php
$html_output = ob_get_contents();
ob_end_clean();
echo $html_output;
?>
You won't be able to see anything loading one by one. The only loader will be your browser tab spinner, and it just displays everything in an instant after everything is loaded. Give it a try.
This method is fully compliant in html files.
Generate the object files with gcc, then use ar
to bundle them into a static library.
The Dragon Book is definitely the "building compilers" book, but if your language isn't quite as complicated as the current generation of languages, you may want to look at the Interpreter pattern from Design Patterns.
The example in the book designs a regular expression-like language and is well thought through, but as they say in the book, it's good for thinking through the process but is effective really only on small languages. However, it is much faster to write an Interpreter for a small language with this pattern than having to learn about all the different types of parsers, yacc and lex, et cetera...
In most cases (including this one), return
will exit immediately. However, if the return is in a try
block with an accompanying finally
block, the finally
always executes and can "override" the return
in the try
.
function foo() {
try {
for (var i = 0; i < 10; i++) {
if (i % 3 == 0) {
return i; // This executes once
}
}
} finally {
return 42; // But this still executes
}
}
console.log(foo()); // Prints 42
No, but you can do this almost as easily.
Go here:
https://romannurik.github.io/AndroidAssetStudio/
Build your icons using that page, and then download the zip package. Unzip it into the right directory and it'll overwrite all the drawable-*/ic_launcher.png correctly.
One idea would be to winsorize the data in a two-pass procedure:
run a first pass, learn what the bounds are, e.g. cut of at given percentile, or N standard deviation above the mean, or ...
in a second pass, set the values beyond the given bound to the value of that bound
I should stress that this is an old-fashioned method which ought to be dominated by more modern robust techniques but you still come across it a lot.
As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:
var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da
For Node.js v5.11.1 and below
Construct a new Buffer
and pass 'base64'
as the second argument:
var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da
If you want to be clean, you can check whether from
exists :
if (typeof Buffer.from === "function") {
// Node 5.10+
buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
// older Node versions, now deprecated
buf = new Buffer(b64string, 'base64'); // Ta-da
}
This works for me without throwing an exception:
package com.sandbox;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Sandbox {
public static void main(String[] args) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
Date parsed = format.parse("20110210");
java.sql.Date sql = new java.sql.Date(parsed.getTime());
}
}
I prefer to use java.util.Scanner
:
try {
Scanner scanner = new Scanner(context.openFileInput(filename)).useDelimiter("\\Z");
StringBuilder sb = new StringBuilder();
while (scanner.hasNext()) {
sb.append(scanner.next());
}
scanner.close();
String result = sb.toString();
} catch (IOException e) {}
If you are looking for NA
counts for each column in a dataframe then:
na_count <-sapply(x, function(y) sum(length(which(is.na(y)))))
should give you a list with the counts for each column.
na_count <- data.frame(na_count)
Should output the data nicely in a dataframe like:
----------------------
| row.names | na_count
------------------------
| column_1 | count
Changing the engine from C to Python did the trick for me.
Engine is C:
pd.read_csv(gdp_path, sep='\t', engine='c')
'utf-8' codec can't decode byte 0x92 in position 18: invalid start byte
Engine is Python:
pd.read_csv(gdp_path, sep='\t', engine='python')
No errors for me.
I would use virtualenv at your HOME directory.
$ sudo easy_install -U virtualenv
$ cd ~
$ virtualenv .
$ bin/pip ...
You could then also alter ~/.(login|profile|bash_profile)
, whichever is right for your shell to add ~/bin to your PATH and then that pip|python|easy_install
would be the one used by default.
Withough testing, I'd try:
for c in session.query(Stuff).all():
c.foo = c.foo+1
session.commit()
(IIRC, commit() works without flush()).
I've found that at times doing a large query and then iterating in python can be up to 2 orders of magnitude faster than lots of queries. I assume that iterating over the query object is less efficient than iterating over a list generated by the all() method of the query object.
[Please note comment below - this did not speed things up at all].
Assuming you have the wrong backend system you can change the backend kernel
by creating a new or editing the existing kernel.json
in the kernels
folder of your jupyter data path jupyter --paths
. You can have multiple kernels (R, Python2, Python3 (+virtualenvs), Haskell), e.g. you can create an Anaconda
specific kernel:
$ <anaconda-path>/bin/python3 -m ipykernel install --user --name anaconda --display-name "Anaconda"
Should create a new kernel:
<jupyter-data-dir>/kernels/anaconda/kernel.json
{
"argv": [ "<anaconda-path>/bin/python3", "-m", "ipykernel", "-f", "{connection_file}" ],
"display_name": "Anaconda",
"language": "python"
}
You need to ensure ipykernel
package is installed in the anaconda distribution.
This way you can just switch between kernels and have different notebooks using different kernels.
You can do this by adding a div i.e. centerBlock. And give this property in CSS to center the image or any content. Here is the code:
<div class="container">
<div class="row">
<div class="col-sm-4 col-md-4 col-lg-4">
<div class="centerBlock">
<img class="img-responsive" src="img/some-image.png" title="This image needs to be centered">
</div>
</div>
<div class="col-sm-8 col-md-8 col-lg-8">
Some content not important at this moment
</div>
</div>
</div>
// CSS
.centerBlock {
display: table;
margin: auto;
}
I am not sure did you see this list of MS SQL Modules for Node JS
Share your experience after using one if possible .
Good Luck
Above answer is very correct but I'm giving an easy step to do it:
private static final long[] THREE_CYCLES = new long[] { 100, 1000, 1000, 1000, 1000, 1000 };
public void longVibrate(View v)
{
vibrateMulti(THREE_CYCLES);
}
private void vibrateMulti(long[] cycles) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification();
notification.vibrate = cycles;
notificationManager.notify(0, notification);
}
And then in your xml file:
<button android:layout_height="wrap_content"
android:layout_width ="wrap_content"
android:onclick ="longVibrate"
android:text ="VibrateThrice">
</button>
That's the easiest way.
According the the Apple Reference on UIImage the object is immutable and you have no access to the backing bytes. While it is true that you can access the CGImage data if you populated the UIImage
with a CGImage
(explicitly or implicitly), it will return NULL
if the UIImage
is backed by a CIImage
and vice-versa.
Image objects not provide direct access to their underlying image data. However, you can retrieve the image data in other formats for use in your app. Specifically, you can use the cgImage and ciImage properties to retrieve versions of the image that are compatible with Core Graphics and Core Image, respectively. You can also use the UIImagePNGRepresentation(:) and UIImageJPEGRepresentation(:_:) functions to generate an NSData object containing the image data in either the PNG or JPEG format.
As stated your options are
Neither of these are particularly good tricks if you want output that isn't ARGB, PNG, or JPEG data and the data isn't already backed by CIImage.
While developing your project it might make more sense for you to avoid UIImage altogether and pick something else. UIImage, as a Obj-C image wrapper, is often backed by CGImage to the point where we take it for granted. CIImage tends to be a better wrapper format in that you can use a CIContext to get out the format you desire without needing to know how it was created. In your case, getting the bitmap would be a matter of calling
- render:toBitmap:rowBytes:bounds:format:colorSpace:
As an added bonus you can start doing nice manipulations to the image by chaining filters onto the image. This solves a lot of the issues where the image is upside down or needs to be rotated/scaled etc.
If your div rule is just div {...}
, then #a {...}
will be sufficient. If it is more complicated, you need a "more specific" selector, as defined by the CSS specification on specificity. (#a being more specific than div is just single aspect in the algorithm.)
This should do the trick:
...
select: function(event, ui){
ui.tab.attr('class');
} ,
...
For more info about the ui.tab see http://jqueryui.com/demos/tabs/#Events
I had the same issue it was due to that I had the bootstrap class "hidden-lg" on the table which caused it to stupidly become display: block !important;
I wonder how Bootstrap never considered to just instead do this:
@media (min-width: 1200px) {
.hidden-lg {
display: none;
}
}
And then just leave the element whatever display it had before for other screensizes.. Perhaps it is too advanced for them to figure out..
Anyway so:
table {
display: table; /* check so these really applies */
width: 100%;
}
should work
Exit
[construct], and intelisense will tell you which one(s) are valid in a particular place.
Use the optional font
argument to turtle.write()
, from the docs:
turtle.write(
arg, move=False, align="left", font=("Arial", 8, "normal"))
Parameters:
- arg – object to be written to the TurtleScreen
- move – True/False
- align – one of the strings “left”, “center” or right”
- font – a triple (fontname, fontsize, fonttype)
So you could do something like turtle.write("messi fan", font=("Arial", 16, "normal"))
to change the font size to 16 (default is 8).
In Web-"MVC" you can do whatever you please.
The original concept (1) described the model as the business logic. It should represent the application state and enforce some data consistency. That approach is often described as "fat model".
Most PHP frameworks follow a more shallow approach, where the model is just a database interface. But at the very least these models should still validate the incoming data and relations.
Either way, you're not very far off if you separate the SQL stuff or database calls into another layer. This way you only need to concern yourself with the real data/behaviour, not with the actual storage API. (It's however unreasonable to overdo it. You'll e.g. never be able to replace a database backend with a filestorage if that wasn't designed ahead.)
Have you try changing your project name in package.json
and execute command git init
to reinitialize the existing Git, instead?
Your existing Git history will still exist.
private OutputStream outputStream;
private InputStream inStream;
private void init() throws IOException {
BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
if (blueAdapter != null) {
if (blueAdapter.isEnabled()) {
Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();
if(bondedDevices.size() > 0) {
Object[] devices = (Object []) bondedDevices.toArray();
BluetoothDevice device = (BluetoothDevice) devices[position];
ParcelUuid[] uuids = device.getUuids();
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
socket.connect();
outputStream = socket.getOutputStream();
inStream = socket.getInputStream();
}
Log.e("error", "No appropriate paired devices.");
} else {
Log.e("error", "Bluetooth is disabled.");
}
}
}
public void write(String s) throws IOException {
outputStream.write(s.getBytes());
}
public void run() {
final int BUFFER_SIZE = 1024;
byte[] buffer = new byte[BUFFER_SIZE];
int bytes = 0;
int b = BUFFER_SIZE;
while (true) {
try {
bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
somevar = tag.getArtist()