objective-c is the primary language used.
i believe there is a mono touch framework that can be used with c#
Adobe also is working in some tools, one is this iPhone Packager which can utilize actionscript code
If you're looking for an HTML only way of doing this in angular...
<div #myDiv class="my_class" (click)="myDiv.classList.toggle('active')">
Some content
</div>
The important bit is the #myDiv
part.
It's a HTML Node reference, so you can use that variable as if it was assigned to document.querySelector('.my_class')
NOTE: this variable is scope specific, so you can use it in *ngFor
statements
Assuming your login dialog is the first window that gets created, try this inside your LoginViewModel class:
void OnLoginResponse(bool loginSucceded)
{
if (loginSucceded)
{
Window1 window = new Window1() { DataContext = new MainWindowViewModel() };
window.Show();
App.Current.MainWindow.Close();
App.Current.MainWindow = window;
}
else
{
LoginError = true;
}
}
I had to add the .classpath too, form a java project. I made a dummy java project and looked in the workspace for this dummy java project to see what is required. I transferred the two files. profile and .claspath to my checked out, and disconnected source from my subversion server. From then on it turned to a java project from just a plain old project.
public static boolean compareList(List ls1, List ls2){
return ls1.containsAll(ls2) && ls1.size() == ls2.size() ? true :false;
}
public static void main(String[] args) {
ArrayList<String> one = new ArrayList<String>();
one.add("one");
one.add("two");
one.add("six");
ArrayList<String> two = new ArrayList<String>();
two.add("one");
two.add("six");
two.add("two");
System.out.println("Output1 :: " + compareList(one, two));
two.add("ten");
System.out.println("Output2 :: " + compareList(one, two));
}
This is OK too; For example:
==> In "NumberController" file:
public ActionResult Create([Bind(Include = "NumberId,Number1,Number2,OperatorId")] Number number)
{
if (ModelState.IsValid)
{
...
...
return RedirectToAction("Index");
}
ViewBag.OperatorId = new SelectList(db.Operators, "OperatorId",
"OperatorSign", number.OperatorId);
return View();
}
==> In View file (Create.cshtml):
<div class="form-group">
@Html.LabelFor(model => model.Number1, htmlAttributes: new { @class =
"control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Number1, new { htmlAttributes = new {
@class = "form-control" } })
@Html.ValidationMessageFor(model => model.Number1, "", new { @class =
"text-danger" })
</div>
</div>
Now if we remove this statement:
ViewBag.OperatorId = new SelectList(db.Operators, "OperatorId", "OperatorSign", number.OperatorId);
from back of the following statement (in our controller) :
return View();
we will see this error:
There is no ViewData item of type 'IEnumerable' that has the key 'OperatorId'.
* So be sure of the existing of these statements. *
Your code alerts the current value of the dropdown for me, showing that it has properly pushed into the array.
Are you wanting to keep old values and append? You're recreating the array each time, meaning that the old value gets clobbered.
Here's some updated code:
var myarray = [];
$("#test").click(function() {
myarray.push($("#drop").val());
alert(myarray);
});
Use \D
to match non-digit characters.
preg_replace('~\D~', '', $str);
You could use this script:
def run(runfile):
with open(runfile,"r") as rnf:
exec(rnf.read())
Syntax:
run("file.py")
To get all divs under 'container', use the following:
$(".container>div") //or
$(".container").children("div");
You can stipulate a specific #id
instead of div
to get a particular one.
You say you want a div with an 'undefined' id. if I understand you right, the following would achieve this:
$(".container>div[id=]")
Although the advice not to parse HTML via regexp is valid, here's a expression that does pretty much what you asked:
/
\G # start where the last match left off
(?> # begin non-backtracking expression
.*? # *anything* until...
<[Aa]\b # an anchor tag
)?? # but look ahead to see that the rest of the expression
# does not match.
\s+ # at least one space
( \p{Alpha} # Our first capture, starting with one alpha
\p{Alnum}* # followed by any number of alphanumeric characters
) # end capture #1
(?: \s* = \s* # a group starting with a '=', possibly surrounded by spaces.
(?: (['"]) # capture a single quote character
(.*?) # anything else
\2 # which ever quote character we captured before
| ( [^>\s'"]+ ) # any number of non-( '>', space, quote ) chars
) # end group
)? # attribute value was optional
/msx;
"But wait," you might say. "What about *comments?!?!" Okay, then you can replace the .
in the non-backtracking section with: (It also handles CDATA sections.)
(?:[^<]|<[^!]|<![^-\[]|<!\[(?!CDATA)|<!\[CDATA\[.*?\]\]>|<!--(?:[^-]|-[^-])*-->)
\K
right before the attribute name and not have to worry about capturing all the stuff you want to skip over. For the Platform Independent Users or Windows users, what you can do is:
import runtime:
import (
"runtime"
"strings"
)
and then trim the string like this:
if runtime.GOOS == "windows" {
input = strings.TrimRight(input, "\r\n")
} else {
input = strings.TrimRight(input, "\n")
}
now you can compare it like that:
if strings.Compare(input, "a") == 0 {
//....yourCode
}
This is a better approach when you're making use of STDIN on multiple platforms.
This happens because on windows lines end with "\r\n"
which is known as CRLF, but on UNIX lines end with "\n"
which is known as LF and that's why we trim "\n"
on unix based operating systems while we trim "\r\n"
on windows.
What about creating an additional wrapper class?
package com.naveen.research.sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public abstract class PreparedStatementWrapper implements AutoCloseable {
protected PreparedStatement stat;
public PreparedStatementWrapper(Connection con, String query, Object ... params) throws SQLException {
this.stat = con.prepareStatement(query);
this.prepareStatement(params);
}
protected abstract void prepareStatement(Object ... params) throws SQLException;
public ResultSet executeQuery() throws SQLException {
return this.stat.executeQuery();
}
public int executeUpdate() throws SQLException {
return this.stat.executeUpdate();
}
@Override
public void close() {
try {
this.stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Then in the calling class you can implement prepareStatement method as:
try (Connection con = DriverManager.getConnection(JDBC_URL, prop);
PreparedStatementWrapper stat = new PreparedStatementWrapper(con, query,
new Object[] { 123L, "TEST" }) {
@Override
protected void prepareStatement(Object... params) throws SQLException {
stat.setLong(1, Long.class.cast(params[0]));
stat.setString(2, String.valueOf(params[1]));
}
};
ResultSet rs = stat.executeQuery();) {
while (rs.next())
System.out.println(String.format("%s, %s", rs.getString(2), rs.getString(1)));
} catch (SQLException e) {
e.printStackTrace();
}
This should do it for you ^wp.*php$
Matches
wp-comments-post.php
wp.something.php
wp.php
Doesn't match
something-wp.php
wp.php.txt
If you are to encounter the error that says Microsoft.CSharp.Core.targets not found
, these are the steps I took to correct mine:
Open any previous working projects folder and navigate to the link showed in the error, that is Projects/(working project name)/packages/Microsoft.Net.Compilers.1.3.2/tools/
and search for Microsoft.CSharp.Core.targets
file.
Copy this file and put it in the non-working project tools folder
(that is, navigating to the tools folder in the non-working project as shown above)
Now close your project (if it was open) and reopen it.
It should be working now.
Also, to make sure everything is working properly in your now open Visual Studio Project, Go to Tools > NuGetPackage Manager > Manage NuGet Packages For Solution
. Here, you might find an error that says, CodeAnalysis.dll is being used by another application.
Again, go to the tools folder
, find the specified file and delete it. Come back to Manage NuGet Packages For Solution
. You will find a link that will ask you to Reload, click it and everything gets re-installed.
Your project should be working properly now.
try this:
var span = document.getElementById("span");
span.style.fontSize = "25px";
span.innerHTML = "String";
You can use Length annotation for a column. By using it you can maximize or minimize column length. Length annotation only be used for Strings
.
@Column(name = "NAME", nullable = false, length = 50)
@Length(max = 50)
public String getName() {
return this.name;
}
Use different format or pattern to get the information from the date
var myDate = new Date("2015-06-17 14:24:36");_x000D_
console.log(moment(myDate).format("YYYY-MM-DD HH:mm:ss"));_x000D_
console.log("Date: "+moment(myDate).format("YYYY-MM-DD"));_x000D_
console.log("Year: "+moment(myDate).format("YYYY"));_x000D_
console.log("Month: "+moment(myDate).format("MM"));_x000D_
console.log("Month: "+moment(myDate).format("MMMM"));_x000D_
console.log("Day: "+moment(myDate).format("DD"));_x000D_
console.log("Day: "+moment(myDate).format("dddd"));_x000D_
console.log("Time: "+moment(myDate).format("HH:mm")); // Time in24 hour format_x000D_
console.log("Time: "+moment(myDate).format("hh:mm A"));
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
For more info: https://momentjs.com/docs/#/parsing/string-format/
For the question
How can i run a jar file in command prompt but with arguments
.
To pass arguments to the jar file at the time of execution
java -jar myjar.jar arg1 arg2
In the main() method of "Main-Class" [mentioned in the manifest.mft file]of your JAR file. you can retrieve them like this:
String arg1 = args[0];
String arg2 = args[1];
The above program will generate that time zone error.
After your database name you have to add this: ?useTimezone=true&serverTimezone=UTC
. Once you have done your code will work fine.
Best of luck :)
You can loop over the properties of your object as follows:
for(var prop in ad) {
if (ad.hasOwnProperty(prop)) {
// handle prop as required
}
}
It is important to use the hasOwnProperty()
method, to determine whether the object has the specified property as a direct property, and not inherited from the object's prototype chain.
From the comments: You can put that code in a function, and make it return false as soon as it reaches the part where there is the comment
As JJ Stiff suggests, you can add your text to a span and then measure the offsetHeight of the span.
var d = document.createElement("span");
d.font = "20px arial";
d.textContent = "Hello world!";
document.body.appendChild(d);
var emHeight = d.offsetHeight;
document.body.removeChild(d);
As shown on HTML5Rocks
The powerful text-based file manager mc (Midnight Commander, vaguely reminding the Norton Commander of old DOS times) has the built-in capability of inspecting and unpacking .rpm and .rpms files, just "open" the .rpm(s) file within mc and select CONTENTS.cpio
: for an rpm you get access to the install tree, for an rpms you get access to the .spec file and all the source packages.
It really isn't easy or efficient, and I suggest you don't do it unless you really have to (and you probably don't have to unless this is homework since the applications of inplace merging are mostly theoretical). Can't you use quicksort instead? Quicksort will be faster anyway with a few simpler optimizations and its extra memory is O(log N).
Anyway, if you must do it then you must. Here's what I found: one and two. I'm not familiar with the inplace merge sort, but it seems like the basic idea is to use rotations to facilitate merging two arrays without using extra memory.
Note that this is slower even than the classic merge sort that's not inplace.
I achieve this by following method
timeAgo = (date) => {
var ms = (new Date()).getTime() - date.getTime();
var seconds = Math.floor(ms / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
var months = Math.floor(days / 30);
var years = Math.floor(months / 12);
if (ms === 0) {
return 'Just now';
} if (seconds < 60) {
return seconds + ' seconds Ago';
} if (minutes < 60) {
return minutes + ' minutes Ago';
} if (hours < 24) {
return hours + ' hours Ago';
} if (days < 30) {
return days + ' days Ago';
} if (months < 12) {
return months + ' months Ago';
} else {
return years + ' years Ago';
}
}
console.log(timeAgo(new Date()));
console.log(timeAgo(new Date('Jun 27 2020 10:12:19')));
console.log(timeAgo(new Date('Jun 27 2020 00:12:19')));
console.log(timeAgo(new Date('May 28 2020 13:12:19')));
console.log(timeAgo(new Date('May 28 2017 13:12:19')));
You should set height
of html, body, .wrapper
to 100%
(in order to inherit full height) and then just set a flex
value greater than 1
to .row3
and not on the others.
.wrapper, html, body {
height: 100%;
margin: 0;
}
.wrapper {
display: flex;
flex-direction: column;
}
#row1 {
background-color: red;
}
#row2 {
background-color: blue;
}
#row3 {
background-color: green;
flex:2;
display: flex;
}
#col1 {
background-color: yellow;
flex: 0 0 240px;
min-height: 100%;/* chrome needed it a question time , not anymore */
}
#col2 {
background-color: orange;
flex: 1 1;
min-height: 100%;/* chrome needed it a question time , not anymore */
}
#col3 {
background-color: purple;
flex: 0 0 240px;
min-height: 100%;/* chrome needed it a question time , not anymore */
}
_x000D_
<div class="wrapper">
<div id="row1">this is the header</div>
<div id="row2">this is the second line</div>
<div id="row3">
<div id="col1">col1</div>
<div id="col2">col2</div>
<div id="col3">col3</div>
</div>
</div>
_x000D_
REST is not a specific web service but a design concept (architecture) for managing state information. The seminal paper on this was Roy Thomas Fielding's dissertation (2000), "Architectural Styles and the Design of Network-based Software Architectures" (available online from the University of California, Irvine).
First read Ryan Tomayko's post How I explained REST to my wife; it's a great starting point. Then read Fielding's actual dissertation. It's not that advanced, nor is it long (six chapters, 180 pages)! (I know you kids in school like it short).
EDIT: I feel it's pointless to try to explain REST. It has so many concepts like scalability, visibility (stateless) etc. that the reader needs to grasp, and the best source for understanding those are the actual dissertation. It's much more than POST/GET etc.
This is a simplified variation of Fernando's answer. This is for Linux and either Python 2 or 3. No external library is needed, and no external process is run.
import glob
def get_command_pid(command):
for path in glob.glob('/proc/*/comm'):
if open(path).read().rstrip() == command:
return path.split('/')[2]
Only the first matching process found will be returned, which works well for some purposes. To get the PIDs of multiple matching processes, you could just replace the return
with yield
, and then get a list with pids = list(get_command_pid(command))
.
Alternatively, as a single expression:
For one process:
next(path.split('/')[2] for path in glob.glob('/proc/*/comm') if open(path).read().rstrip() == command)
For multiple processes:
[path.split('/')[2] for path in glob.glob('/proc/*/comm') if open(path).read().rstrip() == command]
You're misunderstanding the meaning of the merge here.
The --no-commit
prevents the MERGE COMMIT from occuring, and that only happens when you merge two divergent branch histories; in your example that's not the case since Git indicates that it was a "fast-forward" merge and then Git only applies the commits already present on the branch sequentially.
Here is the sample worked in Python: This sample returns the results inline.
from pymongo import MongoClient
from bson.code import Code
mapper = Code("""
function() {
for (var key in this) { emit(key, null); }
}
""")
reducer = Code("""
function(key, stuff) { return null; }
""")
distinctThingFields = db.things.map_reduce(mapper, reducer
, out = {'inline' : 1}
, full_response = True)
## do something with distinctThingFields['results']
Before HTML5 it's only possible to check this with JavaScript or by a server-side verification (better, because JavaScript obviously only works with JavaScript enabled...). There is no native max-length attribute for textareas.
Since HTML5 it's a valid attribut, so defining your doctype as HTML5 may help. I don't know if all browsers support this attribute, though:
<!DOCTYPE html>
You can't return because you're not in a function. You can exit
though.
import sys
sys.exit(0)
0 (the default) means success, non-zero means failure.
I would assume it's possible to place a proxy between the DB and your app then observe the communication. I'm not familiar with what software you would use to do this.
Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.
In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.
Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.
If you look for POSIX compliant solution:
cd DirsRoot && find . -type f -print -o -name . -o -prune
-maxdepth is not POSIX compliant option.
Here is an option using while
:
def number_format(n):
n2, n3 = n, 0
while n2 >= 1e3:
n2 /= 1e3
n3 += 1
return '%.3f' % n2 + ('', ' k', ' M', ' G')[n3]
s = number_format(9012345678)
print(s == '9.012 G')
My issue got resolved by restarting the MS SQL server service, simple.
I do not think document fires the click event. Try using the body element to capture the click event. Might need to check on that...
Your code looks fine except the possibility that if the variable declaration is inside a dom read handler then it will not be a global variable... it will be a closure variable
jQuery(function(){
//here it is a closure variable
var a_href;
$('sth a').on('click', function(e){
a_href = $(this).attr('href');
console.log(a_href);
//output is "home"
e.preventDefault();
}
})
To make the variable global, one solution is to declare the variable in global scope
var a_href;
jQuery(function(){
$('sth a').on('click', function(e){
a_href = $(this).attr('href');
console.log(a_href);
//output is "home"
e.preventDefault();
}
})
another is to set the variable as a property of the window object
window.a_href = $(this).attr('href')
Why console printing undefined
You are getting the output as undefined
because even though the variable is declared, you have not initialized it with a value, the value of the variable is set only after the a
element is clicked till that time the variable will have the value undefined
. If you are not declaring the variable it will throw a ReferenceError
You can convert the URL
to a String
and use it to create a new File
. e.g.
URL url = new URL("http://google.com/pathtoaimage.jpg");
File f = new File(url.getFile());
I got this error even after uninstalling the original APK, which was mystifying. Finally I realized that I had set up multiple users on my Nexus 7 for testing and that the app was still installed for one of the other users. Once I uninstalled it for all users the error went away.
foreach ($all_address as $aa) {
$mail->AddAddress($aa);
}
I had the same issue and I figured out why it was not working on my case
The html page was divided into different html fragments and I found that I have another input field that carries the same Id of the select
, which caused the val()
to be always empty
I hope this saves the day for anyone who have similar issue.
I just found this quite impressive tutorial about jquery to javascript conversion from Jeffrey Way on Jan 19th 2012 *Copyright © 2014 Envato*
:
http://net.tutsplus.com/tutorials/javascript-ajax/from-jquery-to-javascript-a-reference/
Whether we like it or not, more and more developers are being introduced to the world of JavaScript through jQuery first. In many ways, these newcomers are the lucky ones. They have access to a plethora of new JavaScript APIs, which make the process of DOM traversal (something that many folks depend on jQuery for) considerably easier. Unfortunately, they don’t know about these APIs!
In this article, we’ll take a variety of common jQuery tasks, and convert them to both modern and legacy JavaScript.
I proposed it in a comment to OP, and after his suggestion, i publish it has an answer for everyone to refer to.
Also, Jeffrey Way mentioned about his inspiration witch seems to be a good primer for understanding : http://sharedfil.es/js-48hIfQE4XK.html
Has a teaser, this document comparison of jQuery to javascript :
$(document).ready(function() {
// code…
});
document.addEventListener("DOMContentLoaded", function() {
// code…
});
$("a").click(function() {
// code…
})
[].forEach.call(document.querySelectorAll("a"), function(el) {
el.addEventListener("click", function() {
// code…
});
});
You should take a look.
_x000D_
_x000D_
.custom-modal-header_x000D_
{_x000D_
display: block;_x000D_
}_x000D_
.custom-modal .modal-content_x000D_
{_x000D_
width:500px;_x000D_
border: none;_x000D_
}_x000D_
.custom-modal_x000D_
{_x000D_
display: block !important;_x000D_
}_x000D_
.custom-fade .modal-dialog {_x000D_
transform: translateY(4%);_x000D_
opacity: 0;_x000D_
-webkit-transition: all .2s ease-out;_x000D_
-o-transition: all .2s ease-out;_x000D_
transition: all .2s ease-out;_x000D_
will-change: transform;_x000D_
}_x000D_
.custom-fade.in .modal-dialog {_x000D_
opacity: 1;_x000D_
transform: translateY(0%);_x000D_
}
_x000D_
<div class="modal custom-modal custom-fade" tabindex="-1" role="dialog"_x000D_
aria-hidden="true">_x000D_
<div class="modal-dialog modal-lg">_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<h5 class="modal-title">Title</h5>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<p>My cat is dope.</p>_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button type="button" class="btn btn-primary" data-dismiss="modal">Sure (Meow)</button>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
$1
, $2
, $3
, ... are the positional parameters."$@"
is an array-like construct of all positional parameters, {$1, $2, $3 ...}
."$*"
is the IFS expansion of all positional parameters, $1 $2 $3 ...
.$#
is the number of positional parameters.$-
current options set for the shell.$$
pid of the current shell (not subshell).$_
most recent parameter (or the abs path of the command to start the current shell immediately after startup).$IFS
is the (input) field separator.$?
is the most recent foreground pipeline exit status.$!
is the PID of the most recent background command.$0
is the name of the shell or shell script.Most of the above can be found under Special Parameters in the Bash Reference Manual. There are all the environment variables set by the shell.
For a comprehensive index, please see the Reference Manual Variable Index.
I think you could use TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2) something like
select * from MyTab T where
TIMESTAMPDIFF(MINUTE,T.runTime,NOW()) > 20
I think I usually used eqnarray or something. It lets you say
\begin{eqnarray*}
x &=& blah blah blah \\
& & more blah blah blah \\
& & even more blah blah
\end{eqnarray*}
and it will be aligned by the & &... As pkaeding mentioned, it's hard to read, but when you've got an equation thats that long, it's gonna be hard to read no matter what... (The * makes it not have an equation number, IIRC)
None of the answers here were working in my case (64 bit processor but 32 bit OS), so here's the solution which worked for me:
(set | find "ProgramFiles(x86)" > NUL) && (echo "%ProgramFiles(x86)%" | find "x86") > NUL && set bits=64 || set bits=32
Correct solution is to copy or install to /usr/local/bin
not /usr/bin
.This is due to System Integrity Protection (SIP). SIP makes /usr/bin
read-only but leaves /usr/local
as read-write.
SIP should not be disabled as stated in the answer above because it adds another layer of protection against malware gaining root access. Here is a complete explanation of what SIP does and why it is useful.
As suggested in this answer one should not disable SIP (rootless mode) "It is not recommended to disable rootless mode! The best practice is to install custom stuff to "/usr/local" only."
I did it like below. Not the best way i think, but it works :)
Connection c = DriverManager.getConnection("jdbc:postgresql://....");
PreparedStatement s = c.prepareStatement("select * from " + tabName + " where id > ? order by id");
s.setMaxRows(100);
int lastId = 0;
for (;;) {
s.setInt(1, lastId);
ResultSet rs = s.executeQuery();
int lastIdBefore = lastId;
while (rs.next()) {
lastId = Integer.parseInt(rs.getObject(1).toString());
// ...
}
if (lastIdBefore == lastId) {
break;
}
}
I too got similar error when i misplaced the code
text=(TextView)findViewById(R.id.text);// this line has to be below setcontentview
setContentView(R.layout.activity_my_otype);
//this is the correct place
text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
I got it working on placing the code in right order as shown below
setContentView(R.layout.activity_my_otype);
text=(TextView)findViewById(R.id.text);
text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
IIF
is the same as CASE WHEN <Condition> THEN <true part> ELSE <false part> END
. The query plan will be the same. It is, perhaps, "syntactical sugar" as initially implemented.
CASE is portable across all SQL platforms whereas IIF is SQL SERVER 2012+ specific.
Try that:
foreach ($images[1] as $key => &$image) {
if (yourConditionGoesHere) {
unset($images[1][$key])
}
}
unset($image); // detach reference after loop
Normally, foreach
operates on a copy of your array so any changes you make, are made to that copy and don't affect the actual array.
So you need to unset the values via $images[$key]
;
The reference on &$image
prevents the loop from creating a copy of the array which would waste memory.
I know rather old question but....came across looking other thing so I give my shot:
[each*2 for each in [1,2,3,4,5] if each % 10 == 0])
EDIT: many moon after this question was asked, yes, now apparently you can.
No, but it's based on Intellij IDEA.
The community version of that is free for download but it doesn't support most things requiring an external database or application server. The line for Java is pretty much that JavaSE code can happily use Community.
If you want that (or are using JavaEE) then you either need the Ultimate version, which isn't free, or the EAP of the next version which is usually good for a month until they release another.
Basically it works like this
Android Studio is just Android the Android Stuff from IDEA 13 Community...
...which will be free, and is anything from IDEA 13 Ultimate...
...that doesn't require a database or app server.
http://www.jetbrains.com/idea/
IDEA 12 Community doesn't have the ability to import the gradilized project and it won't, so while you can do Android development in it now (I do), don't expect it to have the same features as Android Studio. There's a lot of good new Android stuff in it, that's going into 13.
UPDATE 9 July 2012 - Looks like this is fixed in RTM.
^
and $
so you don't need to add them. (It doesn't appear to be a problem to include them, but you don't need them)View source shows the following:
data-val-regex-pattern="([a-zA-Z0-9 .&'-]+)" <-- MVC 3
data-val-regex-pattern="([a-zA-Z0-9 .&amp;&#39;-]+)" <-- MVC 4/Beta
It looks like we're double encoding.
I think just filter(str.isalnum, string)
works
In [20]: filter(str.isalnum, 'string with special chars like !,#$% etcs.')
Out[20]: 'stringwithspecialcharslikeetcs'
In Python3, filter( )
function would return an itertable object (instead of string unlike in above). One has to join back to get a string from itertable:
''.join(filter(str.isalnum, string))
or to pass list
in join use (not sure but can be fast a bit)
''.join([*filter(str.isalnum, string)])
note: unpacking in [*args]
valid from Python >= 3.5
I've been using P4Merge, it's free and cross platform.
Probably you can implement generic static lookup
method.
Like so
public class LookupUtil {
public static <E extends Enum<E>> E lookup(Class<E> e, String id) {
try {
E result = Enum.valueOf(e, id);
} catch (IllegalArgumentException e) {
// log error or something here
throw new RuntimeException(
"Invalid value for enum " + e.getSimpleName() + ": " + id);
}
return result;
}
}
Then you can
public enum MyEnum {
static public MyEnum lookup(String id) {
return LookupUtil.lookup(MyEnum.class, id);
}
}
or call explicitly utility class lookup method.
In config/app.php file make a instance of env variable like 'name' => env('APP_NAME', 'Laravel')
& In your controller call it like config('app.name')
Run following commands php artisan config:cache
php artisan cache:clear
if it is not working.
You could convert your values into a 'Decimal' datetime and convert it then to a real datetime column:
select cast(rtrim(year *10000+ month *100+ day) as datetime) as Date from DateTable
See here as well for more info.
First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.
Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.
Here's how you should do it with all the suggestions above:
public enum States {
...
MASSACHUSETTS("Massachusetts", "MA", true),
MICHIGAN ("Michigan", "MI", false),
...; // all 50 of those
private final String full;
private final String abbr;
private final boolean originalColony;
private States(String full, String abbr, boolean originalColony) {
this.full = full;
this.abbr = abbr;
this.originalColony = originalColony;
}
public String getFullName() {
return full;
}
public String getAbbreviatedName() {
return abbr;
}
public boolean isOriginalColony(){
return originalColony;
}
}
If speed is what you need and extra dependencies are not a problem, you maybe find numba
quite useful (now it is pretty easy to install, on any platform). The classic ray_tracing
approach you proposed can be easily ported to numba
by using numba @jit
decorator and casting the polygon to a numpy array. The code should look like:
@jit(nopython=True)
def ray_tracing(x,y,poly):
n = len(poly)
inside = False
p2x = 0.0
p2y = 0.0
xints = 0.0
p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x,p1y = p2x,p2y
return inside
The first execution will take a little longer than any subsequent call:
%%time
polygon=np.array(polygon)
inside1 = [numba_ray_tracing_method(point[0], point[1], polygon) for
point in points]
CPU times: user 129 ms, sys: 4.08 ms, total: 133 ms
Wall time: 132 ms
Which, after compilation will decrease to:
CPU times: user 18.7 ms, sys: 320 µs, total: 19.1 ms
Wall time: 18.4 ms
If you need speed at the first call of the function you can then pre-compile the code in a module using pycc
. Store the function in a src.py like:
from numba import jit
from numba.pycc import CC
cc = CC('nbspatial')
@cc.export('ray_tracing', 'b1(f8, f8, f8[:,:])')
@jit(nopython=True)
def ray_tracing(x,y,poly):
n = len(poly)
inside = False
p2x = 0.0
p2y = 0.0
xints = 0.0
p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x,p1y = p2x,p2y
return inside
if __name__ == "__main__":
cc.compile()
Build it with python src.py
and run:
import nbspatial
import numpy as np
lenpoly = 100
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in
np.linspace(0,2*np.pi,lenpoly)[:-1]]
# random points set of points to test
N = 10000
# making a list instead of a generator to help debug
points = zip(np.random.random(N),np.random.random(N))
polygon = np.array(polygon)
%%time
result = [nbspatial.ray_tracing(point[0], point[1], polygon) for point in points]
CPU times: user 20.7 ms, sys: 64 µs, total: 20.8 ms
Wall time: 19.9 ms
In the numba code I used: 'b1(f8, f8, f8[:,:])'
In order to compile with nopython=True
, each var needs to be declared before the for loop
.
In the prebuild src code the line:
@cc.export('ray_tracing' , 'b1(f8, f8, f8[:,:])')
Is used to declare the function name and its I/O var types, a boolean output b1
and two floats f8
and a two-dimensional array of floats f8[:,:]
as input.
For my use case, I need to check if multiple points are inside a single polygon - In such a context, it is useful to take advantage of numba parallel capabilities to loop over a series of points. The example above can be changed to:
from numba import jit, njit
import numba
import numpy as np
@jit(nopython=True)
def pointinpolygon(x,y,poly):
n = len(poly)
inside = False
p2x = 0.0
p2y = 0.0
xints = 0.0
p1x,p1y = poly[0]
for i in numba.prange(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x,p1y = p2x,p2y
return inside
@njit(parallel=True)
def parallelpointinpolygon(points, polygon):
D = np.empty(len(points), dtype=numba.boolean)
for i in numba.prange(0, len(D)):
D[i] = pointinpolygon(points[i,0], points[i,1], polygon)
return D
Note: pre-compiling the above code will not enable the parallel capabilities of numba (parallel CPU target is not supported by pycc/AOT
compilation) see: https://github.com/numba/numba/issues/3336
Test:
import numpy as np
lenpoly = 100
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in np.linspace(0,2*np.pi,lenpoly)[:-1]]
polygon = np.array(polygon)
N = 10000
points = np.random.uniform(-1.5, 1.5, size=(N, 2))
For N=10000
on a 72 core machine, returns:
%%timeit
parallelpointinpolygon(points, polygon)
# 480 µs ± 8.19 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
0
instead of 1
(thanks @mehdi):for i in numba.prange(0, len(D))
Follow-up on the comparison made by @mehdi, I am adding a GPU-based method below. It uses the point_in_polygon
method, from the cuspatial
library:
import numpy as np
import cudf
import cuspatial
N = 100000002
lenpoly = 1000
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in
np.linspace(0,2*np.pi,lenpoly)]
polygon = np.array(polygon)
points = np.random.uniform(-1.5, 1.5, size=(N, 2))
x_pnt = points[:,0]
y_pnt = points[:,1]
x_poly =polygon[:,0]
y_poly = polygon[:,1]
result = cuspatial.point_in_polygon(
x_pnt,
y_pnt,
cudf.Series([0], index=['geom']),
cudf.Series([0], name='r_pos', dtype='int32'),
x_poly,
y_poly,
)
Following @Mehdi comparison. For N=100000002
and lenpoly=1000
- I got the following results:
time_parallelpointinpolygon: 161.54760098457336
time_mpltPath: 307.1664695739746
time_ray_tracing_numpy_numba: 353.07356882095337
time_is_inside_sm_parallel: 37.45389246940613
time_is_inside_postgis_parallel: 127.13793849945068
time_is_inside_rapids: 4.246025562286377
hardware specs:
Notes:
The cuspatial.point_in_poligon
method, is quite robust and powerful, it offers the ability to work with multiple and complex polygons (I guess at the expense of performance)
The numba
methods can also be 'ported' on the GPU - it will be interesting to see a comparison which includes a porting to cuda
of fastest method mentioned by @Mehdi (is_inside_sm
).
source ~/.nvm/nvm.sh
Add this line to ~/.bashrc, ~/.profile, or ~/.zshrc
Quick and dirty way (e.g. to see how data is stored in oracle)
SQL> select dump(dummy) dump_dummy, dummy
, dump(10) dump_ten
from dual
DUMP_DUMMY DUMMY DUMP_TEN
---------------- ----- --------------------
Typ=1 Len=1: 88 X Typ=2 Len=2: 193,11
1 row selected.
will show that dummy column in table sys.dual has typ=1 (varchar2), while 10 is Typ=2 (number).
Scenario: Removing NodeJS when Windows has no Program Entry for your Node installation
I ran into a problem where my version of NodeJS (0.10.26) could NOT be uninstalled nor removed, because Programs & Features in Windows 7 (aka Add/Remove Programs) had no record of my having installed NodeJS... so there was no option to remove it short of manually deleting registry keys and files.
Command to verify your NodeJS version: node --version
I attempted to install the newest recommended version of NodeJS, but it failed at the end of the installation process and rolled back. Multiple versions of NodeJS also failed, and the installer likewise rolled them back as well. I could not upgrade NodeJS from the command line as I did not have SUDO installed.
SOLUTION: After spending several hours troubleshooting the problem, including upgrading NPM, I decided to reinstall the EXACT version of NodeJS on my system, over the top of the existing installation.
That solution worked, and it reinstalled NodeJS without any errors. Better yet, it also added an official entry in Add/Remove Programs dialogue.
Now that Windows was aware of the forgotten NodeJS installation, I was able to uninstall my existing version of NodeJS completely. I then successfully installed the newest recommended release of NodeJS for the Windows platform (version 4.4.5 as of this writing) without a roll-back initiating.
It took me a while to reach sucess, so I am posting this in case it helps anyone else with a similar issue.
Try the following:
CONCAT(datepart(yyyy,DATE),'-', DATEPART(qq,DATE))
It returns:
yyyy-q
Example: 2017-3
for 2017-07-11
This mean that you cant create enclose type. This mean that first you have to cerate a instance of "parent" class and then from this instance you can create nested class instances.
NutritionalFacts n = new NutritionalFacts()
Builder b = new n.Builder(10).carbo(23).fat(1).build();
Here is yet another approach, which was more convenient in my case (I just wanted to drop root privileges and do the rest of my script from restricted user): you can make the script restart itself from correct user. Let's suppose it is run as root initially. Then it will look like this:
#!/bin/bash
if [ $UID -eq 0 ]; then
user=$1
dir=$2
shift 2 # if you need some other parameters
cd "$dir"
exec su "$user" "$0" -- "$@"
# nothing will be executed beyond that line,
# because exec replaces running process with the new one
fi
echo "This will be run from user $UID"
...
Entity Framework detects something about the model has changed, you need to do something to the database to get this work. Solution: 1. enable-migrations 2. update-database
To build on @Livven's answer, here are some useful combinations.
variable substitution, leading tab retained, overwrite file, echo to stdout
tee /path/to/file <<EOF
${variable}
EOF
no variable substitution, leading tab retained, overwrite file, echo to stdout
tee /path/to/file <<'EOF'
${variable}
EOF
variable substitution, leading tab removed, overwrite file, echo to stdout
tee /path/to/file <<-EOF
${variable}
EOF
variable substitution, leading tab retained, append to file, echo to stdout
tee -a /path/to/file <<EOF
${variable}
EOF
variable substitution, leading tab retained, overwrite file, no echo to stdout
tee /path/to/file <<EOF >/dev/null
${variable}
EOF
the above can be combined with sudo
as well
sudo -u USER tee /path/to/file <<EOF
${variable}
EOF
Create a custom class, e.g. .custom-btn
. Note that to override jQM styles without using !important
, CSS hierarchy should be respected. .ui-btn.custom-class
or .ui-input-btn.custom-class
.
.ui-input-btn.custom-btn {
border:1px solid red;
text-decoration:none;
font-family:helvetica;
color:red;
background:url(img.png) repeat-x;
}
Add a data-wrapper-class
to input
. The custom class will be added to input
wrapping div.
<input type="button" data-wrapper-class="custom-btn">
Input
button is wrapped by a DIV with class ui-btn
. You need to select that div and the input[type="submit"]
. Using !important
is essential to override Jquery Mobile styles.
div.ui-btn, input[type="submit"] {
border:1px solid red !important;
text-decoration:none !important;
font-family:helvetica !important;
color:red !important;
background:url(../images/btn_hover.png) repeat-x !important;
}
You can keep your CONTACT parameter with the following approach:
using (var stream = new MemoryStream())
{
var context = (HttpContextBase)Request.Properties["MS_HttpContext"];
context.Request.InputStream.Seek(0, SeekOrigin.Begin);
context.Request.InputStream.CopyTo(stream);
string requestBody = Encoding.UTF8.GetString(stream.ToArray());
}
Returned for me the json representation of my parameter object, so I could use it for exception handling and logging.
Found as accepted answer here
From C++ FAQ Lite -
Use references when you can, and pointers when you have to.
References are usually preferred over pointers whenever you don't need "reseating". This usually means that references are most useful in a class's public interface. References typically appear on the skin of an object, and pointers on the inside.
The exception to the above is where a function's parameter or return value needs a "sentinel" reference — a reference that does not refer to an object. This is usually best done by returning/taking a pointer, and giving the NULL pointer this special significance (references must always alias objects, not a dereferenced NULL pointer).
Note: Old line C programmers sometimes don't like references since they provide reference semantics that isn't explicit in the caller's code. After some C++ experience, however, one quickly realizes this is a form of information hiding, which is an asset rather than a liability. E.g., programmers should write code in the language of the problem rather than the language of the machine.
Set the GET query parameters as managed properties in faces-config.xml
so that you don't need to gather them manually:
<managed-bean>
<managed-bean-name>forward</managed-bean-name>
<managed-bean-class>com.example.ForwardBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>action</property-name>
<value>#{param.action}</value>
</managed-property>
<managed-property>
<property-name>actionParam</property-name>
<value>#{param.actionParam}</value>
</managed-property>
</managed-bean>
This way the request forward.jsf?action=outcome1&actionParam=123
will let JSF set the action
and actionParam
parameters as action
and actionParam
properties of the ForwardBean
.
Create a small view forward.xhtml
(so small that it fits in default response buffer (often 2KB) so that it can be resetted by the navigationhandler, otherwise you've to increase the response buffer in the servletcontainer's configuration), which invokes a bean method on beforePhase
of the f:view
:
<!DOCTYPE html>
<html xmlns:f="http://java.sun.com/jsf/core">
<f:view beforePhase="#{forward.navigate}" />
</html>
The ForwardBean
can look like this:
public class ForwardBean {
private String action;
private String actionParam;
public void navigate(PhaseEvent event) {
FacesContext facesContext = FacesContext.getCurrentInstance();
String outcome = action; // Do your thing?
facesContext.getApplication().getNavigationHandler().handleNavigation(facesContext, null, outcome);
}
// Add/generate the usual boilerplate.
}
The navigation-rule
speaks for itself (note the <redirect />
entries which would do ExternalContext#redirect()
instead of ExternalContext#dispatch()
under the covers):
<navigation-rule>
<navigation-case>
<from-outcome>outcome1</from-outcome>
<to-view-id>/outcome1.xhtml</to-view-id>
<redirect />
</navigation-case>
<navigation-case>
<from-outcome>outcome2</from-outcome>
<to-view-id>/outcome2.xhtml</to-view-id>
<redirect />
</navigation-case>
</navigation-rule>
An alternative is to use forward.xhtml
as
<!DOCTYPE html>
<html>#{forward}</html>
and update the navigate()
method to be invoked on @PostConstruct
(which will be invoked after bean's construction and all managed property setting):
@PostConstruct
public void navigate() {
// ...
}
It has the same effect, however the view side is not really self-documenting. All it basically does is printing ForwardBean#toString()
(and hereby implicitly constructing the bean if not present yet).
Note for the JSF2 users, there is a cleaner way of passing parameters with <f:viewParam>
and more robust way of handling the redirect/navigation by <f:event type="preRenderView">
. See also among others:
It's virtual machine dependent.
If you want to parse a String to a char, whereas the String object represent more than one character, you just simply use the following expression: char c = (char) Integer.parseInt(s). Where s equals the String you want to parse. Most people forget that char's represent a 16-bit number, and thus can be a part of any numerical expression :)
For anyone who stumbles across this in the future, this is how you do it:
xl.Range("A1:A1").Style := "Bad"
xl.Range("A1:A1").Style := "Good"
xl.Range("A1:A1").Style := "Neutral"
An easy way to check on things like this is to open excel and record a macro. In this case I recorded a macro where I just formatted the cell to "Bad". Once you've recorded the macro, just go in and edit it and it will essentially give you the code. It will require a little translation on your part, but here is what the macro looks like when I edit it:
Selection.Style = "Bad"
As you can see, it's pretty easy to make the jump to AHK from what excel provides.
Subject is the certificate's common name and is a critical property for the certificate in a lot of cases if it's a server certificate and clients are looking for a positive identification.
As an example on an SSL certificate for a web site the subject would be the domain name of the web site.
You could just use VideoLAN. VideoLAN will work as a server (or you can wrap your own C# application around it for more control). There are also .NET wrappers for the viewer that you can use and thus embed in your C# client.
Atomic properties :- When a variable assigned with atomic property that means it has only one thread access and it will be thread safe and will be good in performance perspective, will have default behaviour.
Non Atomic Properties :- When a variable assigned with atomic property that means it has multi thread access and it will not be thread safe and will be slow in performance perspective, will have default behaviour and when two different threads want to access variable at same time it will give unexpected results.
TylerH made a really good answer, I just had to give that last button a visual update.
.btn {
border-radius: 5px;
padding: 10px 30px;
box-shadow: 1px 1px 1px #000;
background-image: linear-gradient(to bottom, #eee, #ddd);
}
.btn:hover {
background-image: linear-gradient(to top, #adf, #8bf);
}
.btn:active {
margin: 1px 1px 0;
box-shadow: -1px -1px 1px #000;
}
#btnControl {
display: block;
visibility: hidden;
}
_x000D_
<input type="checkbox" id="btnControl"/>
<label class="btn" for="btnControl">Click me!</label>
_x000D_
I had the same problem but previous solutions not work for me. The only solution works for me is the following URL.
https://enlightensoft.wordpress.com/2013/01/15/maven-error-reading-error-in-opening-zip-file/
[EDIT]
Here I explain more about it
Suppose you got an error like below
[ERROR] error: error reading C:\Users\user\.m2\repository\org\jdom\jdom\1.1\jdom-1.1.jar; error in opening zip file
Then you have to follow these steps.
C:\Users\user\.m2\repository\org\jdom\jdom\1.1\jdom-1.1.jar
C:\Users\user\.m2\repository\org\jdom\jdom\1.1\
Then you can build your project using mvn clean install
hope this will help somebody.
You can do these checks using positive look ahead assertions:
^(?=.*[A-Z].*[A-Z])(?=.*[!@#$&*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{8}$
Explanation:
^ Start anchor
(?=.*[A-Z].*[A-Z]) Ensure string has two uppercase letters.
(?=.*[!@#$&*]) Ensure string has one special case letter.
(?=.*[0-9].*[0-9]) Ensure string has two digits.
(?=.*[a-z].*[a-z].*[a-z]) Ensure string has three lowercase letters.
.{8} Ensure string is of length 8.
$ End anchor.
Here is the simplest thing I've found
-- Midnight floor of current date
SELECT Convert(DateTime, DATEDIFF(DAY, 0, GETDATE()))
The DATEDIFF returns the integer number of days before or since 1900-1-1, and the Convert Datetime obligingly brings it back to that date at midnight.
Since DateDiff returns an integer you can use add or subtract days to get the right offset.
SELECT Convert(DateTime, DATEDIFF(DAY, 0, GETDATE()) + @dayOffset)
This isn't rounding this is truncating...But I think that is what is being asked. (To round add one and truncate...and that's not rounding either, that the ceiling, but again most likely what you want. To really round add .5 (does that work?) and truncate.
It turns out you can add .5 to GetDate() and it works as expected.
-- Round Current time to midnight today or midnight tomorrow
SELECT Convert(DateTime, DATEDIFF(DAY, 0, GETDATE() + .5))
I did all my trials on SQL Server 2008, but I think these functions apply to 2005 as well.
grep 'search this' *.txt
worked for me to search through all .txt files (enter your own search value, of course).
You may write a recursive algorithm in Batch that gives you exact control of what you do in every nested subdirectory:
@echo off
call :treeProcess
goto :eof
:treeProcess
rem Do whatever you want here over the files of this subdir, for example:
copy *.* C:\dest\dir
for /D %%d in (*) do (
cd %%d
call :treeProcess
cd ..
)
exit /b
Windows Batch File Looping Through Directories to Process Files?
For global functions dir()
is the command to use (as mentioned in most of these answers), however this lists both public functions and non-public functions together.
For example running:
>>> import re
>>> dir(re)
Returns functions/classes like:
'__all__', '_MAXCACHE', '_alphanum_bytes', '_alphanum_str', '_pattern_type', '_pickle', '_subx'
Some of which are not generally meant for general programming use (but by the module itself, except in the case of DunderAliases like __doc__
, __file__
ect). For this reason it may not be useful to list them with the public ones (this is how Python knows what to get when using from module import *
).
__all__
could be used to solve this problem, it returns a list of all the public functions and classes in a module (those that do not start with underscores - _
). See
Can someone explain __all__ in Python? for the use of __all__
.
Here is an example:
>>> import re
>>> re.__all__
['match', 'fullmatch', 'search', 'sub', 'subn', 'split', 'findall', 'finditer', 'compile', 'purge', 'template', 'escape', 'error', 'A', 'I', 'L', 'M', 'S', 'X', 'U', 'ASCII', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL', 'VERBOSE', 'UNICODE']
>>>
All the functions and classes with underscores have been removed, leaving only those that are defined as public and can therefore be used via import *
.
Note that __all__
is not always defined. If it is not included then an AttributeError
is raised.
A case of this is with the ast module:
>>> import ast
>>> ast.__all__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'ast' has no attribute '__all__'
>>>
It's an excellent question, I had the same question yesterday. I thought about this problem, specifically SEARCHED if existed something like "ON UPDATE CASCADE" and fortunately the designers of SQL had also thought about that. I agree with Ted.strauss, and I also commented Noran's case.
When did I use it? Like Ted pointed out, when you are treating several databases at one time, and the modification in one of them, in one table, has any kind of reproduction in what Ted calls "satellite database", can't be kept with the very original ID, and for any reason you have to create a new one, in case you can't update the data on the old one (for example due to permissions, or in case you are searching for fastness in a case that is so ephemeral that doesn't deserve the absolute and utter respect for the total rules of normalization, simply because will be a very short-lived utility)
So, I agree in two points:
(A.) Yes, in many times a better design can avoid it; BUT
(B.) In cases of migrations, replicating databases, or solving emergencies, it's a GREAT TOOL that fortunately was there when I went to search if it existed.
To export data you need to right click on your results and select export data, after which you will be asked for a specific file format such as insert
, loader
, or text
etc. After selecting this browse your directory and select the export destination.
another example:
request:
curl -XGET http://127.0.0.1:5000/alert/dingding/test?x=y
then:
request.method: GET
request.url: http://127.0.0.1:5000/alert/dingding/test?x=y
request.base_url: http://127.0.0.1:5000/alert/dingding/test
request.url_charset: utf-8
request.url_root: http://127.0.0.1:5000/
str(request.url_rule): /alert/dingding/test
request.host_url: http://127.0.0.1:5000/
request.host: 127.0.0.1:5000
request.script_root:
request.path: /alert/dingding/test
request.full_path: /alert/dingding/test?x=y
request.args: ImmutableMultiDict([('x', 'y')])
request.args.get('x'): y
You could also just do:
document.getElementById('id').classList.add('class');
document.getElementById('id').classList.remove('class');
And to toggle a class (remove if exists else add it):
document.getElementById('id').classList.toggle('class');
With the plugin: jQuery Selection Box. You can do this:
var myOptions = {
"Value 1" : "Text 1",
"Value 2" : "Text 2",
"Value 3" : "Text 3"
}
$("#myselect2").addOption(myOptions, false);
I also encountered the same problem and passed the following way to solve this problem.
step 1:
$ npm install --save-dev http-proxy-middleware
step 2:
add a proxy when i fetch web api, if you use lite-server you can add a file bs-config.js .
//file: bs-config.js
var proxyMiddleware = require('http-proxy-middleware');
module.exports = {
server: {
middleware: {
1: proxyMiddleware('/example-api', {
target: 'http://api.example.com',
changeOrigin: true,
pathRewrite: {
'^/news-at-api': '/api'
}
})
}
}
};
hope this helps.
Here is a non-recursive implementation, just for fun:
/**
* Deletes the given folder and all its files / subfolders.
* Is not implemented in a recursive way. The "Recursively" in the name stems from the filesystem command
* @param root The folder to delete recursively
*/
public static void deleteRecursively(final File root) {
LinkedList<File> deletionQueue = new LinkedList<>();
deletionQueue.add(root);
while(!deletionQueue.isEmpty()) {
final File toDelete = deletionQueue.removeFirst();
final File[] children = toDelete.listFiles();
if(children == null || children.length == 0) {
// This is either a file or an empty directory -> deletion possible
toDelete.delete();
} else {
// Add the children before the folder because they have to be deleted first
deletionQueue.addAll(Arrays.asList(children));
// Add the folder again because we can't delete it yet.
deletionQueue.addLast(toDelete);
}
}
}
And when I debug this the logic does fall into the sentence.replace.
Yes, and then you discard the return value.
Strings in Java are immutable - when you call replace
, it doesn't change the contents of the existing string - it returns a new string with the modifications. So you want:
sentence = sentence.replace("and", " ");
This applies to all the methods in String (substring
, toLowerCase
etc). None of them change the contents of the string.
Note that you don't really need to do this in a condition - after all, if the sentence doesn't contain "and"
, it does no harm to perform the replacement:
String sentence = "Define, Measure, Analyze, Design and Verify";
sentence = sentence.replace("and", " ");
Use the IP instead:
DROP USER 'root'@'127.0.0.1'; GRANT ALL PRIVILEGES ON . TO 'root'@'%';
For more possibilities, see this link.
To create the root user, seeing as MySQL is local & all, execute the following from the command line (Start > Run > "cmd" without quotes):
mysqladmin -u root password 'mynewpassword'
The way to "start" the array that you want is:
arr = np.empty((0,3), int)
Which is an empty array but it has the proper dimensionality.
>>> arr
array([], shape=(0, 3), dtype=int64)
Then be sure to append along axis 0:
arr = np.append(arr, np.array([[1,2,3]]), axis=0)
arr = np.append(arr, np.array([[4,5,6]]), axis=0)
But, @jonrsharpe is right. In fact, if you're going to be appending in a loop, it would be much faster to append to a list as in your first example, then convert to a numpy array at the end, since you're really not using numpy as intended during the loop:
In [210]: %%timeit
.....: l = []
.....: for i in xrange(1000):
.....: l.append([3*i+1,3*i+2,3*i+3])
.....: l = np.asarray(l)
.....:
1000 loops, best of 3: 1.18 ms per loop
In [211]: %%timeit
.....: a = np.empty((0,3), int)
.....: for i in xrange(1000):
.....: a = np.append(a, 3*i+np.array([[1,2,3]]), 0)
.....:
100 loops, best of 3: 18.5 ms per loop
In [214]: np.allclose(a, l)
Out[214]: True
The numpythonic way to do it depends on your application, but it would be more like:
In [220]: timeit n = np.arange(1,3001).reshape(1000,3)
100000 loops, best of 3: 5.93 µs per loop
In [221]: np.allclose(a, n)
Out[221]: True
Unless you unpack them, assets remain inside the apk. Accordingly, there isn't a path you can feed into a File. The path you've given in your question will work with/in a WebView, but I think that's a special case for WebView.
You'll need to unpack the file or use it directly.
If you have a Context, you can use context.getAssets().open("myfoldername/myfilename");
to open an InputStream on the file. With the InputStream you can use it directly, or write it out somewhere (after which you can use it with File).
This Proxy will expose the buffer as any of the TypedArrays, without any copy. :
https://www.npmjs.com/package/node-buffer-as-typedarray
It only works on LE, but can be easily ported to BE. Also, never got to actually test how efficient this is.
assertTrue
will fail if the checked value is false, and assertFalse
will do the opposite: fail if the checked value is true.
Another thing, your last assertEquals will very likely fail, as it will compare the "Book was already checked out" string with the output of m1.checkOut(b1,p2). It needs a third parameter (the second value to check for equality).
The new C# 8.0 range operator can be a great shortcut to achieve this.
Example #1 (to answer the question):
string myString = "abcdxxx";
var shortenedString = myString[0..^3]
System.Console.WriteLine(shortenedString);
// Results: abcd
Example #2 (to show you how awesome range operators are):
string s = "FooBar99";
// If the last 2 characters of the string are 99 then change to 98
s = s[^2..] == "99" ? s[0..^2] + "98" : s;
System.Console.WriteLine(s);
// Results: FooBar98
Use TablePlus application: Right-Click on the table name from the right panel Choose Import... > From CSV Choose CSV file Review column matching and hit Import All done!
Here is a more compact version of Jaydeep's idea of showing one dialog after the other. I like this solution because it has no dependencies.
Date value = new Date();
final Calendar cal = Calendar.getInstance();
cal.setTime(value);
new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
@Override public void onDateSet(DatePicker view,
int y, int m, int d) {
cal.set(Calendar.YEAR, y);
cal.set(Calendar.MONTH, m);
cal.set(Calendar.DAY_OF_MONTH, d);
// now show the time picker
new TimePickerDialog(NoteEditor.this,
new TimePickerDialog.OnTimeSetListener() {
@Override public void onTimeSet(TimePicker view,
int h, int min) {
cal.set(Calendar.HOUR_OF_DAY, h);
cal.set(Calendar.MINUTE, min);
value = cal.getTime();
}
}, cal.get(Calendar.HOUR_OF_DAY),
cal.get(Calendar.MINUTE), true).show();
}
}, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH)).show();
You will have to set your custom WebviewClient overriding shouldOverrideUrlLoading method for your webview before loading the url.
mWebView.setWebViewClient(new WebViewClient()
{
@SuppressWarnings("deprecation")
@Override
public boolean shouldOverrideUrlLoading(WebView webView, String url)
{
return shouldOverrideUrlLoading(url);
}
@TargetApi(Build.VERSION_CODES.N)
@Override
public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest request)
{
Uri uri = request.getUrl();
return shouldOverrideUrlLoading(uri.toString());
}
private boolean shouldOverrideUrlLoading(final String url)
{
Log.i(TAG, "shouldOverrideUrlLoading() URL : " + url);
// Here put your code
return true; // Returning True means that application wants to leave the current WebView and handle the url itself, otherwise return false.
}
});
Checkout the example code for handling redirect urls and open PDF without download, in webview. https://gist.github.com/ashishdas09/014a408f9f37504eb2608d98abf49500
Install an interval:
<script type="text/javascript">
setInterval(page_refresh, 5*60000); //NOTE: period is passed in milliseconds
</script>
There are multiple ways to do this.
Events - already explained well.
ui router - explained above.
*
<superhero flight speed strength> Superman is here! </superhero>
<superhero speed> Flash is here! </superhero>
*
app.directive('superhero', function(){
return {
restrict: 'E',
scope:{}, // IMPORTANT - to make the scope isolated else we will pollute it in case of a multiple components.
controller: function($scope){
$scope.abilities = [];
this.addStrength = function(){
$scope.abilities.push("strength");
}
this.addSpeed = function(){
$scope.abilities.push("speed");
}
this.addFlight = function(){
$scope.abilities.push("flight");
}
},
link: function(scope, element, attrs){
element.addClass('button');
element.on('mouseenter', function(){
console.log(scope.abilities);
})
}
}
});
app.directive('strength', function(){
return{
require:'superhero',
link: function(scope, element, attrs, superHeroCtrl){
superHeroCtrl.addStrength();
}
}
});
app.directive('speed', function(){
return{
require:'superhero',
link: function(scope, element, attrs, superHeroCtrl){
superHeroCtrl.addSpeed();
}
}
});
app.directive('flight', function(){
return{
require:'superhero',
link: function(scope, element, attrs, superHeroCtrl){
superHeroCtrl.addFlight();
}
}
});
This will work:
tr:hover {
background: #000 !important;
}
If you want to only apply bg-color on TD then:
tr:hover td {
background: #c7d4dd !important;
}
It will even overwrite your given color and apply this forcefully.
One part of @gaurav solution worked for jQuery 2.1.3 and JQuery UI 1.10.2 with multiple sliders. My project is using four range sliders to filter data with this filter.js plugin. Other solutions were resetting the slider handles back to their starting end points just fine, but apparently they were not firing an event that filter.js understood. So here's how I looped through the sliders:
$("yourSliderSelection").each (function () {
var hs = $(this);
var options = $(this).slider('option');
//reset the ui
$(this).slider( 'values', [ options.min, options.max ] );
//refresh/trigger event so that filter.js can reset handling the data
hs.slider('option', 'slide').call(
hs,
null,
{
handle: $('.ui-slider-handle', hs),
values: [options.min, options.max]
}
);
});
The hs.slider()
code resets the data, but not the UI in my scenario. Hope this helps others.
In VB.NET, you need to use the GetType
method to retrieve the type of an instance of an object, and the GetType()
operator to retrieve the type of another known type.
Once you have the two types, you can simply compare them using the Is
operator.
So your code should actually be written like this:
Sub FillCategories(ByVal Obj As Object)
Dim cmd As New SqlCommand("sp_Resources_Categories", Conn)
cmd.CommandType = CommandType.StoredProcedure
Obj.DataSource = cmd.ExecuteReader
If Obj.GetType() Is GetType(System.Web.UI.WebControls.DropDownList) Then
End If
Obj.DataBind()
End Sub
You can also use the TypeOf
operator instead of the GetType
method. Note that this tests if your object is compatible with the given type, not that it is the same type. That would look like this:
If TypeOf Obj Is System.Web.UI.WebControls.DropDownList Then
End If
Totally trivial, irrelevant nitpick: Traditionally, the names of parameters are camelCased (which means they always start with a lower-case letter) when writing .NET code (either VB.NET or C#). This makes them easy to distinguish at a glance from classes, types, methods, etc.
Here is the function example trim generic type of array object
const trimArrayObject = <T>(items: T[]) => {
items.forEach(function (o) {
for (let [key, value] of Object.entries(o)) {
const keyName = <keyof typeof o>key;
if (Array.isArray(value)) {
trimArrayObject(value);
} else if (typeof o[keyName] === "string") {
o[keyName] = value.trim();
}
}
});
};
I solved the problem by cat'ing all the pems together:
cat cert.pem chain.pem fullchain.pem >all.pem
openssl pkcs12 -export -in all.pem -inkey privkey.pem -out cert_and_key.p12 -name tomcat -CAfile chain.pem -caname root -password MYPASSWORD
keytool -importkeystore -deststorepass MYPASSWORD -destkeypass MYPASSWORD -destkeystore MyDSKeyStore.jks -srckeystore cert_and_key.p12 -srcstoretype PKCS12 -srcstorepass MYPASSWORD -alias tomcat
keytool -import -trustcacerts -alias root -file chain.pem -keystore MyDSKeyStore.jks -storepass MYPASSWORD
(keytool didn't know what to do with a PKCS7 formatted key)
I got all the pems from letsencrypt
server.session.timeout=1200
server.servlet.session.timeout=10m
If your elements are glitching this is probably because when you change the position to relative
the Y position of the footer increases which tries to send the item back to fixed
which creates a loop. You can avoid this by setting two different cases when scrolling up and down. You don't even need to reference the fixed element, just the footer, and window size.
const footer = document.querySelector('footer');
document.addEventListener("scroll", checkScroll);
let prevY = window.scrollY + window.innerHeight;
function checkScroll() {
let footerTop = getRectTop(footer) + window.scrollY;
let windowBottomY = window.scrollY + window.innerHeight;
if (prevY < windowBottomY) { // Scroll Down
if (windowBottomY > footerTop)
setScrolledToFooter(true) // using React state. Change class or change style in JS.
} else { // Scroll Up
if (windowBottomY <= footerTop)
setScrolledToFooter(false)
}
prevY = windowBottomY
};
function getRectTop(el) {
var rect = el.getBoundingClientRect();
return rect.top;
}
and the position of the element in the style object as follows:
position: scrolledToFooter ? 'relative' : 'fixed'
Consider following code
<ul id="myTask">
<li>Coding</li>
<li>Answering</li>
<li>Getting Paid</li>
</ul>
Now, here goes the difference
// Remove the myTask item when clicked.
$('#myTask').children().click(function () {
$(this).remove()
});
Now, what if we add a myTask again?
$('#myTask').append('<li>Answer this question on SO</li>');
Clicking this myTask item will not remove it from the list, since it doesn't have any event handlers bound. If instead we'd used .on
, the new item would work without any extra effort on our part. Here's how the .on version would look:
$('#myTask').on('click', 'li', function (event) {
$(event.target).remove()
});
Summary:
The difference between .on()
and .click()
would be that .click()
may not work when the DOM elements associated with the .click()
event are added dynamically at a later point while .on()
can be used in situations where the DOM elements associated with the .on()
call may be generated dynamically at a later point.
I'd suggest that the -i
means it does match "ABC", but the difference is in the output. -i
doesn't manipulate the input, so it won't change "ABC" to "abc" because you specified "abc" as the pattern. -o
says it only shows the part of the output that matches the pattern specified, it doesn't say about matching input.
The output of echo "ABC" | grep -i abc
is ABC
, the -o
shows output matching "abc" so nothing shows:
Naos:~ mattlacey$ echo "ABC" | grep -i abc | grep -o abc
Naos:~ mattlacey$ echo "ABC" | grep -i abc | grep -o ABC
ABC
A dependency has to be available from the registry
to be installed just by specifying a version
descriptor.
You can certainly create and use your own registry instead of registry.npmjs.org
if your projects shouldn't be shared publicly.
But, if it's not in a registry, it'll have to be referenced by URL or Git URL. To specify a version with a Git URL, include an appropriate <commit-ish>
, such as a tag, at the end as a URL fragment.
Example, for a tag named 0.3.1
:
"dependencies": {
"myprivatemodule": "[email protected]:...#0.3.1"
}
Note: The above snippet shows the base URL the same as it was posted in the question.
The snipped portion (
...
) should be filled in:"myprivatemodule": "[email protected]:{owner}/{project}.git#0.3.1"
And, a different address format will be needed when SSH access isn't available:
"myprivatemodule": "git://github.com/{owner}/{project}.git#0.3.1"
Depending on your OS, you may also be able to link
to the dependency in another folder where you have it cloned from Github.
The list function will do this
>>> list('foo')
['f', 'o', 'o']
Probably I am too late to answer. But if anybody need it, following works fine, as I have used it a lot of times.
npm config set registry=https://registry.npmjs.com/
Overload less than operator, then sort. This is an example I found off the web...
class MyData
{
public:
int m_iData;
string m_strSomeOtherData;
bool operator<(const MyData &rhs) const { return m_iData < rhs.m_iData; }
};
std::sort(myvector.begin(), myvector.end());
Source: here
I'm gonna try to write this as a tutorial for you so it becomes easy to follow.
NOTE: This tutorial only works for older raspbian images. For the newer Raspbian based on Debian Buster see the following how-to in this thread: https://stackoverflow.com/a/58559140/869402
Before you start you need to make sure the following is installed:
apt-get install git rsync cmake libc6-i386 lib32z1 lib32stdc++6
Start with making a folder in your home directory called raspberrypi
.
Go in to this folder and pull down the ENTIRE tools folder you mentioned above:
git clone git://github.com/raspberrypi/tools.git
You wanted to use the following of the 3 ones, gcc-linaro-arm-linux-gnueabihf-raspbian
, if I did not read wrong.
Go into your home directory and add:
export PATH=$PATH:$HOME/raspberrypi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin
to the end of the file named ~/.bashrc
Now you can either log out and log back in (i.e. restart your terminal session), or run . ~/.bashrc
in your terminal to pick up the PATH
addition in your current terminal session.
Now, verify that you can access the compiler arm-linux-gnueabihf-gcc -v
. You should get something like this:
Using built-in specs.
COLLECT_GCC=arm-linux-gnueabihf-gcc
COLLECT_LTO_WRAPPER=/home/tudhalyas/raspberrypi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/../libexec/gcc/arm-linux-gnueabihf/4.7.2/lto-wrapper
Target: arm-linux-gnueabihf
Configured with: /cbuild/slaves/oort61/crosstool-ng/builds/arm-linux-gnueabihf-raspbian-linux/.b
uild/src/gcc-linaro-4.7-2012.08/configure --build=i686-build_pc-linux-gnu --host=i686-build_pc-
linux-gnu --target=arm-linux-gnueabihf --prefix=/cbuild/slaves/oort61/crosstool-ng/builds/arm-l
inux-gnueabihf-raspbian-linux/install --with-sysroot=/cbuild/slaves/oort61/crosstool-ng/builds/
arm-linux-gnueabihf-raspbian-linux/install/arm-linux-gnueabihf/libc --enable-languages=c,c++,fo
rtran --disable-multilib --with-arch=armv6 --with-tune=arm1176jz-s --with-fpu=vfp --with-float=
hard --with-pkgversion='crosstool-NG linaro-1.13.1+bzr2458 - Linaro GCC 2012.08' --with-bugurl=
https://bugs.launchpad.net/gcc-linaro --enable-__cxa_atexit --enable-libmudflap --enable-libgom
p --enable-libssp --with-gmp=/cbuild/slaves/oort61/crosstool-ng/builds/arm-linux-gnueabihf-rasp
bian-linux/.build/arm-linux-gnueabihf/build/static --with-mpfr=/cbuild/slaves/oort61/crosstool-
ng/builds/arm-linux-gnueabihf-raspbian-linux/.build/arm-linux-gnueabihf/build/static --with-mpc
=/cbuild/slaves/oort61/crosstool-ng/builds/arm-linux-gnueabihf-raspbian-linux/.build/arm-linux-
gnueabihf/build/static --with-ppl=/cbuild/slaves/oort61/crosstool-ng/builds/arm-linux-gnueabihf
-raspbian-linux/.build/arm-linux-gnueabihf/build/static --with-cloog=/cbuild/slaves/oort61/cros
stool-ng/builds/arm-linux-gnueabihf-raspbian-linux/.build/arm-linux-gnueabihf/build/static --wi
th-libelf=/cbuild/slaves/oort61/crosstool-ng/builds/arm-linux-gnueabihf-raspbian-linux/.build/a
rm-linux-gnueabihf/build/static --with-host-libstdcxx='-L/cbuild/slaves/oort61/crosstool-ng/bui
lds/arm-linux-gnueabihf-raspbian-linux/.build/arm-linux-gnueabihf/build/static/lib -lpwl' --ena
ble-threads=posix --disable-libstdcxx-pch --enable-linker-build-id --enable-plugin --enable-gol
d --with-local-prefix=/cbuild/slaves/oort61/crosstool-ng/builds/arm-linux-gnueabihf-raspbian-li
nux/install/arm-linux-gnueabihf/libc --enable-c99 --enable-long-long
Thread model: posix
gcc version 4.7.2 20120731 (prerelease) (crosstool-NG linaro-1.13.1+bzr2458 - Linaro GCC 2012.08
)
We're not done yet! So far, we've only done the basics.
In your raspberrypi
folder, make a folder called rootfs
.
Now you need to copy the entire /lib
and /usr
directory to this newly created folder. I usually bring the rpi image up and copy it via rsync:
rsync -rl --delete-after --safe-links [email protected]:/{lib,usr} $HOME/raspberrypi/rootfs
where 192.168.1.PI
is replaced by the IP of your Raspberry Pi.
Now, we need to write a cmake
config file. Open ~/home/raspberrypi/pi.cmake
in your favorite editor and insert the following:
SET(CMAKE_SYSTEM_NAME Linux)
SET(CMAKE_SYSTEM_VERSION 1)
SET(CMAKE_C_COMPILER $ENV{HOME}/raspberrypi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-gcc)
SET(CMAKE_CXX_COMPILER $ENV{HOME}/raspberrypi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++)
SET(CMAKE_FIND_ROOT_PATH $ENV{HOME}/raspberrypi/rootfs)
SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
Now you should be able to compile your cmake
programs simply by adding this extra flag: -D CMAKE_TOOLCHAIN_FILE=$HOME/raspberrypi/pi.cmake
.
Using a cmake hello world example:
git clone https://github.com/jameskbride/cmake-hello-world.git
cd cmake-hello-world
mkdir build
cd build
cmake -D CMAKE_TOOLCHAIN_FILE=$HOME/raspberrypi/pi.cmake ../
make
scp CMakeHelloWorld [email protected]:/home/pi/
ssh [email protected] ./CMakeHelloWorld
Based on my experience with AngularJS modals so far I believe that the most elegant approach is a dedicated service to which we can provide a partial (HTML) template to be displayed in a modal.
When we think about it modals are kind of AngularJS routes but just displayed in modal popup.
The AngularUI bootstrap project (http://angular-ui.github.com/bootstrap/) has an excellent $modal
service (used to be called $dialog prior to version 0.6.0) that is an implementation of a service to display partial's content as a modal popup.
How I redirect to an area is add it as a parameter
@Html.Action("Action", "Controller", new { area = "AreaName" })
for the href portion of a link I use
@Url.Action("Action", "Controller", new { area = "AreaName" })
TASKLIST
does not set errorlevel.
echo off
tasklist /fi "imagename eq notepad.exe" |find ":" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"
exit
should do the job, since ":" should appear in TASKLIST
output only if the task is NOT found, hence FIND
will set the errorlevel to 0
for not found
and 1
for found
Nevertheless,
taskkill /f /im "notepad.exe"
will kill a notepad task if it exists - it can do nothing if no notepad task exists, so you don't really need to test - unless there's something else you want to do...like perhaps
echo off
tasklist /fi "imagename eq notepad.exe" |find ":" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"&exit
which would appear to do as you ask - kill the notepad process if it exists, then exit - otherwise continue with the batch
Your fragment class should implement OnClickListener
public class SmartTvControllerFragment extends Fragment implements View.OnClickListener
Then get view, link button and set onClickListener like in example below
View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.smart_tv_controller_fragment, container, false);
upButton = (Button) view.findViewById(R.id.smart_tv_controller_framgment_up_button);
upButton.setOnClickListener(this);
return view;
}
And then add onClickListener method and do what you want.
@Override
public void onClick(View v) {
//do what you want to do when button is clicked
switch (v.getId()) {
case R.id.textView_help:
switchFragment(HelpFragment.TAG);
break;
case R.id.textView_settings:
switchFragment(SettingsFragment.TAG);
break;
}
}
This is my example of code, but I hope you understood
If you aren’t using Auto Layout, have you tried setting the child view’s autoresize mask? Try this:
myChildeView.autoresizingMask = (UIViewAutoresizingFlexibleWidth |
UIViewAutoresizingFlexibleHeight);
Also, you may need to call
myParentView.autoresizesSubviews = YES;
to get the parent view to resize its subviews automatically when its frame changes.
If you’re still seeing the child view drawing outside of the parent view’s frame, there’s a good chance that the parent view is not clipping its contents. To fix that, call
myParentView.clipsToBounds = YES;
According to the Cloudera documentation - What's New in CDH 5.7.0 it includes Spark 1.6.0.
http://docs.ansible.com/ansible/latest/plugins/lookup/dig.html
so in template, for e. g.:
{{ lookup('dig', ansible_host) }}
Notes:
But still it serves 99 % (figuratively speaking) of use cases.
with parse.JSON
var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );
This is a modified version of the Nibble to Hex method
void hexArrayToStr(unsigned char* info, unsigned int infoLength, char **buffer) {
const char* pszNibbleToHex = {"0123456789ABCDEF"};
int nNibble, i;
if (infoLength > 0) {
if (info != NULL) {
*buffer = (char *) malloc((infoLength * 2) + 1);
buffer[0][(infoLength * 2)] = 0;
for (i = 0; i < infoLength; i++) {
nNibble = info[i] >> 4;
buffer[0][2 * i] = pszNibbleToHex[nNibble];
nNibble = info[i] & 0x0F;
buffer[0][2 * i + 1] = pszNibbleToHex[nNibble];
}
} else {
*buffer = NULL;
}
} else {
*buffer = NULL;
}
}
It is always an option to enter python on the command line with the command python
then import your file so import example_file
then run the command with example_file.hello()
This avoids the weird .pyc copy function that crops up every time you run python -c etc.
Maybe not as convenient as a single-command, but a good quick fix to text a file from the command line, and allows you to use python to call and execute your file.
For preloading background images set with CSS, the most efficient answer i came up with was a modified version of some code I found that did not work:
$(':hidden').each(function() {
var backgroundImage = $(this).css("background-image");
if (backgroundImage != 'none') {
tempImage = new Image();
tempImage.src = backgroundImage;
}
});
The massive benefit of this is that you don't need to update it when you bring in new background images in the future, it will find the new ones and preload them!
When doing this from DBeaver I had to go to "Connection settings" -> "SSL" tab and then :
Note that this is suitable for local development only.
When you create local variables inside a function that are created on the stack, they most likely get overwritten in memory when exiting the function.
So code like this in most C++ implementations will not work:
char[] populateChar()
{
char* ch = "wonet return me";
return ch;
}
A fix is to create the variable that want to be populated outside the function or where you want to use it, and then pass it as a parameter and manipulate the function, example:
void populateChar(char* ch){
strcpy(ch, "fill me, Will. This will stay", size); // This will work as long as it won't overflow it.
}
int main(){
char ch[100]; // Reserve memory on the stack outside the function
populateChar(ch); // Populate the array
}
A C++11 solution using std::move(ch) to cast lvalues to rvalues:
void populateChar(char* && fillme){
fillme = new char[20];
strcpy(fillme, "this worked for me");
}
int main(){
char* ch;
populateChar(std::move(ch));
return 0;
}
Or this option in C++11:
char* populateChar(){
char* ch = "test char";
// Will change from lvalue to r value
return std::move(ch);
}
int main(){
char* ch = populateChar();
return 0;
}
Even better
#include <stdio.h>
int
main(void)
{
char *line = NULL;
size_t count;
char *dup_line;
getline(&line,&count, stdin);
dup_line=strdup(line);
puts(dup_line);
free(dup_line);
free(line);
return 0;
}
Found it!
Change host: localhost
in config/database.yml to host: 127.0.0.1
to make rails connect over TCP/IP instead of local socket.
development:
adapter: mysql2
host: 127.0.0.1
username: root
password: xxxx
database: xxxx
I was also facing the same problem with gradle. Now I have solved by installing the highlighted in red. To navigate on this page Open Android studio > Tool > Android > SDK Manager > Appearance & Behavior > System Settings > Android SDK > SDK Tools (from tab options) > Show Package details(check box on the right bottom corner). After installing these just refresh the gradle everything will be resolved.
I've changed the recursion to iteration.
def MovingTheBall(listOfBalls,position,numCell):
while 1:
stop=1
positionTmp = (position[0]+choice([-1,0,1]),position[1]+choice([-1,0,1]),0)
for i in range(0,len(listOfBalls)):
if positionTmp==listOfBalls[i].pos:
stop=0
if stop==1:
if (positionTmp[0]==0 or positionTmp[0]>=numCell or positionTmp[0]<=-numCell or positionTmp[1]>=numCell or positionTmp[1]<=-numCell):
stop=0
else:
return positionTmp
Works good :D
For everyone who felt they want to run away with all the steps and screen shots on the (great!) above answers, this worked for me with android studio 2.2.1
:
Create a new project, name it as you want and take the default (minSdkVersion 15 is fine).
Download the zip file from here: https://sourceforge.net/projects/opencvlibrary/files/opencv-android/ (I downloaded 3.2.0 version, but there may be a newer versions).
Unzip the zip file, the best place is in your workspace folder, but it not really matter.
Inside Android Studio
, click File->New-> Import Module
and navigate to \path_to_your_unzipped_file\OpenCV-android-sdk\sdk\java
and hit Ok, then accept all default dialogs.
In the gradle
file of your app
module, add this to the dependencies block:
dependencies {
compile project(':openCVLibraryXYZ')
//rest of code
}
Where XYZ is the exact version you downloaded, for example in my case:
dependencies {
compile project(':openCVLibrary320')
//rest of code
}
The align-items
, or respectively align-content
attribute controls this behaviour.
align-items
defines the items' positioning perpendicularly to flex-direction
.
The default flex-direction
is row
, therfore vertical placement can be controlled with align-items
.
There is also the align-self
attribute to control the alignment on a per item basis.
#a {_x000D_
display:flex;_x000D_
_x000D_
align-items:flex-start;_x000D_
align-content:flex-start;_x000D_
}_x000D_
_x000D_
#a > div {_x000D_
_x000D_
background-color:red;_x000D_
padding:5px;_x000D_
margin:2px;_x000D_
}_x000D_
#a > #c {_x000D_
align-self:stretch;_x000D_
}
_x000D_
<div id="a">_x000D_
_x000D_
<div id="b">left</div>_x000D_
<div id="c">middle</div>_x000D_
<div>right<br>right<br>right<br>right<br>right<br></div>_x000D_
_x000D_
</div>
_x000D_
css-tricks has an excellent article on the topic. I recommend reading it a couple of times.
Mostly, I prefer to use this syntax :
if ($('#MyId')!= null) {
// dostuff
}
Even if this code is not commented, the functionality is obvious.
<android.support.v4.widget.NestedScrollView
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/btmlyt"
android:layout_below="@+id/deshead_tv">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:id="@+id/des_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/btmlyt"
android:background="@android:color/white"
android:paddingLeft="3dp"
android:paddingRight="3dp"
android:scrollbars="vertical"
android:paddingTop="3dp"
android:text="description"
android:textColor="@android:color/black"
android:textSize="18sp" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
There is a somehow recommended directory structure mentioned at https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-structuring-your-code.html
You can create a api
folder and put your controllers there.
If you have some configuration beans, put them in a separate package too.
I've been having this problem in Linux, with a project that I renamed, removed, and reimported. Somewhere in the .metadata, it's still there evidently.
I finally solved it by the following steps:
close Eclipse mv .metadata .metadata_orig start Eclipse reset default workspace reimport projects
This may not work for everyone, especially if you already have lots of projects in multiple workspaces. But if you're used to reconfiguring Eclipse (which I do every time I upgrade to the next Eclipse release) it's not too bad.
In the following httpd.conf
file, configure the ServerName
properly.
/etc/httpd/conf/httpd.conf
Like below:
ServerName 127.0.0.1:80
or
ServerName sitename
This resolved similar issue I was facing.
Just to add an extra, if you want to install it in your pip file it can be added like this:
-e git+https://github.com/tangentlabs/django-oscar-paypal.git@issue/34/oscar-0.6#egg=django-oscar-paypal
It will be saved as an egg though.
I was having the same problem. It seems that passing Me.ComboBox1.Value
as an argument for the Vlookup
function is causing the issue. What I did was assign this value to a double and then put it into the Vlookup function.
Dim x As Double
x = Me.ComboBox1.Value
Me.TextBox1.Value = Application.WorksheetFunction.VLookup(x, Worksheets("Sheet3").Range("Names"), 2, False)
Or, for a shorter method, you can just convert the type within the Vlookup function using Cdbl(<Value>)
.
So it would end up being
Me.TextBox1.Value = Application.WorksheetFunction.VLookup(Cdbl(Me.ComboBox1.Value), Worksheets("Sheet3").Range("Names"), 2, False)
Strange as it may sound, it works for me.
Hope this helps.
What's the first part of your Subversion repository URL?
I can't guarantee the first four since it's possible to reconfigure everything to use different ports, of if you go through a proxy of some sort.
If you're using a VPN, you may have to configure your VPN client to reroute these to their correct ports. A lot of places don't configure their correctly VPNs to do this type of proxying. It's either because they have some sort of anal-retentive IT person who's being overly security conscious, or because they simply don't know any better. Even worse, they'll give you a client where this stuff can't be reconfigured.
The only way around that is to log into a local machine over the VPN, and then do everything from that system.
Yes there is a difference in the performance of both:
jQuery('#id').show()
is slower than jQuery('#id').css("display","block")
as in former case extra work is to be done for retrieving the initial state from the jquery cache as display is not a binary attribute it can be inline
,block
,none
,table
, etc.
similar is the case with hide()
method.
.content .right{
overflow: auto;
background-color: red;
}
+1 for Merkuro, but if the size of the float changes your fixed margin will fail.
If u use above CSS on the right div
it will nicely change size with changing size on the left float. It is a bit more flexible like that.
Check the fiddle here: http://jsfiddle.net/9ZHBK/144/
in a custom UITableViewCell -controller add this
-(void)layoutSubviews {
CGRect newCellSubViewsFrame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
CGRect newCellViewFrame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, self.frame.size.height);
self.contentView.frame = self.contentView.bounds = self.backgroundView.frame = self.accessoryView.frame = newCellSubViewsFrame;
self.frame = newCellViewFrame;
[super layoutSubviews];
}
In the UITableView -controller add this
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [indexPath row] * 1.5; // your dynamic height...
}
You can also get the page count using
$im->getNumberImages();
Then you can can create thumbs of all the pages using a loop, eg.
'file.pdf['.$x.']'
In laymen's terms an unsigned int is an integer that can not be negative and thus has a higher range of positive values that it can assume. A signed int is an integer that can be negative but has a lower positive range in exchange for more negative values it can assume.
No need to use a particular class Language,
Just replace it with :
KeyValuePair<string,string>
On macOs I manage to fix this by adding:
export ANDROID_HOME=$HOME/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/emulator
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH:$ANDROID_HOME/platform-tools
to ~/.zsh_profile file.
and than type to your terminal
source $HOME/.zsh_profile
The issue was caused by using iTerm2 shell so it's required to edit its own config instead of default $HOME/.bash_profile as described in the official documentation https://reactnative.dev/docs/environment-setup
Since AngularJS 1.5 we should use $onInit
which is available on any AngularJS component. Taken from the component lifecycle documentation since v1.5 its the preffered way:
$onInit() - Called on each controller after all the controllers on an element have been constructed and had their bindings initialized (and before the pre & post linking functions for the directives on this element). This is a good place to put initialization code for your controller.
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {
//default state
$scope.name = '';
//all your init controller goodness in here
this.$onInit = function () {
$scope.name = 'Superhero';
}
});
The component lifecycle gives us the ability to handle component stuff in a good way. It allows us to create events for e.g. "init", "change" or "destroy" of an component. In that way we are able to manage stuff which is depending on the lifecycle of an component. This little example shows to register & unregister an $rootScope
event listener $on
. By knowing, that an event $on
binded on $rootScope
will not be undinded when the controller loses its reference in the view or getting destroyed we need to destroy a $rootScope.$on
listener manually. A good place to put that stuff is $onDestroy
lifecycle function of an component:
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope, $rootScope) {
var registerScope = null;
this.$onInit = function () {
//register rootScope event
registerScope = $rootScope.$on('someEvent', function(event) {
console.log("fired");
});
}
this.$onDestroy = function () {
//unregister rootScope event by calling the return function
registerScope();
}
});
To get properties from dynamic doc
when .GetType()
returns null
, try this:
var keyValuePairs = ((System.Collections.Generic.IDictionary<string, object>)doc);
var val = keyValuePairs["propertyName"].ToObject<YourModel>;
First things first, you need to check to make sure that localStorage is enabled. I would recommend doing it like this:
var localStorageEnabled = false;
try { localStorageEnabled = !!localStorage; } catch(e) {};
Yes, you can (in some cases) just check to see if the localStorage is a member of the window object. However, there are iframe sandboxing options (among other things) that will throw an exception if you even attempt to access the index 'localStorage'. Thus, for best-practices reasons, this is the best way to check to see if the localStorage is enabled. Then, you can just clear the localStorage like so.
if (localStorageEnabled) localStorage.clear();
For example, you could clear the localStorage after an error occurs in webkit browsers like so.
// clears the local storage upon error
if (localStorageEnabled)
window.onerror = localStorage.clear.bind(localStorage);
In the above example, you need the .bind(window)
because without it, the localStorage.clear
function will run in the context of the window
object, instead of the localStorage
object making it silently fail. To demonstrate this, look at the below example:
window.onerror = localStorage.clear;
is the same as:
window.onerror = function(){
localStorage.clear.call(window);
}
Install it by running
python setup.py install
Better yet, you can download from github. Install git via apt-get install git
and then follow this steps:
git clone https://github.com/mwaskom/seaborn.git
cd seaborn
python setup.py install
create a macro like this
Option Compare Database
Sub a()
DoCmd.RunSQL "DELETE * from TABLENAME where CONDITIONS"
DoCmd.RunSQL "DELETE * from TABLENAME where CONDITIONS"
End Sub
From your code, it looks like provider
is a variant or some other variable, and not an object.
Is Nothing
is for objects only, yet later you say it's a value that should either be NULL or NOT NULL, which would be handled by IsNull
.
Try using:
If Not IsNull(provider) Then
url = url & "&provider=" & provider
End if
Alternately, if that doesn't work, try:
If provider <> "" Then
url = url & "&provider=" & provider
End if
One reason why the top answer and others wont work for you is because it is missing a critical line. (note many API manuals leave out this necessity)
request.PreAuthenticate = true;
The easiest way is this.
byte[] bytes = rs.getBytes("my_field");
Let's fit the model:
> library(ISwR)
> fit <- lm(metabolic.rate ~ body.weight, rmr)
> summary(fit)
Call:
lm(formula = metabolic.rate ~ body.weight, data = rmr)
Residuals:
Min 1Q Median 3Q Max
-245.74 -113.99 -32.05 104.96 484.81
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 811.2267 76.9755 10.539 2.29e-13 ***
body.weight 7.0595 0.9776 7.221 7.03e-09 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 157.9 on 42 degrees of freedom
Multiple R-squared: 0.5539, Adjusted R-squared: 0.5433
F-statistic: 52.15 on 1 and 42 DF, p-value: 7.025e-09
The 95% confidence interval for the slope is the estimated coefficient (7.0595) ± two standard errors (0.9776).
This can be computed using confint
:
> confint(fit, 'body.weight', level=0.95)
2.5 % 97.5 %
body.weight 5.086656 9.0324
You can import .sql file using the standard input like this:
mysql -u <user> -p<password> <dbname> < file.sql
Note: There shouldn't space between <-p>
and <password>
Reference: http://dev.mysql.com/doc/refman/5.0/en/mysql-batch-commands.html
Note for suggested edits: This answer was slightly changed by suggested edits to use inline password parameter. I can recommend it for scripts but you should be aware that when you write password directly in the parameter (-p<password>
) it may be cached by a shell history revealing your password to anyone who can read the history file. Whereas -p
asks you to input password by standard input.
First of all go to the /home directorty then open invisible shell script with some text editor, ~/.bash_profile (macOS) or ~/.bashrc (linux)
go to the bottom, you would see something like this,
export LD_LIBRARY_PATH = /usr/local/lib
change this like that( remove blank point around the =
),
export LD_LIBRARY_PATH=/usr/local/lib
it should be useful.
Here is a supplemental answer that shows some fuller code:
Container(
decoration: BoxDecoration(
color: Colors.tealAccent,
borderRadius: BorderRadius.circular(32),
),
child: TextField(
decoration: InputDecoration(
hintStyle: TextStyle(fontSize: 17),
hintText: 'Search your trips',
suffixIcon: Icon(Icons.search),
border: InputBorder.none,
contentPadding: EdgeInsets.all(20),
),
),
),
Notes:
Colors.teal
.InputDecoration
also has a filled
and fillColor
property, but I couldn't get them to have a corner radius, so I used a container instead.For someone who needs an explanation and an example of how to use a regxp in Eclipse. Here is my example illustrating the problem.
I want to rename
/download.mp4^lecture_id=271
to
/271.mp4
And there can be multiple of these.
Here is how it should be done.
Then hit find/replace button
The previous posts information is correct, but it does not have details on how to link containers, which should be connected as "external_links".
Hope this example make more clear to you:
Suppose you have app1/docker-compose.yml, with two services (svc11 and svc12), and app2/docker-compose.yml with two more services (svc21 and svc22) and suppose you need to connect in a crossed fashion:
svc11 needs to connect to svc22's container
So the configuration should be like this:
this is app1/docker-compose.yml:
version: '2'
services:
svc11:
container_name: container11
[..]
networks:
- default # this network
- app2_default # external network
external_links:
- container22:container22
[..]
svc12:
container_name: container12
[..]
networks:
default: # this network (app1)
driver: bridge
app2_default: # external network (app2)
external: true
this is app2/docker-compose.yml:
version: '2'
services:
svc21:
container_name: container21
[..]
networks:
- default # this network (app2)
- app1_default # external network (app1)
external_links:
- container11:container11
[..]
svc22:
container_name: container22
[..]
networks:
default: # this network (app2)
driver: bridge
app1_default: # external network (app1)
external: true
In kotlin with constructor implementation
Initialize your Recyclerview constructor like below
class ListAdapter(
c: Context,
private var list: List<Project>,
private val itemClick: (Project) -> Unit
) : RecyclerView.Adapter<ListAdapter.ViewHolder>()
return with itemClick in your onCreateViewHolder
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int):ProjectViewHolder {
val view = inflater.inflate(R.layout.list_item, parent, false)
return ViewHolder(view, itemClick)
}
Your onBindViewHolder
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bindProject(list[position])
}
Then with viewHolder class create bindProject function.
class ViewHolder(
view: View,
private val itemClick: (Project) -> Unit
) : RecyclerView.ViewHolder(view) {
private val clientTextCount = 7
val titleTextView: TextView = view.projectTitleTextView
fun bindProject(project: Project) {
with(project) {
titleTextView.text = name
itemView.setOnClickListener { itemClick(this) }
}
}
}
Finally in your activity initialize adapter with lazy
private val adapter: ListAdapter by lazy {
ListAdapter(this, projectList, {
// Here you can implement your onClick function.
})
}
For adding new list to recyclerview initialize below method in your adapter
fun setProjects(projects: List<Project>) {
projectList = projects
notifyDataSetChanged()
}
and call setProjects method anywhere in your activity.
adapter.setProjects(projects)
That's it.
I discovered today that we can now debug Javascript With the developer tool bar plugins integreted in IE 8.
You can use watch, breakpoint, see the call stack etc, similarly to debuggers in professional browsers.
You can also use the statement debugger;
in your JavaScript code the set a breakpoint.
python -dv yourscript.py
That will make the interpreter to run in debug mode and to give you a trace of what the interpreter is doing.
If you want to interactively debug the code you should run it like this:
python -m pdb yourscript.py
That tells the python interpreter to run your script with the module "pdb" which is the python debugger, if you run it like that the interpreter will be executed in interactive mode, much like GDB
You've specifically mentioned a "variable-length array" in your question, so neither of the existing two answers (as I write this) are quite right.
Java doesn't have any concept of a "variable-length array", but it does have Collections, which serve in this capacity. Any collection (technically any "Iterable", a supertype of Collections) can be looped over as simply as this:
Collection<Thing> things = ...;
for (Thing t : things) {
System.out.println(t);
}
EDIT: it's possible I misunderstood what he meant by 'variable-length'. He might have just meant it's a fixed length but not every instance is the same fixed length. In which case the existing answers would be fine. I'm not sure what was meant.
If you're using data binding, then you need to use the ContentRendered event.
For the code below, the Header is NULL when the Loaded event is raised. However, Header gets its value when the ContentRendered event is raised.
<MenuItem Header="{Binding NewGame_Name}" Command="{Binding NewGameCommand}" />
Could you try this one:
create or replace
procedure point_triangle
IS
BEGIN
FOR thisteam in (select P.FIRSTNAME,P.LASTNAME, SUM(P.PTS) S from PLAYERREGULARSEASON P where P.TEAM = 'IND' group by P.FIRSTNAME, P.LASTNAME order by SUM(P.PTS) DESC)
LOOP
dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.S);
END LOOP;
END;
Actually when you pass an array inside a function, the pointer to the original array is passed in the function parameter and thus the changes made to the array inside that function is actually made on the original array.
#include <iostream>
using namespace std;
int* func(int ar[])
{
for(int i=0;i<100;i++)
ar[i]=i;
int *ptr=ar;
return ptr;
}
int main() {
int *p;
int y[100]={0};
p=func(y);
for(int i=0;i<100;i++)
cout<<i<<" : "<<y[i]<<'\n';
}
Run it and you will see the changes
you can download USBview and get all the information you need. Along with the list of devices it will also show you the configuration of each device.
This isn't really a fixing solution but it may help others. Unlike Nick had said for me it was due to code in my program. I have the mega ADK model. The issue was tied to a switch statement for processing and parsing the returned byte[] from the usb connection to the Android. Its very strange because it would compile perfectly every time but would fail as the OP had stated. I commented it out and it worked fine.
Most likely you have different versions of Python installed, ensure that the installed Tesseract is on the same Python version.
which pip3
shows you the path to the pip3 installation and which python3
shows the corresponding path to the Python installation.
Ensure that these two are the same.
Put this code somewhere in your C++ project:
#ifdef _DEBUG
TCHAR version[50];
sprintf(&version[0], "Version = %d", _MSC_VER);
MessageBox(NULL, (LPCTSTR)szMsg, "Visual Studio", MB_OK | MB_ICONINFORMATION);
#endif
Note that _MSC_VER
symbol is Microsoft specific. Here you can find a list of Visual Studio versions with the value for _MSC_VER
for each version.
Use System.DateTime.DaysInMonth, from code sample:
const int July = 7;
const int Feb = 2;
// daysInJuly gets 31.
int daysInJuly = System.DateTime.DaysInMonth(2001, July);
// daysInFeb gets 28 because the year 1998 was not a leap year.
int daysInFeb = System.DateTime.DaysInMonth(1998, Feb);
// daysInFebLeap gets 29 because the year 1996 was a leap year.
int daysInFebLeap = System.DateTime.DaysInMonth(1996, Feb);
While the accepted answer is very true, just want to point out that AllowTransparency has some downfalls. It does not allow child window controls to show up, ie WebBrowser, and it usually forces software rendering which can have negative performance effects.
There is a better work around though.
When you want to create a window with no border that is resizeable and is able to host a WebBrowser control or a Frame control pointed to a URL you simply couldn't, the contents of said control would show empty.
I found a workaround though; in the Window, if you set the WindowStyle to None, ResizeMode to NoResize (bear with me, you will still be able to resize once done) then make sure you have UNCHECKED AllowsTransparency you will have a static sized window with no border and will show the browser control.
Now, you probably still want to be able to resize right? Well we can to that with a interop call:
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();
//Attach this to the MouseDown event of your drag control to move the window in place of the title bar
private void WindowDrag(object sender, MouseButtonEventArgs e) // MouseDown
{
ReleaseCapture();
SendMessage(new WindowInteropHelper(this).Handle,
0xA1, (IntPtr)0x2, (IntPtr)0);
}
//Attach this to the PreviewMousLeftButtonDown event of the grip control in the lower right corner of the form to resize the window
private void WindowResize(object sender, MouseButtonEventArgs e) //PreviewMousLeftButtonDown
{
HwndSource hwndSource = PresentationSource.FromVisual((Visual)sender) as HwndSource;
SendMessage(hwndSource.Handle, 0x112, (IntPtr)61448, IntPtr.Zero);
}
And voila, A WPF window with no border and still movable and resizable without losing compatibility with with controls like WebBrowser
The problem was the table width. I had used width: 100%
for the table. The table columns are adjusted automatically after removing the width tag.
"pull-left" is what you need, it looks like you are using Bootstrap 2, I am not sure if that is available, consider bootstrap 3, unless ofcourse it is a huge rework! ... for Bootstrap 3 but you need to make sure you have 12 columns in each row as well, otherwise you will have issues.
For tracking changes to a folder where the folder was moved, I started using:
git rev-list --all --pretty=oneline -- "*/foo/subfoo/*"
This isn't perfect as it will grab other folders with the same name, but if it is unique, then it seems to work.
In my case, I restart the computer and enable the virtualization technology in BIOS. Then start up computer, open VM Virtual Box
, choose a virtual device, go to Settings
-General
-Basic
-Version
, choose ubuntu(64 bit)
, save the settings then start virtual device from genymotion, everything is ok now.
This is my work around:
1) Add a wrapper div to the recaptcha div.
<div id="recaptcha-wrapper"><div class="g-recaptcha" data-sitekey="..."></div></div>
2) Add javascript/jquery code.
$(function(){
// global variables
captchaResized = false;
captchaWidth = 304;
captchaHeight = 78;
captchaWrapper = $('#recaptcha-wrapper');
captchaElements = $('#rc-imageselect, .g-recaptcha');
resizeCaptcha();
$(window).on('resize', function() {
resizeCaptcha();
});
});
function resizeCaptcha() {
if (captchaWrapper.width() >= captchaWidth) {
if (captchaResized) {
captchaElements.css('transform', '').css('-webkit-transform', '').css('-ms-transform', '').css('-o-transform', '').css('transform-origin', '').css('-webkit-transform-origin', '').css('-ms-transform-origin', '').css('-o-transform-origin', '');
captchaWrapper.height(captchaHeight);
captchaResized = false;
}
} else {
var scale = (1 - (captchaWidth - captchaWrapper.width()) * (0.05/15));
captchaElements.css('transform', 'scale('+scale+')').css('-webkit-transform', 'scale('+scale+')').css('-ms-transform', 'scale('+scale+')').css('-o-transform', 'scale('+scale+')').css('transform-origin', '0 0').css('-webkit-transform-origin', '0 0').css('-ms-transform-origin', '0 0').css('-o-transform-origin', '0 0');
captchaWrapper.height(captchaHeight * scale);
if (captchaResized == false) captchaResized = true;
}
}
3) Optional: add some styling if needed.
#recaptcha-wrapper {
text-align:center;
margin-bottom:15px;
}
.g-recaptcha {
display:inline-block;
}
The following example is based on jQuery but it can be achieved using any JS tool kit or even plain old JS
$(document).ready(function(){
$("#a").mouseover(function(){
$("#b").css("background-color", "red");
});
});
Since C-style strings are always terminated with the null character (\0
), you can check whether the string is empty by writing
do {
...
} while (url[0] != '\0');
Alternatively, you could use the strcmp
function, which is overkill but might be easier to read:
do {
...
} while (strcmp(url, ""));
Note that strcmp
returns a nonzero value if the strings are different and 0 if they're the same, so this loop continues to loop until the string is nonempty.
Hope this helps!
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
And then install wget
with brew and also enable openressl
for TLS support
brew install wget --with-libressl
It worked perfectly for me.
this is easy, use this query to find what you want.
select * from Product_Sales where From_date<='2018-04-11' and To_date>='2018-04-11'
The definition of method_two
is invalid. When you call method_two
, you'll get TypeError: method_two() takes 0 positional arguments but 1 was given
from the interpreter.
An instance method is a bounded function when you call it like a_test.method_two()
. It automatically accepts self
, which points to an instance of Test
, as its first parameter. Through the self
parameter, an instance method can freely access attributes and modify them on the same object.
I have read some article before and it's working fine but really don't know is safe or not
a. Create new folder local.
b. Move all project into the local folder expect public folder.
c. Move all the content of public folder to project root.
d. Delete the blank public folder
f. Edit the index file.
Edit the index.php
require __DIR__.'/../bootstrap/autoload.php';
$app = require_once __DIR__.'/../bootstrap/app.php';
to
require __DIR__.'/local/bootstrap/autoload.php';
$app = require_once __DIR__.'/local/bootstrap/app.php';
sudo apt-get install build-essential python3-dev python2.7-dev libldap2-dev libsasl2-dev slapd ldap-utils python-tox lcov valgrind
This seems to work in most browsers:
function copyStylesInline(destinationNode, sourceNode) {
var containerElements = ["svg","g"];
for (var cd = 0; cd < destinationNode.childNodes.length; cd++) {
var child = destinationNode.childNodes[cd];
if (containerElements.indexOf(child.tagName) != -1) {
copyStylesInline(child, sourceNode.childNodes[cd]);
continue;
}
var style = sourceNode.childNodes[cd].currentStyle || window.getComputedStyle(sourceNode.childNodes[cd]);
if (style == "undefined" || style == null) continue;
for (var st = 0; st < style.length; st++){
child.style.setProperty(style[st], style.getPropertyValue(style[st]));
}
}
}
function triggerDownload (imgURI, fileName) {
var evt = new MouseEvent("click", {
view: window,
bubbles: false,
cancelable: true
});
var a = document.createElement("a");
a.setAttribute("download", fileName);
a.setAttribute("href", imgURI);
a.setAttribute("target", '_blank');
a.dispatchEvent(evt);
}
function downloadSvg(svg, fileName) {
var copy = svg.cloneNode(true);
copyStylesInline(copy, svg);
var canvas = document.createElement("canvas");
var bbox = svg.getBBox();
canvas.width = bbox.width;
canvas.height = bbox.height;
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, bbox.width, bbox.height);
var data = (new XMLSerializer()).serializeToString(copy);
var DOMURL = window.URL || window.webkitURL || window;
var img = new Image();
var svgBlob = new Blob([data], {type: "image/svg+xml;charset=utf-8"});
var url = DOMURL.createObjectURL(svgBlob);
img.onload = function () {
ctx.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob)
{
var blob = canvas.msToBlob();
navigator.msSaveOrOpenBlob(blob, fileName);
}
else {
var imgURI = canvas
.toDataURL("image/png")
.replace("image/png", "image/octet-stream");
triggerDownload(imgURI, fileName);
}
document.removeChild(canvas);
};
img.src = url;
}