Tried everything on this page, but http://<name>.local:<PORT>
only worked on my iPhone after I quit and restarted Safari...
Just for completeness:
There is another solution, I would recommend: subtree merging.
In contrast to submodules, it's easier to maintain. You would create each repository the normal way. While in your main repository, you want to merge the master (or any other branch) of another repository in a directory of your main directory.
$ git remote add -f OtherRepository /path/to/that/repo
$ git merge -s ours --no-commit OtherRepository/master
$ git read-tree --prefix=AnyDirectoryToPutItIn/ -u OtherRepository/master
$ git commit -m "Merge OtherRepository project as our subdirectory"`
Then, in order to pull the other repository into your directory (to update it), use the subtree merge strategy:
$ git pull -s subtree OtherRepository master
I'm using this method for years now, it works :-)
More about this way including comparing it with sub modules may be found in this git howto doc.
one more approach to use.
first, define the following somewhere on the page:
<div id="valueHolderId">${someValue}</div>
then in JS, just do something similar to
var someValue = $('#valueHolderId').html();
it works great for the cases when all scripts are inside .js files and obviously there is no jstl available
if the other div is sibling/child, or any combination of, of the parent yes
.showme{ _x000D_
display: none;_x000D_
}_x000D_
.showhim:hover .showme{_x000D_
display : block;_x000D_
}_x000D_
.showhim:hover .hideme{_x000D_
display : none;_x000D_
}_x000D_
.showhim:hover ~ .hideme2{ _x000D_
display:none;_x000D_
}
_x000D_
<div class="showhim">_x000D_
HOVER ME_x000D_
<div class="showme">hai</div> _x000D_
<div class="hideme">bye</div>_x000D_
</div>_x000D_
<div class="hideme2">bye bye</div>
_x000D_
For org.json I've rolled out my own solution, a method that compares to JSONObject instances. I didn't work with complex JSON objects in that project, so I don't know whether this works in all scenarios. Also, given that I use this in unit tests, I didn't put effort into optimizations. Here it is:
public static boolean jsonObjsAreEqual (JSONObject js1, JSONObject js2) throws JSONException {
if (js1 == null || js2 == null) {
return (js1 == js2);
}
List<String> l1 = Arrays.asList(JSONObject.getNames(js1));
Collections.sort(l1);
List<String> l2 = Arrays.asList(JSONObject.getNames(js2));
Collections.sort(l2);
if (!l1.equals(l2)) {
return false;
}
for (String key : l1) {
Object val1 = js1.get(key);
Object val2 = js2.get(key);
if (val1 instanceof JSONObject) {
if (!(val2 instanceof JSONObject)) {
return false;
}
if (!jsonObjsAreEqual((JSONObject)val1, (JSONObject)val2)) {
return false;
}
}
if (val1 == null) {
if (val2 != null) {
return false;
}
} else if (!val1.equals(val2)) {
return false;
}
}
return true;
}
var BlobBuilder = (window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder);
can be used without the try catch.
Thankx to check_ca. Great work.
I don't know if this is Ruby intention or if this is a bug but try this code below. This code was run on Ruby version 2.5.1 and was on a Linux system.
puts 1 > -1 and 257 < 256
# => false
puts 1 > -1 && 257 < 256
# => true
The solution from Edward worked for me.
If you want the whole tablix on one sheet with a constant name, specify the PageName in the tablix's Properties. If you set the PageName in the tablix's Properties, you can not use data from the tablix's dataset in your expression.
If you want rows from the tablix grouped into sheets (or you want one sheet with a name based on the data), specify the PageName in the Group Header.
The easiest answer is given by W3schools. https://www.w3schools.com/html/html_youtube.asp
<iframe width="640" height="520"
src="https://www.youtube.com/embed/<VideoID>">
</iframe>
At the risk of being years late and off topic - and notwithstanding @Marc's excellent insight, in Swift it looks like:
let basename = NSURL(string: "path/to/file.ext")?.URLByDeletingPathExtension?.lastPathComponent
To split a string s
, the easiest way is to pass it to list()
. So,
s = 'abc'
s_l = list(s) # s_l is now ['a', 'b', 'c']
You can also use a list comprehension, which works but is not as concise as the above:
s_l = [c for c in s]
There are other ways, as well, but these should suffice.
Later, if you want to recombine them, a simple call to "".join(s_l)
will return your list to all its former glory as a string...
There is no absolute answer to your question, because technology is always bound to be implementation-specific. I am assuming you are communicating in UDP because incoming buffer size does not bring problem to TCP communication.
According to RFC 768, the packet size (header-inclusive) for UDP can range from 8 to 65 515 bytes. So the fail-proof size for incoming buffer is 65 507 bytes (~64KB)
However, not all large packets can be properly routed by network devices, refer to existing discussion for more information:
What is the optimal size of a UDP packet for maximum throughput?
What is the largest Safe UDP Packet Size on the Internet
Use DateFormat. (Sorry, but the brevity of the question does not warrant a longer or more detailed answer.)
Your code doesn't get the UTF-8 into memory as you read it back into a string again, so its no longer in UTF-8, but back in UTF-16 (though ideally its best to consider strings at a higher level than any encoding, except when forced to do so).
To get the actual UTF-8 octets you could use:
var serializer = new XmlSerializer(typeof(SomeSerializableObject));
var memoryStream = new MemoryStream();
var streamWriter = new StreamWriter(memoryStream, System.Text.Encoding.UTF8);
serializer.Serialize(streamWriter, entry);
byte[] utf8EncodedXml = memoryStream.ToArray();
I've left out the same disposal you've left. I slightly favour the following (with normal disposal left in):
var serializer = new XmlSerializer(typeof(SomeSerializableObject));
using(var memStm = new MemoryStream())
using(var xw = XmlWriter.Create(memStm))
{
serializer.Serialize(xw, entry);
var utf8 = memStm.ToArray();
}
Which is much the same amount of complexity, but does show that at every stage there is a reasonable choice to do something else, the most pressing of which is to serialise to somewhere other than to memory, such as to a file, TCP/IP stream, database, etc. All in all, it's not really that verbose.
You can read your BufferedInputStream like this. It will read data till it reaches end of stream which is indicated by -1.
inputS = new BufferedInputStream(inBS);
byte[] buffer = new byte[1024]; //If you handle larger data use a bigger buffer size
int read;
while((read = inputS.read(buffer)) != -1) {
System.out.println(read);
// Your code to handle the data
}
How about the apache POI java library. I havent used it for Excel , but did use it for Word 2007.
Here's a guy that posted his Eclipse preferences for changing the colors like a theme:
http://blog.codefront.net/2006/09/28/vibrant-ink-textmate-theme-for-eclipse/
And here's more about how to set the colors in the Ganymede Eclipse version (v. 3.4, mid 2008):
width: intrinsic; /* Safari/WebKit uses a non-standard name */
width: -moz-max-content; /* Firefox/Gecko */
width: -webkit-max-content; /* Chrome */
There are two uses for the keyword static when it comes to functions in C++.
The first is to mark the function as having internal linkage so it cannot be referenced in other translation units. This usage is deprecated in C++. Unnamed namespaces are preferred for this usage.
// inside some .cpp file:
static void foo(); // old "C" way of having internal linkage
// C++ way:
namespace
{
void this_function_has_internal_linkage()
{
// ...
}
}
The second usage is in the context of a class. If a class has a static member function, that means the function is a member of the class (and has the usual access to other members), but it doesn't need to be invoked through a particular object. In other words, inside that function, there is no "this" pointer.
I have found that using backticks to capture command output into a variable, adversly, yeilds one too many ps aux results, e.g. for a single running instance of abc.sh:
ps aux | grep -w "abc.sh" | grep -v grep | wc -l
returns "1". However,
count=`ps aux | grep -w "abc.sh" | grep -v grep | wc -l`
echo $count
returns "2"
Seems like using the backtick construction somehow temporarily creates another process. Could be the reason why the topicstarter could not make this work. Just need to decrement the $count var.
<script type="text/javascript">
$(document).ready(function () {
$("#txtDate").datepicker({ dateFormat: 'yy/mm/dd' }).datepicker("setDate", "0");
$("#txtDate2").datepicker({ dateFormat: 'yy/mm/dd', }).datepicker("setDate", new Date().getDay+15); }); </script>
Another way to do this in AngularJS is to use a Grid.
The advantage with grids is that the row sorting behavior you are looking for is included by default.
The functionality is well encapsulated. You don't need to add ng-click attributes, or use scope variables to maintain state:
<body ng-controller="MyCtrl">
<div class="gridStyle" ng-grid="gridOptions"></div>
</body>
You just add the grid options to your controller:
$scope.gridOptions = {
data: 'myData.employees',
columnDefs: [{
field: 'firstName',
displayName: 'First Name'
}, {
field: 'lastName',
displayName: 'Last Name'
}, {
field: 'age',
displayName: 'Age'
}]
};
Full working snippet attached:
var app = angular.module('myApp', ['ngGrid', 'ngAnimate']);_x000D_
app.controller('MyCtrl', function($scope) {_x000D_
_x000D_
$scope.myData = {_x000D_
employees: [{_x000D_
firstName: 'John',_x000D_
lastName: 'Doe',_x000D_
age: 30_x000D_
}, {_x000D_
firstName: 'Frank',_x000D_
lastName: 'Burns',_x000D_
age: 54_x000D_
}, {_x000D_
firstName: 'Sue',_x000D_
lastName: 'Banter',_x000D_
age: 21_x000D_
}]_x000D_
};_x000D_
_x000D_
$scope.gridOptions = {_x000D_
data: 'myData.employees',_x000D_
columnDefs: [{_x000D_
field: 'firstName',_x000D_
displayName: 'First Name'_x000D_
}, {_x000D_
field: 'lastName',_x000D_
displayName: 'Last Name'_x000D_
}, {_x000D_
field: 'age',_x000D_
displayName: 'Age'_x000D_
}]_x000D_
};_x000D_
});
_x000D_
/*style.css*/_x000D_
.gridStyle {_x000D_
border: 1px solid rgb(212,212,212);_x000D_
width: 400px;_x000D_
height: 200px_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html ng-app="myApp">_x000D_
<head lang="en">_x000D_
<meta charset="utf-8">_x000D_
<title>Custom Plunker</title>_x000D_
<link rel="stylesheet" type="text/css" href="http://angular-ui.github.com/ng-grid/css/ng-grid.css" />_x000D_
<link rel="stylesheet" type="text/css" href="style.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular-animate.js"></script>_x000D_
<script type="text/javascript" src="http://angular-ui.github.com/ng-grid/lib/ng-grid.debug.js"></script>_x000D_
<script type="text/javascript" src="main.js"></script>_x000D_
</head>_x000D_
<body ng-controller="MyCtrl">_x000D_
<div class="gridStyle" ng-grid="gridOptions"></div>_x000D_
</body>_x000D_
</html>
_x000D_
Ten non-deleted answers; most do not do what the user asked for. Most Answers mis-read the question as thinking that there are 58 users in each town instead of 58 in total. Even the few that are correct are not optimal.
mysql> flush status;
Query OK, 0 rows affected (0.00 sec)
SELECT province, total_cities
FROM ( SELECT DISTINCT province FROM canada ) AS provinces
CROSS JOIN ( SELECT COUNT(*) total_cities FROM canada ) AS tot;
+---------------------------+--------------+
| province | total_cities |
+---------------------------+--------------+
| Alberta | 5484 |
| British Columbia | 5484 |
| Manitoba | 5484 |
| New Brunswick | 5484 |
| Newfoundland and Labrador | 5484 |
| Northwest Territories | 5484 |
| Nova Scotia | 5484 |
| Nunavut | 5484 |
| Ontario | 5484 |
| Prince Edward Island | 5484 |
| Quebec | 5484 |
| Saskatchewan | 5484 |
| Yukon | 5484 |
+---------------------------+--------------+
13 rows in set (0.01 sec)
SHOW session status LIKE 'Handler%';
+----------------------------+-------+
| Variable_name | Value |
+----------------------------+-------+
| Handler_commit | 1 |
| Handler_delete | 0 |
| Handler_discover | 0 |
| Handler_external_lock | 4 |
| Handler_mrr_init | 0 |
| Handler_prepare | 0 |
| Handler_read_first | 3 |
| Handler_read_key | 16 |
| Handler_read_last | 1 |
| Handler_read_next | 5484 | -- One table scan to get COUNT(*)
| Handler_read_prev | 0 |
| Handler_read_rnd | 0 |
| Handler_read_rnd_next | 15 |
| Handler_rollback | 0 |
| Handler_savepoint | 0 |
| Handler_savepoint_rollback | 0 |
| Handler_update | 0 |
| Handler_write | 14 | -- leapfrog through index to find provinces
+----------------------------+-------+
In the OP's context:
SELECT town, total_users
FROM ( SELECT DISTINCT town FROM canada ) AS towns
CROSS JOIN ( SELECT COUNT(*) total_users FROM canada ) AS tot;
Since there is only one row from tot
, the CROSS JOIN
is not as voluminous as it might otherwise be.
The usual pattern is COUNT(*)
instead of COUNT(town)
. The latter implies checking town
for being not null, which is unnecessary in this context.
If there are no spaces in paths, and you are interested, like I was, in files of specific extension only, you can use
git checkout otherBranch -- $(git ls-tree --name-only -r otherBranch | egrep '*.java')
list.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
namespace ReverseString
{
class Program
{
static void Main(string[] args)
{
string stat = "This is an example of code" +
"This code has written in C#\n\n";
Console.Write(stat);
char[] myArrayofChar = stat.ToCharArray();
Array.Reverse(myArrayofChar);
foreach (char myNewChar in myArrayofChar)
Console.Write(myNewChar); // You just need to write the function
// Write instead of WriteLine
Console.ReadKey();
}
}
}
This is the output:
#C ni nettirw sah edoc sihTedoc fo elpmaxe na si sihT
Ajax Submit form with out page refresh by using jquery ajax method first include library jquery.js and jquery-form.js then create form in html:
<form action="postpage.php" method="POST" id="postForm" >
<div id="flash_success"></div>
name:
<input type="text" name="name" />
password:
<input type="password" name="pass" />
Email:
<input type="text" name="email" />
<input type="submit" name="btn" value="Submit" />
</form>
<script>
var options = {
target: '#flash_success', // your response show in this ID
beforeSubmit: callValidationFunction,
success: YourResponseFunction
};
// bind to the form's submit event
jQuery('#postForm').submit(function() {
jQuery(this).ajaxSubmit(options);
return false;
});
});
function callValidationFunction()
{
// validation code for your form HERE
}
function YourResponseFunction(responseText, statusText, xhr, $form)
{
if(responseText=='success')
{
$('#flash_success').html('Your Success Message Here!!!');
$('body,html').animate({scrollTop: 0}, 800);
}else
{
$('#flash_success').html('Error Msg Here');
}
}
</script>
You can use word-wrap : break-word;
What do you think about creating new package i.e image.icons in your src directory and moving there you .png images? Than you just need to write:
Image image = new Image("/image/icons/nameOfImage.png");
primaryStage.getIcons().add(image);
This solution works for me perfectly, but still I'm not sure if it's correct (beginner here).
I think your question is a bit more general than I originally thought. type()
with one argument returns the type
or class
of the object. So if you have a = 'abc'
and use type(a)
this returns str
because the variable a
is a string. If b = 10
, type(b)
returns int
.
See also python documentation on type().
If you want a comparison you could use: if type(v) == h5py.h5r.Reference
(to check if it is a h5py.h5r.Reference
instance).
But it is recommended that one uses if isinstance(v, h5py.h5r.Reference)
but then also subclasses will evaluate to True
.
If you want to print the class use print v.__class__.__name__
.
More generally: You can compare if two instances have the same class by using type(v) is type(other_v)
or isinstance(v, other_v.__class__)
.
Not with an iterator.
For org.json.JSONArray
, you can do:
for (int i = 0; i < arr.length(); i++) {
arr.getJSONObject(i);
}
For javax.json.JsonArray
, you can do:
for (int i = 0; i < arr.size(); i++) {
arr.getJsonObject(i);
}
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.URL);
});
This JavaScript code does not allow any user to go back (works in Chrome, Firefox, Internet Explorer, and Edge).
A way to replace it with a java 8 stream:
public static void main(String[] args) throws IOException
{
String test = "ab19198zxncvl1308j10923.";
StringBuilder result = new StringBuilder();
test.chars().mapToObj( i-> (char)i ).filter( c -> Character.isDigit(c) || c == '.' ).forEach( c -> result.append(c) );
System.out.println( result ); //returns 19198.130810923.
}
I only have half the answer, but I hope that it is useful as it adds unicode (utf-8) support
//decimal to unicode character
function unichr($dec) {
if ($dec < 128) {
$utf = chr($dec);
} else if ($dec < 2048) {
$utf = chr(192 + (($dec - ($dec % 64)) / 64));
$utf .= chr(128 + ($dec % 64));
} else {
$utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
$utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
$utf .= chr(128 + ($dec % 64));
}
return $utf;
}
To string
var_dump(unichr(hexdec('e641')));
Source: http://www.php.net/manual/en/function.chr.php#Hcom55978
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date(); System.out.println(dateFormat.format(date)); //2014/08/06 15:59:4
html { overflow-y: scroll; }
This css
rule causes a vertical scrollbar to always appear.
Source: http://css-tricks.com/snippets/css/force-vertical-scrollbar/
If I want tranfer only the response variable y instead of a linear model with x specified, eg I wanna transfer/normalize a list of data, I can take 1 for x, then the object becomes a linear model:
library(MASS)
y = rf(500,30,30)
hist(y,breaks = 12)
result = boxcox(y~1, lambda = seq(-5,5,0.5))
mylambda = result$x[which.max(result$y)]
mylambda
y2 = (y^mylambda-1)/mylambda
hist(y2)
There's no specific answer. It depends on the platform. It is implementation-defined. It can be 2, 4 or something else.
The idea behind int
was that it was supposed to match the natural "word" size on the given platform: 16 bit on 16-bit platforms, 32 bit on 32-bit platforms, 64 bit on 64-bit platforms, you get the idea. However, for backward compatibility purposes some compilers prefer to stick to 32-bit int
even on 64-bit platforms.
The time of 2-byte int
is long gone though (16-bit platforms?) unless you are using some embedded platform with 16-bit word size. Your textbooks are probably very old.
This link has answers to the same basic question, but basically, id is used for scripting identification and name is for server-side.
http://www.velocityreviews.com/forums/t115115-id-vs-name-attribute-for-html-controls.html
(Just leaving this here for my own reference.) This will show version and build for the "version" and "build" fields you see in an Xcode target:
- (NSString*) version {
NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
NSString *build = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
return [NSString stringWithFormat:@"%@ build %@", version, build];
}
In Swift
func version() -> String {
let dictionary = NSBundle.mainBundle().infoDictionary!
let version = dictionary["CFBundleShortVersionString"] as? String
let build = dictionary["CFBundleVersion"] as? String
return "\(version) build \(build)"
}
Because it's more common to call range(0, 10)
which returns [0,1,2,3,4,5,6,7,8,9]
which contains 10 elements which equals len(range(0, 10))
. Remember that programmers prefer 0-based indexing.
Also, consider the following common code snippet:
for i in range(len(li)):
pass
Could you see that if range()
went up to exactly len(li)
that this would be problematic? The programmer would need to explicitly subtract 1. This also follows the common trend of programmers preferring for(int i = 0; i < 10; i++)
over for(int i = 0; i <= 9; i++)
.
If you are calling range with a start of 1 frequently, you might want to define your own function:
>>> def range1(start, end):
... return range(start, end+1)
...
>>> range1(1, 10)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
I've been using something like this. Just set up a simple HTML page with an textinput. Make sure that the textinput always has focus. When you scan a barcode with your barcode scanner you will receive the code and after that a 'enter'. Realy simple then; just capture the incoming keystrokes and when the 'enter' comes in you can use AJAX to handle your code.
This is mainly for future readers. As the question (at least the title) focuses on "connecting to sql server database from node js", I would like to chip in about "mssql" node module.
At this moment, we have a stable version of Microsoft SQL Server driver for NodeJs ("msnodesql") available here: https://www.npmjs.com/package/msnodesql. While it does a great job of native integration to Microsoft SQL Server database (than any other node module), there are couple of things to note about.
"msnodesql" require a few pre-requisites (like python, VC++, SQL native client etc.) to be installed on the host machine. That makes your "node" app "Windows" dependent. If you are fine with "Windows" based deployment, working with "msnodesql" is the best.
On the other hand, there is another module called "mssql" (available here https://www.npmjs.com/package/mssql) which can work with "tedious" or "msnodesql" based on configuration. While this module may not be as comprehensive as "msnodesql", it pretty much solves most of the needs.
If you would like to start with "mssql", I came across a simple and straight forward video, which explains about connecting to Microsoft SQL Server database using NodeJs here: https://www.youtube.com/watch?v=MLcXfRH1YzE
Source code for the above video is available here: http://techcbt.com/Post/341/Node-js-basic-programming-tutorials-videos/how-to-connect-to-microsoft-sql-server-using-node-js
Just in case, if the above links are not working, I am including the source code here:
var sql = require("mssql");_x000D_
_x000D_
var dbConfig = {_x000D_
server: "localhost\\SQL2K14",_x000D_
database: "SampleDb",_x000D_
user: "sa",_x000D_
password: "sql2014",_x000D_
port: 1433_x000D_
};_x000D_
_x000D_
function getEmp() {_x000D_
var conn = new sql.Connection(dbConfig);_x000D_
_x000D_
conn.connect().then(function () {_x000D_
var req = new sql.Request(conn);_x000D_
req.query("SELECT * FROM emp").then(function (recordset) {_x000D_
console.log(recordset);_x000D_
conn.close();_x000D_
})_x000D_
.catch(function (err) {_x000D_
console.log(err);_x000D_
conn.close();_x000D_
}); _x000D_
})_x000D_
.catch(function (err) {_x000D_
console.log(err);_x000D_
});_x000D_
_x000D_
//--> another way_x000D_
//var req = new sql.Request(conn);_x000D_
//conn.connect(function (err) {_x000D_
// if (err) {_x000D_
// console.log(err);_x000D_
// return;_x000D_
// }_x000D_
// req.query("SELECT * FROM emp", function (err, recordset) {_x000D_
// if (err) {_x000D_
// console.log(err);_x000D_
// }_x000D_
// else { _x000D_
// console.log(recordset);_x000D_
// }_x000D_
// conn.close();_x000D_
// });_x000D_
//});_x000D_
_x000D_
}_x000D_
_x000D_
getEmp();
_x000D_
The above code is pretty self explanatory. We define the db connection parameters (in "dbConfig" JS object) and then use "Connection" object to connect to SQL Server. In order to execute a "SELECT" statement, in this case, it uses "Request" object which internally works with "Connection" object. The code explains both flavors of using "promise" and "callback" based executions.
The above source code explains only about connecting to sql server database and executing a SELECT query. You can easily take it to the next level by following documentation of "mssql" node available at: https://www.npmjs.com/package/mssql
UPDATE: There is a new video which does CRUD operations using pure Node.js REST standard (with Microsoft SQL Server) here: https://www.youtube.com/watch?v=xT2AvjQ7q9E. It is a fantastic video which explains everything from scratch (it has got heck a lot of code and it will not be that pleasing to explain/copy the entire code here)
With modern browser i prefer a much lightweight approach with a bit of Js and CSS3...
transition: background 300ms ease-in 200ms;
Look at this demo:
The default
keyword works for me:
mysql> insert into user_table (user_id, ip, partial_ip, source, user_edit_date, username) values
(default, '39.48.49.126', null, 'user signup page', now(), 'newUser');
---
Query OK, 1 row affected (0.00 sec)
I'm running mysql --version
5.1.66:
mysql Ver 14.14 Distrib **5.1.66**, for debian-linux-gnu (x86_64) using readline 6.1
When the above solution doesn’t work try this:
<IfModule mod_security.c>
SecRuleEngine Off
SecFilterInheritance Off
SecFilterEngine Off
SecFilterScanPOST Off
SecRuleRemoveById 300015 3000016 3000017
</IfModule>
Unfortunately, vars files do not have include statements.
You can either put all the vars into the definitions
dictionary, or add the variables as another dictionary in the same file.
If you don't want to have them in the same file, you can include them at the playbook level by adding the vars file at the start of the play:
---
- hosts: myhosts
vars_files:
- default_step.yml
or in a task:
---
- hosts: myhosts
tasks:
- name: include default step variables
include_vars: default_step.yml
The answer to the above question is "none of the above". When you download new STS it won't support the old Spring Boot parent version. Just update parent version with latest comes with STS it will work.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
If you have problem getting the latest, just create a new Spring Starter Project. Go to File->New->Spring Start Project and create a demo project you will get the latest parent version, change your version with that all will work. I do this every time I change STS.
You can call qApp.exit();
. I always use that and never had a problem with it.
If you application is a command line application, you might indeed want to return an exit code. It's completely up to you what the code is.
@Casperah pointed out that i'm thinking about it wrong:
TextBox
doesn't have linesThe question then is how to accomplish what i want, rather than what WinForms lets me.
There are subtle bugs in the other given variants:
textBox1.AppendText("Hello" + Environment.NewLine);
textBox1.AppendText("Hello" + "\r\n");
textBox1.Text += "Hello\r\n"
textbox1.Text += System.Environment.NewLine + "brown";
They either append or prepend a newline when one (might) not be required.
So, extension helper:
public static class WinFormsExtensions
{
public static void AppendLine(this TextBox source, string value)
{
if (source.Text.Length==0)
source.Text = value;
else
source.AppendText("\r\n"+value);
}
}
So now:
textBox1.Clear();
textBox1.AppendLine("red");
textBox1.AppendLine("green");
textBox1.AppendLine("blue");
and
textBox1.AppendLine(String.Format("Processing file {0}", filename));
Note: Any code is released into the public domain. No attribution required.
Full code that shows now and 10 minutes added.....
$nowtime = date("Y-m-d H:i:s");
echo $nowtime;
$date = date('Y-m-d H:i:s', strtotime($nowtime . ' + 10 minute'));
echo "<br>".$date;
Yes. You need to use the "Searched" form rather than the "Simple" form of the CASE
expression
SELECT CASE
WHEN c.Number IN ( '1121231', '31242323' ) THEN 1
WHEN c.Number IN ( '234523', '2342423' ) THEN 2
END AS Test
FROM tblClient c
Doing password checks on client side is unsafe especially when the password is hard coded.
The safest way is password checking on server side, but even then the password should not be transmitted plain text.
Checking the password client side is possible in a "secure way":
Say "abc" is your password so your md5 would be "900150983cd24fb0d6963f7d28e17f72" (consider salting!). Now build a url containing the hash (like http://yourdomain.com/90015...f72.html).
To increase the phpMyAdmin
Session Timeout, open config.inc.php
in the root phpMyAdmin
directory and add this setting (anywhere).
$cfg['LoginCookieValidity'] = <your_new_timeout>;
Where <your_new_timeout>
is some number larger than 1800.
Note:
Always keep on mind that a short cookie lifetime is all well and good for the development server. So do not do this on your production server.
If you're just quickly looking to keep a cmd instance open instead of exiting immediately, simply doing the following is enough
set /p asd="Hit enter to continue"
at the end of your script and it'll keep the window open.
Note that this'll set asd
as an environment variable, and can be replaced with anything else.
You can use body or * to make margin and padding 0px;
*{
margin: 0px;
padding:0px;
}
Below are the methods which have always worked for me
Set the display of the parent div to display: flex;
and the you can align the child elements inside the div using the justify-content: center;
(to align the items on main axis) and align-items: center;
(to align the items on cross axis).
If you have more than one child element and want to control the way they are arranged (column/rows), then you can also add flex-direction
property.
Working example:
.parent {_x000D_
align-items: center;_x000D_
border: 1px solid black;_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
height: 250px;_x000D_
width: 250px;_x000D_
}_x000D_
_x000D_
.child {_x000D_
border: 1px solid black;_x000D_
height: 50px;_x000D_
width: 50px;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child"></div>_x000D_
</div>
_x000D_
2. (older method) Using position, margin properties and fixed size
Working example:
.parent {_x000D_
border: 1px solid black;_x000D_
height: 250px;_x000D_
position: relative;_x000D_
width: 250px;_x000D_
}_x000D_
_x000D_
.child {_x000D_
border: 1px solid black;_x000D_
margin: auto;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
height: 50px;_x000D_
position: absolute;_x000D_
width: 50px;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child"></div>_x000D_
</div>
_x000D_
You mention Haxe/NME but you seem to instinctively dislike it. However, my experience with it has been very positive. Sure, the API is a reimplementation of the Flash API, but you're not limited to targeting Flash, you can also compile to HTML5 or native Windows, Mac, iOS and Android apps. Haxe is a pleasant, modern language similar to Java or C#.
If you're interested, I've written a bit about my experience using Haxe/NME: link
Your issue is in PHPMyAdmin itself. Some versions do not display the value of bit columns, even though you did set it correctly.
In my case the problem occurred while the default setting for Android Version in the Designer was set to 'Preview N'. Changed Android Version to '23' and the error notification went away.
Edit
And don't forget to uncheck 'Automatically Pick Best'.
Here is what I have been using:
public static HashMap<String, Object> parse(String json) {
JsonObject object = (JsonObject) parser.parse(json);
Set<Map.Entry<String, JsonElement>> set = object.entrySet();
Iterator<Map.Entry<String, JsonElement>> iterator = set.iterator();
HashMap<String, Object> map = new HashMap<String, Object>();
while (iterator.hasNext()) {
Map.Entry<String, JsonElement> entry = iterator.next();
String key = entry.getKey();
JsonElement value = entry.getValue();
if (!value.isJsonPrimitive()) {
map.put(key, parse(value.toString()));
} else {
map.put(key, value.getAsString());
}
}
return map;
}
try:
if val is None: # The variable
print('It is None')
except NameError:
print ("This variable is not defined")
else:
print ("It is defined and has a value")
From ggplot 2.2.0
labels can easily be stacked by using position = position_stack(vjust = 0.5)
in geom_text
.
ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
geom_bar(stat = "identity") +
geom_text(size = 3, position = position_stack(vjust = 0.5))
Also note that "position_stack()
and position_fill()
now stack values in the reverse order of the grouping, which makes the default stack order match the legend."
Answer valid for older versions of ggplot
:
Here is one approach, which calculates the midpoints of the bars.
library(ggplot2)
library(plyr)
# calculate midpoints of bars (simplified using comment by @DWin)
Data <- ddply(Data, .(Year),
transform, pos = cumsum(Frequency) - (0.5 * Frequency)
)
# library(dplyr) ## If using dplyr...
# Data <- group_by(Data,Year) %>%
# mutate(pos = cumsum(Frequency) - (0.5 * Frequency))
# plot bars and add text
p <- ggplot(Data, aes(x = Year, y = Frequency)) +
geom_bar(aes(fill = Category), stat="identity") +
geom_text(aes(label = Frequency, y = pos), size = 3)
To prevent IE8 from going on an endless loop of refreshing and crashing it stops after two times and shows this url. There could be many issues that might be causing it to crash.
In my case an upgrade to jQuery v1.10.2 from v1.4.4 causing the issue, but it must have been mostly our code bad and was now more evident with the upgrade.
My observation was everything seems working fine on IE7/XP, IE8/Win7, IE9/Win7 and IE10/Win7 but was not working fine on IE8/XP and IE8/Server2003. The version of IE8 on Win7 and XP/Server 2003 are different. Here is the list of versions for each Operating System (http://support.microsoft.com/kb/969393).
Then looked at Event viewer on Win Server 2003 and it had something like faulting module mshtml.dll, version 8.0.6001.18975 and on Win XP it was faulting module mshtml.dll, version 8.0.6001.18702 even though the browser version is same on both which is 8.0.6001.18702.
Then further searching about this mshtml.dll, it looks like Microsoft keeps updating mshtml.dll which is the HTML component of the browser through patches. So then I realised its not the browser version that is important but mshtml.dll version instead.
So I went ahead and downloaded the latest Cumulative patch for IE8 from here (https://technet.microsoft.com/en-us/security/bulletin/ms13-059) which updated my mshtml.dll file (in system32 folder) to 8.0.6001.23515 and it started working fine , may be they fixed it some time back probably in this (http://technet.microsoft.com/en-us/security/bulletin/ms12-037)
See also:
http://support.microsoft.com/kb/980344 http://support.microsoft.com/kb/979665
But first things first always reset your browser so that you disable all plugins and rule out the possible cause by external plugins.
'this' refers to the DOM object to which the event listener has been attached. 'event.target' refers to the DOM object for which the event listener got triggered. A natural question arises as, why the event listener is triggering for other DOM objects. This is because event listener attached parent triggers for child object too.
SELECT ...
SELECT SLEEP(5);
SELECT ...
But what are you using this for? Are you trying to circumvent/reinvent mutexes or transactions?
You can easily do this by css. HTML :
<form id="aform" name="aform" method="POST">
<input name="chkBox_1" type="checkbox" checked value="1" readonly />
<br/>
<input name="chkBox_2" type="checkbox" value="1" readonly />
<br/>
<input id="submitBttn" type="button" value="Submit">
</form>
CSS :
input[type="checkbox"][readonly] {
pointer-events: none;
}
Use an extra condition to check if innerHTML and innerText are the same. Only in those cases, replace the text.
$(function() {
$('body *').each(function () {
console.log($(this).html());
console.log($(this).text());
if($(this).text() === "Search" && $(this).html()===$(this).text()) {
$(this).html("Find");
}
})
})
The suggested for loop is quite fine but you have to check the properties with hasOwnProperty
. I'd rather suggest using Object.keys()
that only returns 'own properties' of the object (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)
var data = {_x000D_
"messages": [{_x000D_
"msgFrom": "13223821242",_x000D_
"msgBody": "Hi there"_x000D_
}, {_x000D_
"msgFrom": "Bill",_x000D_
"msgBody": "Hello!"_x000D_
}]_x000D_
};_x000D_
_x000D_
data.messages.forEach(function(message, index) {_x000D_
console.log('message index '+ index);_x000D_
Object.keys(message).forEach(function(prop) { _x000D_
console.log(prop + " = " + message[prop]);_x000D_
});_x000D_
});
_x000D_
When people ask a question like this, I like to think to myself "what would happen if this were actually possible?" I don't really know what this would mean, but I guess it would have something to do with being able to override the constructor implementation based on the dynamic type of the object being created.
I see a number of potential problems with this. For one thing, the derived class will not be fully constructed at the time the virtual constructor is called, so there are potential issues with the implementation.
Secondly, what would happen in the case of multiple inheritance? Your virtual constructor would be called multiple times presumably, you would then need to have some way of know which one was being called.
Thirdly, generally speaking at the time of construction, the object does not have the virtual table fully constructed, this means it would require a large change to the language specification to allow for the fact that the dynamic type of the object would be known at construction time. This would then allow the base class constructor to maybe call other virtual functions at construction time, with a not fully constructed dynamic class type.
Finally, as someone else has pointed out you can implement a kind of virtual constructor using static "create" or "init" type functions that basically do the same thing as a virtual constructor would do.
Basically ? [ for left multiple indent and ? ] right multiple indent.
For TR
keyboard you can left multiple indent with ? ? 8 and right multiple indent with ? ? 9.Because both 8 and 9 are ALT
characters of the these nums.Or if you have a keyboard which has [ or ] characters are belong to ALT
(?) property so you can use ? ? KEYBOARD CHARACTER
Aight fam, after some research and experimenting, I think the best approach is to have the thing's height at 0px
, and let it transition to an exact height. You get the exact height with JavaScript. The JavaScript isn't doing the animating, it's just changing the height value. Check it:
function setInfoHeight() {
$(window).on('load resize', function() {
$('.info').each(function () {
var current = $(this);
var closed = $(this).height() == 0;
current.show().height('auto').attr('h', current.height() );
current.height(closed ? '0' : current.height());
});
});
Whenever the page loads or is resized, the element with class info
will get its h
attribute updated. Then you could have a button trigger the style="height: __"
to set it to that previously set h
value.
function moreInformation() {
$('.icon-container').click(function() {
var info = $(this).closest('.dish-header').next('.info'); // Just the one info
var icon = $(this).children('.info-btn'); // Select the logo
// Stop any ongoing animation loops. Without this, you could click button 10
// times real fast, and watch an animation of the info showing and closing
// for a few seconds after
icon.stop();
info.stop();
// Flip icon and hide/show info
icon.toggleClass('flip');
// Metnod 1, animation handled by JS
// info.slideToggle('slow');
// Method 2, animation handled by CSS, use with setInfoheight function
info.toggleClass('active').height(icon.is('.flip') ? info.attr('h') : '0');
});
};
Here's the styling for the info
class.
.info {
display: inline-block;
height: 0px;
line-height: 1.5em;
overflow: hidden;
padding: 0 1em;
transition: height 0.6s, padding 0.6s;
&.active {
border-bottom: $thin-line;
padding: 1em;
}
}
I used this on one of my projects so class names are specific. You can change them up however you like.
The styling might not be supported cross-browser. Works fine in chrome.
Below is the live example for this code. Just click on the ?
icon to start the animation
When using the Hibernate implementation of JPA , I've found that simply declaring the type as an ArrayList instead of List allows hibernate to store the list of data.
Clearly this has a number of disadvantages compared to creating a list of Entity objects. No lazy loading, no ability to reference the entities in the list from other objects, perhaps more difficulty in constructing database queries. However when you are dealing with lists of fairly primitive types that you will always want to eagerly fetch along with the entity, then this approach seems fine to me.
@Entity
public class Command implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
ArrayList<String> arguments = new ArrayList<String>();
}
Try using
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">
There are a couple of ways to solve this problem
Pyinx - a pretty lightweight tool that allows you to call Python from withing the excel process space http://code.google.com/p/pyinex/
I've used this one a few years ago (back when it was being actively developed) and it worked quite well
If you don't mind paying, this looks pretty good
https://datanitro.com/product.html
I've never used it though
Though if you are already writting in Python, maybe you could drop excel entirely and do everything in pure python? It's a lot easier to maintain one code base (python) rather than 2 (python + whatever excel overlay you have).
If you really have to output your data into excel there are even some pretty good tools for that in Python. If that may work better let me know and I'll get the links.
I would use nearly the same way but with list as buffer for read integers:
static Object[] readFile(String fileName) {
Scanner scanner = new Scanner(new File(fileName));
List<Integer> tall = new ArrayList<Integer>();
while (scanner.hasNextInt()) {
tall.add(scanner.nextInt());
}
return tall.toArray();
}
I got this error because I had a dependency on another module that was not loaded.
angular.module("app", ["kendo.directives"]).controller("MyCtrl", function(){}...
so even though I had all the Angular modules, I didn't have the kendo one.
Simple and efficient:
int rand7 ( void )
{
return 4; // this number has been calculated using
// rand5() and is in the range 1..7
}
(Inspired by What's your favorite "programmer" cartoon?).
You can use the below command to check the list of all services.
ps aux
To check your own service:
ps aux | grep postgres
You can do it like this:
SELECT * FROM ... WHERE name LIKE 'someone'
(It's not the solution, but in some cases is very convenient)
"The LIKE operator does a pattern matching comparison. The operand to the right contains the pattern, the left hand operand contains the string to match against the pattern. A percent symbol ("%") in the pattern matches any sequence of zero or more characters in the string. An underscore ("_") in the pattern matches any single character in the string. Any other character matches itself or its lower/upper case equivalent (i.e. case-insensitive matching). (A bug: SQLite only understands upper/lower case for ASCII characters. The LIKE operator is case sensitive for unicode characters that are beyond the ASCII range. For example, the expression 'a' LIKE 'A' is TRUE but 'æ' LIKE 'Æ' is FALSE.)."
Bootstrap has 3 lines of CSS, within your bootstrap.css generated file that control the placeholder text color:
.form-control::-moz-placeholder {
color: #999999;
opacity: 1;
}
.form-control:-ms-input-placeholder {
color: #999999;
}
.form-control::-webkit-input-placeholder {
color: #999999;
}
Now if you add this to your own CSS file it won't override bootstrap's because it is less specific. So assmuning your form inside a then add that to your CSS:
form .form-control::-moz-placeholder {
color: #fff;
opacity: 1;
}
form .form-control:-ms-input-placeholder {
color: #fff;
}
form .form-control::-webkit-input-placeholder {
color: #fff;
}
Voila that will override bootstrap's CSS.
Although I don't know about asp.net mvc, but this is what we should do in a normal .net website. It should work for asp.net mvc also.
YourSessionClass obj=Session["key"] as YourSessionClass;
if(obj==null){
obj=new YourSessionClass();
Session["key"]=obj;
}
You would put this inside a method for easy access. HTH
When you hit on the submit button, the page is sent to the server. If you want to send it async, you can do it with ajax.
Since Java 8 this kind of code compiles as expected and the type parameter gets inferred by the compiler.
public Person(String name) {
this(name, Collections.emptyList()); // Inferred to List<String> in Java 8
}
public Person(String name, List<String> nicknames) {
this.name = name;
this.nicknames = nicknames;
}
The new thing in Java 8 is that the target type of an expression will be used to infer type parameters of its sub-expressions. Before Java 8 only direct assignments and arguments to methods where used for type parameter inference.
In this case the parameter type of the constructor will be the target type for Collections.emptyList()
, and the return value type will get chosen to match the parameter type.
This mechanism was added in Java 8 mainly to be able to compile lambda expressions, but it improves type inferences generally.
Java is getting closer to proper Hindley–Milner type inference with every release!
When you use the finish() method, it does not close the process completely , it is STILL working in background.
Please use this code in Main Activity (Please don't use in every activities or sub Activities):
@Override
public void onBackPressed() {
android.os.Process.killProcess(android.os.Process.myPid());
// This above line close correctly
}
split the file "file.txt" into 10000 lines files:
split -l 10000 file.txt
Situation:
We have certificate.key
certificate.crt
inside /user/ssl/
We want to rename anything that starts with certificate
to certificate_OLD
We are now located inside /user
First, you do a dry run with -n
:
rename -n "s/certificate/certificate_old/" ./ssl/*
Which returns:
rename(./ssl/certificate.crt, ./ssl/certificate_OLD.crt)
rename(./ssl/certificate.key, ./ssl/certificate_OLD.key)
Your files will be unchanged this is just a test run.
Solution:
When your happy with the result of the test run it for real:
rename "s/certificate/certificate_OLD/" ./ssl/*
What it means:
`rename "s/ SOMETHING / SOMETING_ELSE " PATH/FILES
Tip:
If you are already on the path run it like this:
rename "s/certificate/certificate_OLD/" *
Or if you want to do this in any sub-directory starting with ss
do:
rename -n "s/certificat/certificate_old/" ./ss*/*
You can also do:
rename -n "s/certi*/certificate_old/" ./ss*/*
Which renames anything starting with certi
in any sub-directory starting with ss
.
The sky is the limit.
Play around with regex and ALWAYS test this BEFORE with -n
.
WATCH OUT THIS WILL EVEN RENAME FOLDER NAMES THAT MATCH.
Better cd
into the directory and do it there.
USE AT OWN RISK.
You need to create a object from your list like:
List<CartProduct> lst = new List<CartProduct>();
CartProduct obj = lst.Find(x => (x.Name == "product name"));
That object get the looked value searching by their properties: x.name
Then you can use List methods like Contains or Remove
if (lst.Contains(obj))
{
lst.Remove(obj);
}
If your GRADLE_HOME and JAVA_HOME environment are set properly then check your JDK directory and make sure you have java.exe file under below path.
C:\Program Files (x86)\Java\jdk1.8.0_181\bin
As error mentioned in gradle.bat file
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
It is not able to locate your java installation. So find and set
java.exe
under %JAVA_HOME%/bin
if everything is correct.
This works for me (my account got disabled by client and their admin has removed java.exe from my directory.)
Unit testing is usually done by the developers side, whereas testers are partly evolved in this type of testing where testing is done unit by unit. In Java JUnit test cases can also be possible to test whether the written code is perfectly designed or not.
This type of testing is possible after the unit testing when all/some components are integrated. This type of testing will make sure that when components are integrated, do they affect each others' working capabilities or functionalities?
This type of testing is done at the last when system is integrated successfully and ready to go on production server.
This type of testing will make sure that every important functionality from start to end is working fine and system is ready to deploy on production server.
This type of testing is important to test that unintended/unwanted defects are not present in the system when developer fixed some issues. This testing also make sure that all the bugs are successfully solved and because of that no other issues are occurred.
You need to add the following line into your Apache config file:
AddType application/x-httpd-php .htm .html
You also need two other things:
Allow Overridding
In your_site.conf
file (e.g. under /etc/apache2/mods-available
in my case), add the following lines:
<Directory "<path_to_your_html_dir(in my case: /var/www/html)>">
AllowOverride All
</Directory>
Enable Rewrite Mod
Run this command on your machine:
sudo a2enmod rewrite
After any of those steps, you should restart apache:
sudo service apache2 restart
Fn + Up/Down can scroll Terminal in Mac OS X 10.11
Do it as follows :-
@Id
@GenericGenerator(name="kaugen" , strategy="increment")
@GeneratedValue(generator="kaugen")
@Column(name="proj_id")
public Integer getId() {
return id;
}
You can use any arbitrary name instead of kaugen. It worked well, I could see below queries on console
Hibernate: select max(proj_id) from javaproj
Hibernate: insert into javaproj (AUTH_email, AUTH_firstName, AUTH_lastName, projname, proj_id) values (?, ?, ?, ?, ?)
Some good answers here but just adding an approach that won't be affected by borders and padding:
<style type="text/css">
html, body{width: 100%; height: 100%; padding: 0; margin: 0}
div{position: absolute; padding: 1em; border: 1px solid #000}
#nw{background: #f09; top: 0; left: 0; right: 50%; bottom: 50%}
#ne{background: #f90; top: 0; left: 50%; right: 0; bottom: 50%}
#sw{background: #009; top: 50%; left: 0; right: 50%; bottom: 0}
#se{background: #090; top: 50%; left: 50%; right: 0; bottom: 0}
</style>
<div id="nw">test</div>
<div id="ne">test</div>
<div id="sw">test</div>
<div id="se">test</div>
.button {
border: none;
background: url('/forms/up.png') no-repeat top left;
padding: 2px 8px;
}
You can normally check for ASCII letters or numbers using simple conditions
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
{
/*This is an alphabet*/
}
For digits you can use
if (ch >= '0' && ch <= '9')
{
/*It is a digit*/
}
But since characters in C are internally treated as ASCII values you can also use ASCII values to check the same.
Using inline styles:
<input type="text" style="text-align: right"/>
or, put it in a style sheet, like so:
<style>
.rightJustified {
text-align: right;
}
</style>
and reference the class:
<input type="text" class="rightJustified"/>
Another thing to check, which happened to be my solution (found here), is how data is being returned from your server. In my application, I'm using PDO to connect from PHP to MySQL. I needed to add a flag to the connection which said get the data back in UTF-8 format
The answer was
$dbHandle = new PDO("mysql:host=$dbHost;dbname=$dbName;charset=utf8", $dbUser, $dbPass,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
It's a known bug, it's not because of large files. Since Android Caches the Drawables, it's going out of memory after using few images. But I've found an alternate way for it, by skipping the android default cache system.
Solution: Move the images to "assets" folder and use the following function to get BitmapDrawable:
public static Drawable getAssetImage(Context context, String filename) throws IOException {
AssetManager assets = context.getResources().getAssets();
InputStream buffer = new BufferedInputStream((assets.open("drawable/" + filename + ".png")));
Bitmap bitmap = BitmapFactory.decodeStream(buffer);
return new BitmapDrawable(context.getResources(), bitmap);
}
There are a number utility functions or services that are better cached in the same way that System.Random should be, so it lends itself to a generic implementation:
static public class CachedService<T> where T : new() {
static public T Get { get; } = new T();
}
To use for random (or similar):
CachedService<System.Random>.Get.Next(999);
a = "A long string with a . in the middle ending with ."
# if you want to find the index of the last occurrence of any string, In our case we #will find the index of the last occurrence of with
index = a.rfind("with")
# the result will be 44, as index starts from 0.
Give Icomoon a try. You can upload your own SVGs, add them to the library, then create a custom font combining FontAwesome with your own icons.
This requires no special permissions, and works with the Storage Access Framework, as well as the unofficial ContentProvider
pattern (file path in _data
field).
/**
* Get a file path from a Uri. This will get the the path for Storage Access
* Framework Documents, as well as the _data field for the MediaStore and
* other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @author paulburke
*/
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
See an up-to-date version of this method here.
Found a way with two (2) easy codes here. First do a mysqldump:
mysqldump -uUSERNAME -p DATABASE_NAME > database-dump.sql
then grep the sqldump file:
grep -i "Search string" database-dump.sql
It possible also to find/replace and re-import back to the database.
This can be achieved using dplyr package, which is available in CRAN. The simple way to achieve this:
dplyr
package. library(dplyr)
df<- select(filter(dat,name=='tom'| name=='Lynn'), c('days','name))
Explanation:
So, once we’ve downloaded dplyr, we create a new data frame by using two different functions from this package:
filter: the first argument is the data frame; the second argument is the condition by which we want it subsetted. The result is the entire data frame with only the rows we wanted. select: the first argument is the data frame; the second argument is the names of the columns we want selected from it. We don’t have to use the names() function, and we don’t even have to use quotation marks. We simply list the column names as objects.
If you installed IIS after the .Net framework you can solve the porblem by re-installing the .Net framework. Part of its install detects whether IIS is present and updates IIS accordingly.
According to official documentation: Creating REST Controllers with the @RestController annotation
@RestController is a stereotype annotation that combines @ResponseBody and @Controller. More than that, it gives more meaning to your Controller and also may carry additional semantics in future releases of the framework.
It seems that it's best to use @RestController
for clarity, but you can also combine it with ResponseEntity
for flexibility when needed (According to official tutorial and the code here and my question to confirm that).
For example:
@RestController
public class MyController {
@GetMapping(path = "/test")
@ResponseStatus(HttpStatus.OK)
public User test() {
User user = new User();
user.setName("Name 1");
return user;
}
}
is the same as:
@RestController
public class MyController {
@GetMapping(path = "/test")
public ResponseEntity<User> test() {
User user = new User();
user.setName("Name 1");
HttpHeaders responseHeaders = new HttpHeaders();
// ...
return new ResponseEntity<>(user, responseHeaders, HttpStatus.OK);
}
}
This way, you can define ResponseEntity
only when needed.
Update
You can use this:
return ResponseEntity.ok().headers(responseHeaders).body(user);
The answer given by @HursVanBloob works only with fixed width parent container, but fails in case of fluid-width containers.
I tried a lot of properties, but nothing worked as expected. Finally I came to a conclusion that giving word-spacing
a very huge value works perfectly fine.
p { word-spacing: 9999999px; }
or, for the modern browsers you can use the CSS vw
unit (visual width in % of the screen size).
p { word-spacing: 100vw; }
a div usually needs at least a non-breaking space ( ) in order to have a width.
If you are running PHP on Apache then you can use the enviroment variable called DOCUMENT_ROOT
. This means that the path is dynamic, and can be moved between servers without messing about with the code.
<?php
$fileLocation = getenv("DOCUMENT_ROOT") . "/myfile.txt";
$file = fopen($fileLocation,"w");
$content = "Your text here";
fwrite($file,$content);
fclose($file);
?>
Cron jobs usually are stored in a per-user file under /var/spool/cron
The simplest thing for you to do is probably just create a text file with the job configured, then copy it to the cron spool folder and make sure it has the right permissions (600).
While AngularJS allows you to get a hand on a click event (and thus a target of it) with the following syntax (note the $event
argument to the setMaster
function; documentation here: http://docs.angularjs.org/api/ng.directive:ngClick):
function AdminController($scope) {
$scope.setMaster = function(obj, $event){
console.log($event.target);
}
}
this is not very angular-way of solving this problem. With AngularJS the focus is on the model manipulation. One would mutate a model and let AngularJS figure out rendering.
The AngularJS-way of solving this problem (without using jQuery and without the need to pass the $event
argument) would be:
<div ng-controller="AdminController">
<ul class="list-holder">
<li ng-repeat="section in sections" ng-class="{active : isSelected(section)}">
<a ng-click="setMaster(section)">{{section.name}}</a>
</li>
</ul>
<hr>
{{selected | json}}
</div>
where methods in the controller would look like this:
$scope.setMaster = function(section) {
$scope.selected = section;
}
$scope.isSelected = function(section) {
return $scope.selected === section;
}
Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/WXJ3p/15/
Named export
In TS you can export with the export
keyword. It then can be imported via import {name} from "./mydir";
. This is called a named export. A file can export multiple named exports. Also the names of the imports have to match the exports. For example:
// foo.js file
export class foo{}
export class bar{}
// main.js file in same dir
import {foo, bar} from "./foo";
The following alternative syntax is also valid:
// foo.js file
function foo() {};
function bar() {};
export {foo, bar};
// main.js file in same dir
import {foo, bar} from './foo'
Default export
We can also use a default export. There can only be one default export per file. When importing a default export we omit the square brackets in the import statement. We can also choose our own name for our import.
// foo.js file
export default class foo{}
// main.js file in same directory
import abc from "./foo";
It's just JavaScript
Modules and their associated keyword like import
, export
, and export default
are JavaScript constructs, not typescript. However typescript added the exporting and importing of interfaces and type aliases to it.
While a lot of the above answers give ways to embed an image using a file or with Python code, there is a way to embed an image in the jupyter notebook itself using only markdown and base64!
To view an image in the browser, you can visit the link data:image/png;base64,**image data here**
for a base64-encoded PNG image, or data:image/jpg;base64,**image data here**
for a base64-encoded JPG image. An example link can be found at the end of this answer.
To embed this into a markdown page, simply use a similar construct as the file answers, but with a base64 link instead: ![**description**](data:image/**type**;base64,**base64 data**)
. Now your image is 100% embedded into your Jupyter Notebook file!
Example link: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABHNCSVQICAgIfAhkiAAAAD9JREFUGJW1jzEOADAIAqHx/1+mE4ltNXEpI3eJQknCIGsiHSLJB+aO/06PxOo/x2wBgKR2jCeEy0rOO6MDdzYQJRcVkl1NggAAAABJRU5ErkJggg==
Example markdown:
![smile](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABHNCSVQICAgIfAhkiAAAAD9JREFUGJW1jzEOADAIAqHx/1+mE4ltNXEpI3eJQknCIGsiHSLJB+aO/06PxOo/x2wBgKR2jCeEy0rOO6MDdzYQJRcVkl1NggAAAABJRU5ErkJggg==)
select *
from MyTable
where CAST(Created as time) not between '07:00' and '22:59:59 997'
The solution i found was
const [files, setFiles] = useState([] as any);
This problem comes when you are writing data in many files simultaneously and your Operating System has a fixed limit of Open files. In Linux, you can increase the limit of open files.
https://www.tecmint.com/increase-set-open-file-limits-in-linux/
There is no way to identify the charset of a string that is completely accurate. There are ways to try to guess the charset. One of these ways, and probably/currently the best in PHP, is mb_detect_encoding(). This will scan your string and look for occurrences of stuff unique to certain charsets. Depending on your string, there may not be such distinguishable occurrences.
Take the ISO-8859-1 charset vs ISO-8859-15 ( http://en.wikipedia.org/wiki/ISO/IEC_8859-15#Changes_from_ISO-8859-1 )
There's only a handful of different characters, and to make it worse, they're represented by the same bytes. There is no way to detect, being given a string without knowing it's encoding, whether byte 0xA4 is supposed to signify ¤ or € in your string, so there is no way to know it's exact charset.
(Note: you could add a human factor, or an even more advanced scanning technique (e.g. what Oroboros102 suggests), to try to figure out based upon the surrounding context, if the character should be ¤ or €, though this seems like a bridge too far)
There are more distinguishable differences between e.g. UTF-8 and ISO-8859-1, so it's still worth trying to figure it out when you're unsure, though you can and should never rely on it being correct.
Interesting read: http://kore-nordmann.de/blog/php_charset_encoding_FAQ.html#how-do-i-determine-the-charset-encoding-of-a-string
There are other ways of ensuring the correct charset though. Concerning forms, try to enforce UTF-8 as much as possible (check out snowman to make sure yout submission will be UTF-8 in every browser: http://intertwingly.net/blog/2010/07/29/Rails-and-Snowmen ) That being done, at least you're can be sure that every text submitted through your forms is utf_8. Concerning uploaded files, try running the unix 'file -i' command on it through e.g. exec() (if possible on your server) to aid the detection (using the document's BOM.) Concerning scraping data, you could read the HTTP headers, that usually specify the charset. When parsing XML files, see if the XML meta-data contain a charset definition.
Rather than trying to automagically guess the charset, you should first try to ensure a certain charset yourself where possible, or trying to grab a definition from the source you're getting it from (if applicable) before resorting to detection.
By code:
btn_edit.IsEnabled = true;
By XAML:
<Button Content="Edit data" Grid.Column="1" Name="btn_edit" Grid.Row="1" IsEnabled="False" />
Starting with Safari 5/Firefox 4, it’s easiest to use the FormData
class:
var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
So now you have a FormData
object, ready to be sent along with the XMLHttpRequest.
jQuery.ajax({
url: 'php/upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
method: 'POST',
type: 'POST', // For jQuery < 1.9
success: function(data){
alert(data);
}
});
It’s imperative that you set the contentType
option to false
, forcing jQuery not to add a Content-Type
header for you, otherwise, the boundary string will be missing from it.
Also, you must leave the processData
flag set to false, otherwise, jQuery will try to convert your FormData
into a string, which will fail.
You may now retrieve the file in PHP using:
$_FILES['file-0']
(There is only one file, file-0
, unless you specified the multiple
attribute on your file input, in which case, the numbers will increment with each file.)
Using the FormData emulation for older browsers
var opts = {
url: 'php/upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
method: 'POST',
type: 'POST', // For jQuery < 1.9
success: function(data){
alert(data);
}
};
if(data.fake) {
// Make sure no text encoding stuff is done by xhr
opts.xhr = function() { var xhr = jQuery.ajaxSettings.xhr(); xhr.send = xhr.sendAsBinary; return xhr; }
opts.contentType = "multipart/form-data; boundary="+data.boundary;
opts.data = data.toString();
}
jQuery.ajax(opts);
Create FormData from an existing form
Instead of manually iterating the files, the FormData object can also be created with the contents of an existing form object:
var data = new FormData(jQuery('form')[0]);
Use a PHP native array instead of a counter
Just name your file elements the same and end the name in brackets:
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file[]', file);
});
$_FILES['file']
will then be an array containing the file upload fields for every file uploaded. I actually recommend this over my initial solution as it’s simpler to iterate over.
Update Angular CLI for a workspace (Local)
npm install --save -dev @angular/cli@latest
Note: Make sure to install the global version using the command with ‘-g’ is if it installed properly.
npm install -g @angular/cli@latest
Run Update command to get a list of all dependencies required to be upgraded
ng update
Next Run update command as below for each individual Angular core package
ng update @angular/cli @angular/core
However, I had to add ‘–force’ and ‘–allow-dirty’ flags command additionally to fix all other pending issues.
ng update @angular/cli @angular/core --allow-dirty --force
Extracts myArchive.tar to /destinationDirectory
Commands:
cd /destinationDirectory
pax -rv -f myArchive.tar -s ',^/,,'
I came across this myself. I used .on
so it looks a bit different but I did this:
$('#element').on('keypress', function() {
//code to be executed
}).on('keydown', function(e) {
if (e.keyCode==8)
$('element').trigger('keypress');
});
Adding my Work Around here. I needed to delete ssn typed by user so i did this in jQuery
$(this).bind("keydown", function (event) {
// Allow: backspace, delete
if (event.keyCode == 46 || event.keyCode == 8)
{
var tempField = $(this).attr('name');
var hiddenID = tempField.substr(tempField.indexOf('_') + 1);
$('#' + hiddenID).val('');
$(this).val('')
return;
} // Allow: tab, escape, and enter
else if (event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
else
{
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105))
{
event.preventDefault();
}
}
});
hashCode()
is used for bucketing in Hash
implementations like HashMap
, HashTable
, HashSet
, etc.
The value received from hashCode()
is used as the bucket number for storing elements of the set/map. This bucket number is the address of the element inside the set/map.
When you do contains()
it will take the hash code of the element, then look for the bucket where hash code points to. If more than 1 element is found in the same bucket (multiple objects can have the same hash code), then it uses the equals()
method to evaluate if the objects are equal, and then decide if contains()
is true or false, or decide if element could be added in the set or not.
Morgan :- Morgan is a middleware which will help us to identify the clients who are accessing our application. Basically a logger.
To Use Morgan, We need to follow below steps :-
npm install --save morgan
This will add morgan to json.package file
var morgan = require('morgan');
3> // create a write stream (in append mode)
var accessLogStream = fs.createWriteStream(
path.join(__dirname, 'access.log'), {flags: 'a'}
);
// setup the logger
app.use(morgan('combined', {stream: accessLogStream}));
Note: Make sure you do not plumb above blindly make sure you have every conditions where you need .
Above will automatically create a access.log file to your root once user will access your app.
You have your ssh clone
statement wrong: git clone username [email protected]:root/test.git
That statement would try to clone a repository named username
into the location relative to your current path, [email protected]:root/test.git
.
You want to leave out username
:
git clone [email protected]:root/test.git
I don't think you can attach down into a window that you are instancing... I KNOW you can't do it if the url's are on different domains (XSS and all that jazz), but you can talk UP from that window and access elements of the parent window assuming they are on the same domain. your best bet is to attach the stylesheet at the page you are loading, and if that page isn't on the same domain, (e.g. trying to restyle some one else's page,) you won't be able to.
Agree with redsquare however it is worth mentioning that if you have a two word property like text-align
you would do this:
$("#message").css({ width: '30px', height: '10px', 'text-align': 'center'});
>>> L = [1,2,3]
>>> " ".join(str(x) for x in L)
'1 2 3'
Since you are using JSON.NET, personally I would go with serialization so that you can have Intellisense support for your object. You'll need a class that represents your JSON structure. You can build this by hand, or you can use something like json2csharp to generate it for you:
e.g.
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class RootObject
{
public List<Person> People { get; set; }
}
Then, you can simply call JsonConvert
's methods to deserialize the JSON into an object:
RootObject instance = JsonConvert.Deserialize<RootObject>(json);
Then you have Intellisense:
var firstName = instance.People[0].FirstName;
var lastName = instance.People[0].LastName;
public static byte[] intToBytes(int x) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(bos);
out.writeInt(x);
out.close();
byte[] int_bytes = bos.toByteArray();
bos.close();
return int_bytes;
}
A simple method involves using the get and set functions on the variable
using System;
public string Name{
get{
return name;
}
set{
name= value;
OnVarChange?.Invoke();
}
}
private string name;
public event System.Action OnVarChange;
#define DEBUG
#ifdef DEBUG
#define PRINT print
#else
#define PRINT(...) ((void)0) //strip out PRINT instructions from code
#endif
void print(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
vsprintf(str, fmt, args);
va_end(args);
printf("%s\n", str);
}
int main() {
PRINT("[%s %d, %d] Hello World", "March", 26, 2009);
return 0;
}
If the compiler does not understand variadic macros, you can also strip out PRINT with either of the following:
#define PRINT //
or
#define PRINT if(0)print
The first comments out the PRINT instructions, the second prevents PRINT instruction because of a NULL if condition. If optimization is set, the compiler should strip out never executed instructions like: if(0) print("hello world"); or ((void)0);
In one line, using Java 8:
list.sort(Comparator.naturalOrder());
There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:
With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.
Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/
Update 2019:
You can concisely initialize a vector<string>
from a statically-created char*
array:
char* strarray[] = {"hey", "sup", "dogg"};
vector<string> strvector(strarray, strarray + 3);
This copies all the strings, by the way, so you use twice the memory. You can use Will Dean's suggestion to replace the magic number 3 here with arraysize(str_array) -- although I remember there being some special case in which that particular version of arraysize might do Something Bad (sorry I can't remember the details immediately). But it very often works correctly.
Also, if you're really gung-ho about the one line thingy, you can define a variadic macro so that a single line such as DEFINE_STR_VEC(strvector, "hi", "there", "everyone");
works.
for debian users its 'easy' to create their own libopencv-nonfree package.
i followed the opencv tutorial for python, but in my debian the SIFT and SURF modules were missing. And there is no non-free package available for debian including SIFT and SURF etc.
They were stripped from the package due to license issues....
i never created a package for debian before (adding a new module etc) but i followed some small steps in the debian tutorials and tried and guessed around a bit, and after 1 day, voila... i got working a libopencv-nonfree2.4 deb package and a python module with correct bindings.
(i dont know if i also needed to install the newly built python-opencv package or only the nonfree... i re-installed both and got a working python opencv library with all necessary nonfree modules!)
ok, here it is:
!this is for libopencv 2.4!
!you can do all steps except installing as a normal user!
we need the built essesntials and some tools from debian repository to compile and create a new package:
sudo apt-get install build-essential fakeroot devscripts
create a directory in your home and change to that directory:
cd ~ && mkdir opencv-debian
cd opencv-debian
download the needed packages:
apt-get source libopencv-core2.4
and download all needed dependency packages to build the new opencv
apt-get build-dep libopencv-core2.4
this will download the neeeded sources and create a directory called "opencv-2.4.9.1+dfsg"
change to that directory:
cd opencv-2.4.9.1+dfsg
now you can test if the package will built without modifications by typing:
fakeroot debian/rules binary
this will take a long time! this step should finish without errors you now have a lot of .deb packages in your opencv-debian directory
now we make some modifications to the package definition to let debian buld the nonfree modules and package!
change to the opencv-debian directory and download the correct opencv source.. in my case opencv 2.4.9 or so
i got mine from https://github.com/Itseez/opencv/releases
wget https://codeload.github.com/Itseez/opencv/tar.gz/2.4.9
this will download opencv-2.4.9.tar.gz
extract the archive:
tar -xzvf opencv-2.4.9.tar.gz
this will unpack the original source to a directory called opencv-2.4.9
now copy the nonfree modules from original source to the debian source:
cp -rv opencv-2.4.9/modules/nonfree opencv-2.4.9.1+dfsg/modules/
ok, now we have the source of the nonfree modules, but thats not enough for debian... we need to modify 1 file and create a new one
we have to edit the debian control file and add a new section at end of file: (i use mcedit as an editor here)
mcedit opencv-2.4.9.1+dfsg/debian/control
or use any other editor of your choice
and add this section:
Package: libopencv-nonfree2.4
Architecture: any
Depends: ${shlibs:Depends}, ${misc:Depends}
Description: OpenCV Nonfree Modules like SIFT and SURF
This package contains nonfree modules for the OpenCV (Open Computer Vision)
library.
.
The Open Computer Vision Library is a collection of algorithms and sample
code for various computer vision problems. The library is compatible with
IPL (Intel's Image Processing Library) and, if available, can use IPP
(Intel's Integrated Performance Primitives) for better performance.
.
OpenCV provides low level portable data types and operators, and a set
of high level functionalities for video acquisition, image processing and
analysis, structural analysis, motion analysis and object tracking, object
recognition, camera calibration and 3D reconstruction.
now we create a new file called libopencv-nonfree2.4.install
touch opencv-2.4.9.1+dfsg/debian/libopencv-nonfree2.4.install
and edit:
mcedit opencv-2.4.9.1+dfsg/debian/libopencv-nonfree2.4.install
and add the following content:
usr/lib/*/libopencv_nonfree.so.*
ok, thats it, now create the packages again:
cd opencv-2.4.9.1+dfsg
first a clean up:
fakeroot debian/rules clean
and build:
fakeroot debian/rules binary
et voila... after a while you have a fresh built and a new package libopencv-nonfree2.4.deb!
now install as root:
dpkg -i libopencv-nonfree2.4.deb
dpkg -i python-opencv.deb
and test!
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('test.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
sift = cv2.SIFT()
kp = sift.detect(gray,None)
img=cv2.drawKeypoints(gray,kp)
corners = cv2.goodFeaturesToTrack(gray,16,0.05,10)
corners = np.int0(corners)
for i in corners:
x,y = i.ravel()
cv2.circle(img,(x,y),90,255,3)
plt.imshow(img),plt.show()
have fun!
Something like this - for each line read into string variable a
:
>>> a = "123,456"
>>> b = a.split(",")
>>> b
['123', '456']
>>> c = [int(e) for e in b]
>>> c
[123, 456]
>>> x, y = c
>>> x
123
>>> y
456
Now you can do what is necessary with x
and y
as assigned, which are integers.
This method will not truncate a word in the middle.
list($output)=explode("\n",wordwrap(strip_tags($str),500),1);
echo $output. ' ... <a href="#">Read more</a>';
We have experienced the same issue when moving the sql server in-house.
A good solution that we ended up using is splitting the sql file into chunks. There are several ways to do that. Use
http://www.ozerov.de/bigdump/ seems good (but never used it)
http://www.rusiczki.net/2007/01/24/sql-dump-file-splitter/ used it and it was very useful to get structure out of the mess and you can take it from there.
Hope this helps :)
Is there a command that does?
thread apply all where
You have to use the FormulaEvaluator, as shown here. This will return a value that is either the value present in the cell or the result of the formula if the cell contains such a formula :
FileInputStream fis = new FileInputStream("/somepath/test.xls");
Workbook wb = new HSSFWorkbook(fis); //or new XSSFWorkbook("/somepath/test.xls")
Sheet sheet = wb.getSheetAt(0);
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
// suppose your formula is in B3
CellReference cellReference = new CellReference("B3");
Row row = sheet.getRow(cellReference.getRow());
Cell cell = row.getCell(cellReference.getCol());
if (cell!=null) {
switch (evaluator.evaluateFormulaCell(cell)) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.println(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BLANK:
break;
case Cell.CELL_TYPE_ERROR:
System.out.println(cell.getErrorCellValue());
break;
// CELL_TYPE_FORMULA will never occur
case Cell.CELL_TYPE_FORMULA:
break;
}
}
if you need the exact contant (ie the formla if the cell contains a formula), then this is shown here.
Edit : Added a few example to help you.
first you get the cell (just an example)
Row row = sheet.getRow(rowIndex+2);
Cell cell = row.getCell(1);
If you just want to set the value into the cell using the formula (without knowing the result) :
String formula ="ABS((1-E"+(rowIndex + 2)+"/D"+(rowIndex + 2)+")*100)";
cell.setCellFormula(formula);
cell.setCellStyle(this.valueRightAlignStyleLightBlueBackground);
if you want to change the message if there is an error in the cell, you have to change the formula to do so, something like
IF(ISERR(ABS((1-E3/D3)*100));"N/A"; ABS((1-E3/D3)*100))
(this formula check if the evaluation return an error and then display the string "N/A", or the evaluation if this is not an error).
if you want to get the value corresponding to the formula, then you have to use the evaluator.
Hope this help,
Guillaume
To my understanding, when you need to train a NN, you need a large dataset involves many data items. when NN is being trained, data items go in to NN one by one, that is called an iteration; When the whole dataset goes through, it is called an epoch.
in my case favorPathExtension(false) helped me
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer
.setUseSuffixPatternMatch(false); // to use special character in path variables, for example, `[email protected]`
}
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer
.favorPathExtension(false); // to avoid HttpMediaTypeNotAcceptableException on standalone tomcat
}
}
Another elegant one is
header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
exit;
HttpCookie cook = new HttpCookie("testcook");
cook = Request.Cookies["CookName"];
if (cook != null)
{
lbl_cookie_value.Text = cook.Value;
}
else
{
lbl_cookie_value.Text = "Empty value";
}
Reference Click here
For Sql Server you can resort to Dynamic SQL.
Most of the time in such situations you have the parameter of IN clause based on some data from database.
The example below is a little "forced", but this can match various real cases found in legacy databases.
Suppose you have table Persons where person names are stored in a single field PersonName as FirstName + ' ' + LastName. You need to select all persons from a list of first names, stored in field NameToSelect in table NamesToSelect, plus some additional criteria (like filtered on gender, birth date, etc)
You can do it as follows
-- @gender is nchar(1), @birthDate is date
declare
@sql nvarchar(MAX),
@subWhere nvarchar(MAX)
@params nvarchar(MAX)
-- prepare the where sub-clause to cover LIKE IN (...)
-- it will actually generate where clause PersonName Like 'param1%' or PersonName Like 'param2%' or ...
set @subWhere = STUFF(
(
SELECT ' OR PersonName like ''' + [NameToSelect] + '%'''
FROM [NamesToSelect] t FOR XML PATH('')
), 1, 4, '')
-- create the dynamic SQL
set @sql ='select
PersonName
,Gender
,BirstDate -- and other field here
from [Persons]
where
Gender = @gender
AND BirthDate = @birthDate
AND (' + @subWhere + ')'
set @params = ' @gender nchar(1),
@birthDate Date'
EXECUTE sp_executesql @sql, @params,
@gender,
@birthDate
All other answer are correct, but remember that if you cast double to int you will loss decimal value.. so 2.9 double become 2 int.
You can use Math.round(double)
function or simply do :
(int)(yourDoubleValue + 0.5d)
Easier if the input is a string, we can use split()
decimal = input("Input decimal number: ") #123.456
# split 123.456 by dot = ['123', '456']
after_coma = decimal.split('.')[1]
# because only index 1 is taken then '456'
print(after_coma) # '456'
if you want to make a number type print(int(after_coma)) # 456
It's the first result on Google: http://docs.python.org/library/stdtypes.html#string-formatting
See also the new format() function: http://docs.python.org/library/stdtypes.html#str.format
Starting with your table definition:
- UserID
- Fname
- Lname
- Email
- Password
- IV
Here are the changes:
Fname
, Lname
and Email
will be encrypted using a symmetric cipher, provided by OpenSSL,IV
field will store the initialisation vector used for encryption. The storage requirements depend on the cipher and mode used; more about this later.Password
field will be hashed using a one-way password hash,Cipher and mode
Choosing the best encryption cipher and mode is beyond the scope of this answer, but the final choice affects the size of both the encryption key and initialisation vector; for this post we will be using AES-256-CBC which has a fixed block size of 16 bytes and a key size of either 16, 24 or 32 bytes.
Encryption key
A good encryption key is a binary blob that's generated from a reliable random number generator. The following example would be recommended (>= 5.3):
$key_size = 32; // 256 bits
$encryption_key = openssl_random_pseudo_bytes($key_size, $strong);
// $strong will be true if the key is crypto safe
This can be done once or multiple times (if you wish to create a chain of encryption keys). Keep these as private as possible.
IV
The initialisation vector adds randomness to the encryption and required for CBC mode. These values should be ideally be used only once (technically once per encryption key), so an update to any part of a row should regenerate it.
A function is provided to help you generate the IV:
$iv_size = 16; // 128 bits
$iv = openssl_random_pseudo_bytes($iv_size, $strong);
Let's encrypt the name field, using the earlier $encryption_key
and $iv
; to do this, we have to pad our data to the block size:
function pkcs7_pad($data, $size)
{
$length = $size - strlen($data) % $size;
return $data . str_repeat(chr($length), $length);
}
$name = 'Jack';
$enc_name = openssl_encrypt(
pkcs7_pad($name, 16), // padded data
'AES-256-CBC', // cipher and mode
$encryption_key, // secret key
0, // options (not used)
$iv // initialisation vector
);
The encrypted output, like the IV, is binary; storing these values in a database can be accomplished by using designated column types such as BINARY
or VARBINARY
.
The output value, like the IV, is binary; to store those values in MySQL, consider using BINARY
or VARBINARY
columns. If this is not an option, you can also convert the binary data into a textual representation using base64_encode()
or bin2hex()
, doing so requires between 33% to 100% more storage space.
Decryption of the stored values is similar:
function pkcs7_unpad($data)
{
return substr($data, 0, -ord($data[strlen($data) - 1]));
}
$row = $result->fetch(PDO::FETCH_ASSOC); // read from database result
// $enc_name = base64_decode($row['Name']);
// $enc_name = hex2bin($row['Name']);
$enc_name = $row['Name'];
// $iv = base64_decode($row['IV']);
// $iv = hex2bin($row['IV']);
$iv = $row['IV'];
$name = pkcs7_unpad(openssl_decrypt(
$enc_name,
'AES-256-CBC',
$encryption_key,
0,
$iv
));
You can further improve the integrity of the generated cipher text by appending a signature that's generated from a secret key (different from the encryption key) and the cipher text. Before the cipher text is decrypted, the signature is first verified (preferably with a constant-time comparison method).
// generate once, keep safe
$auth_key = openssl_random_pseudo_bytes(32, $strong);
// authentication
$auth = hash_hmac('sha256', $enc_name, $auth_key, true);
$auth_enc_name = $auth . $enc_name;
// verification
$auth = substr($auth_enc_name, 0, 32);
$enc_name = substr($auth_enc_name, 32);
$actual_auth = hash_hmac('sha256', $enc_name, $auth_key, true);
if (hash_equals($auth, $actual_auth)) {
// perform decryption
}
See also: hash_equals()
Storing a reversible password in your database must be avoided as much as possible; you only wish to verify the password rather than knowing its contents. If a user loses their password, it's better to allow them to reset it rather than sending them their original one (make sure that password reset can only be done for a limited time).
Applying a hash function is a one-way operation; afterwards it can be safely used for verification without revealing the original data; for passwords, a brute force method is a feasible approach to uncover it due to its relatively short length and poor password choices of many people.
Hashing algorithms such as MD5 or SHA1 were made to verify file contents against a known hash value. They're greatly optimized to make this verification as fast as possible while still being accurate. Given their relatively limited output space it was easy to build a database with known passwords and their respective hash outputs, the rainbow tables.
Adding a salt to the password before hashing it would render a rainbow table useless, but recent hardware advancements made brute force lookups a viable approach. That's why you need a hashing algorithm that's deliberately slow and simply impossible to optimize. It should also be able to increase the load for faster hardware without affecting the ability to verify existing password hashes to make it future proof.
Currently there are two popular choices available:
This answer will use an example with bcrypt.
Generation
A password hash can be generated like this:
$password = 'my password';
$random = openssl_random_pseudo_bytes(18);
$salt = sprintf('$2y$%02d$%s',
13, // 2^n cost factor
substr(strtr(base64_encode($random), '+', '.'), 0, 22)
);
$hash = crypt($password, $salt);
The salt is generated with openssl_random_pseudo_bytes()
to form a random blob of data which is then run through base64_encode()
and strtr()
to match the required alphabet of [A-Za-z0-9/.]
.
The crypt()
function performs the hashing based on the algorithm ($2y$
for Blowfish), the cost factor (a factor of 13 takes roughly 0.40s on a 3GHz machine) and the salt of 22 characters.
Validation
Once you have fetched the row containing the user information, you validate the password in this manner:
$given_password = $_POST['password']; // the submitted password
$db_hash = $row['Password']; // field with the password hash
$given_hash = crypt($given_password, $db_hash);
if (isEqual($given_hash, $db_hash)) {
// user password verified
}
// constant time string compare
function isEqual($str1, $str2)
{
$n1 = strlen($str1);
if (strlen($str2) != $n1) {
return false;
}
for ($i = 0, $diff = 0; $i != $n1; ++$i) {
$diff |= ord($str1[$i]) ^ ord($str2[$i]);
}
return !$diff;
}
To verify a password, you call crypt()
again but you pass the previously calculated hash as the salt value. The return value yields the same hash if the given password matches the hash. To verify the hash, it's often recommended to use a constant-time comparison function to avoid timing attacks.
Password hashing with PHP 5.5
PHP 5.5 introduced the password hashing functions that you can use to simplify the above method of hashing:
$hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 13]);
And verifying:
if (password_verify($given_password, $db_hash)) {
// password valid
}
See also: password_hash()
, password_verify()
I was searching an answer for this same question and found ENTRYPOINT in Dockerfile solution for me.
Dockerfile
...
ENTRYPOINT /my-script.sh ; /my-script2.sh ; /bin/bash
Now the scripts are executed when I start the container and I get the bash prompt after the scripts has been executed.
Use the @ViewChildren decorator combined with QueryList. Both of these are from "@angular/core"
@ViewChildren(CustomComponent) customComponentChildren: QueryList<CustomComponent>;
Doing something with each child looks like:
this.customComponentChildren.forEach((child) => { child.stuff = 'y' })
There is further documentation to be had at angular.io, specifically: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#sts=Parent%20calls%20a%20ViewChild
Unfortunately, this is not possible. Per the spec:
Generated content does not alter the document tree. In particular, it is not fed back to the document language processor (e.g., for reparsing).
In other words, for string values this means the value is always treated literally. It is never interpreted as markup, regardless of the document language in use.
As an example, using the given CSS with the following HTML:
<h1 class="header">Title</h1>
... will result in the following output:
footerText {
line-height: 20px;
}
you don't need to start playing with position or even layout of other elements... use this simple solution
A void* can point to anything (it's a raw pointer without any type info).
For those wondering about a solution using the data.table way, here is one I wrote a function for, available on my Github:
library(devtools)
source_url("https://github.com/YoannPa/Miscellaneous/blob/master/datatable_pattern_substitution.R?raw=TRUE")
dt.sub(DT = dat2, pattern = "^$|^ $",replacement = NA)
dat2
The function goes through each column, to identify which column contains pattern matches. Then gsub()
is aplied only on columns containing matches for the pattern "^$|^ $"
, to substitutes matches by NA
s.
I will keep improving this function to make it faster.
This worked for me, no delayed expansion necessary:
@echo off
(
echo ^<html^>
echo ^<body^>
echo Hello
echo ^</body^>
echo ^</html^>
)
pause
It writes output like this:
<html>
<body>
Hello
</body>
</html>
Press any key to continue . . .
On Linux you can also use:
struct timeval timeout;
timeout.tv_sec = 7; // after 7 seconds connect() will timeout
timeout.tv_usec = 0;
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
connect(...)
Don't forget to clear SO_SNDTIMEO
after connect()
if you don't need it.
In your broadcast receiver you could access a view via inflation a root layout from XML resource and then find all your views from this root layout with findViewByid():
View view = View.inflate(context, R.layout.ROOT_LAYOUT, null);
Now you can access your views via 'view' and cast them to your view type:
myImage = (ImageView) view.findViewById(R.id.my_image);
You are getting arithmetic overflow. this means you are trying to make a conversion impossible to be made. This error is thrown when you try to make a conversion and the destiny data type is not enough to convert the origin data. For example:
If you try to convert 100.52 to decimal(4,2) you will get this error. The number 100.52 requires 5 positions and 2 of them are decimal.
Try to change the decimal precision to something like 16,2 or higher. Try with few records first then use it to all your select.
You could use something like this:
Private Sub PrintTableOrView(ByVal table As DataTable, ByVal label As String)
Dim sw As System.IO.StringWriter
Dim output As String
Console.WriteLine(label)
' Loop through each row in the table. '
For Each row As DataRow In table.Rows
sw = New System.IO.StringWriter
' Loop through each column. '
For Each col As DataColumn In table.Columns
' Output the value of each column's data.
sw.Write(row(col).ToString() & ", ")
Next
output = sw.ToString
' Trim off the trailing ", ", so the output looks correct. '
If output.Length > 2 Then
output = output.Substring(0, output.Length - 2)
End If
' Display the row in the console window. '
Console.WriteLine(output)
Next
Console.WriteLine()
End Sub
Say you're dealing with some other delimiter, such as a \t
tab, instead of a \n
newline.
A more general approach to delimiters is the use of getc()
, which grabs one character at a time.
Note that getc()
returns an int
, so that we can test for equality with EOF
.
Secondly, we define an array line[BUFFER_MAX_LENGTH]
of type char
, in order to store up to BUFFER_MAX_LENGTH-1
characters on the stack (we have to save that last character for a \0
terminator character).
Use of an array avoids the need to use malloc
and free
to create a character pointer of the right length on the heap.
#define BUFFER_MAX_LENGTH 1024
int main(int argc, char* argv[])
{
FILE *file = NULL;
char line[BUFFER_MAX_LENGTH];
int tempChar;
unsigned int tempCharIdx = 0U;
if (argc == 2)
file = fopen(argv[1], "r");
else {
fprintf(stderr, "error: wrong number of arguments\n"
"usage: %s textfile\n", argv[0]);
return EXIT_FAILURE;
}
if (!file) {
fprintf(stderr, "error: could not open textfile: %s\n", argv[1]);
return EXIT_FAILURE;
}
/* get a character from the file pointer */
while(tempChar = fgetc(file))
{
/* avoid buffer overflow error */
if (tempCharIdx == BUFFER_MAX_LENGTH) {
fprintf(stderr, "error: line is too long. increase BUFFER_MAX_LENGTH.\n");
return EXIT_FAILURE;
}
/* test character value */
if (tempChar == EOF) {
line[tempCharIdx] = '\0';
fprintf(stdout, "%s\n", line);
break;
}
else if (tempChar == '\n') {
line[tempCharIdx] = '\0';
tempCharIdx = 0U;
fprintf(stdout, "%s\n", line);
continue;
}
else
line[tempCharIdx++] = (char)tempChar;
}
return EXIT_SUCCESS;
}
If you must use a char *
, then you can still use this code, but you strdup()
the line[]
array, once it is filled up with a line's worth of input. You must free
this duplicated string once you're done with it, or you'll get a memory leak:
#define BUFFER_MAX_LENGTH 1024
int main(int argc, char* argv[])
{
FILE *file = NULL;
char line[BUFFER_MAX_LENGTH];
int tempChar;
unsigned int tempCharIdx = 0U;
char *dynamicLine = NULL;
if (argc == 2)
file = fopen(argv[1], "r");
else {
fprintf(stderr, "error: wrong number of arguments\n"
"usage: %s textfile\n", argv[0]);
return EXIT_FAILURE;
}
if (!file) {
fprintf(stderr, "error: could not open textfile: %s\n", argv[1]);
return EXIT_FAILURE;
}
while(tempChar = fgetc(file))
{
/* avoid buffer overflow error */
if (tempCharIdx == BUFFER_MAX_LENGTH) {
fprintf(stderr, "error: line is too long. increase BUFFER_MAX_LENGTH.\n");
return EXIT_FAILURE;
}
/* test character value */
if (tempChar == EOF) {
line[tempCharIdx] = '\0';
dynamicLine = strdup(line);
fprintf(stdout, "%s\n", dynamicLine);
free(dynamicLine);
dynamicLine = NULL;
break;
}
else if (tempChar == '\n') {
line[tempCharIdx] = '\0';
tempCharIdx = 0U;
dynamicLine = strdup(line);
fprintf(stdout, "%s\n", dynamicLine);
free(dynamicLine);
dynamicLine = NULL;
continue;
}
else
line[tempCharIdx++] = (char)tempChar;
}
return EXIT_SUCCESS;
}
I'm a bit late to the party but I wrote a custom view that let's you do this, by default it's set to entypo, but you can modify it to use any iconfont: check it out here: github.com/MarsVard/IconView
// edit the library is old and not supported anymore... new one here https://github.com/MarsVard/IonIconView
You can use the $.ajax()
, and if you don't want to put the parameters directly into the URL, use the data:
. That's appended to the URL
The man
page has very detailed descriptions of all of the various options (the status bar is highly configurable). Your best bet is to read through man tmux
and pay particular attention to those options that begin with status-
.
So, for example, status-bg red
would set the background colour of the bar.
The three components of the bar, the left and right sections and the window-list in the middle, can all be configured to suit your preferences. status-left
and status-right
, in addition to having their own variables (like #S
to list the session name) can also call custom scripts to display, for example, system information like load average or battery time.
The option to rename windows or panes based on what is currently running in them is automatic-rename
. You can set, or disable it globally with:
setw -g automatic-rename [on | off]
The most straightforward way to become comfortable with building your own status bar is to start with a vanilla one and then add changes incrementally, reloading the config as you go.1
You might also want to have a look around on github or bitbucket for other people's conf files to provide some inspiration. You can see mine here2.
1 You can automate this by including this line in your .tmux.conf
:
bind R source-file ~/.tmux.conf \; display-message "Config reloaded..."
You can then test your new functionality with Ctrlb,Shiftr. tmux
will print a helpful error message—including a line number of the offending snippet—if you misconfigure an option.
2 Note: I call a different status bar depending on whether I am in X or the console - I find this quite useful.
The getPosts()
function seems to be expecting $con
to be global, but you're not declaring it as such.
A lot of programmers regard bald global variables as a "code smell". The alternative at the other end of the scale is to always pass around the connection resource. Partway between the two is a singleton call that always returns the same resource handle.
Here's an easy way using jQuery.
var scrollbarWidth = jQuery('div.withScrollBar').get(0).scrollWidth - jQuery('div.withScrollBar').width();
Basically we subtract the scrollable width from the overall width and that should provide the scrollbar's width. Of course, you'd want to cache the jQuery('div.withScrollBar') selection so you're not doing that part twice.
Not sure what your asking!
However
SELECT GETDATE()
Will get you the current date and time
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
Will get you just the date with time set to 00:00:00
What you want is:
cp -R t1/. t2/
The dot at the end tells it to copy the contents of the current directory, not the directory itself. This method also includes hidden files and folders.
You have System.out.println("Scanning...")
in a catch block.
Do you want to put that in try?
In a Spring project:
I typed wrong hibernate.packagesToScan=com.okan.springdemo.entity
and got this error.
Now it's working well.
I tried all above, but none working
Finally tried this my own
getBaseActivity().getFragmentManager()
and is working .. :)
This is sort of similar to what @icesar said.
But I was trying to post stuff to my api, located in site/api/index.php
, only posting to site/api
since it gets passed on to index.php
by itself. This however, apparently cause something to get messed up, as my $_POST
got emptied on the fly. Simply posting to site/api/index.php
directly instead solved it.
You can use:
From android doc:
String MANUFACTURER
The manufacturer of the product/hardware.
String MODEL
The end-user-visible name for the end product.
String DEVICE
The name of the industrial design.
As a example:
String deviceName = android.os.Build.MANUFACTURER + " " + android.os.Build.MODEL;
//to add to textview
TextView textView = (TextView) findViewById(R.id.text_view);
textView.setText(deviceName);
Furthermore, their is lot of attribute in Build class that you can use, like:
os.android.Build.BOARD
os.android.Build.BRAND
os.android.Build.BOOTLOADER
os.android.Build.DISPLAY
os.android.Build.CPU_ABI
os.android.Build.PRODUCT
os.android.Build.HARDWARE
os.android.Build.ID
Also their is other ways you can get device name without using Build
class(through the bluetooth).
For me, it was a CORS issue. I removed crossorigin="anonymous"
from my script importing tags, and it started working again.
BTW the latest script tags, in the correct order, can always be found here: https://getbootstrap.com/
Edit: Apparently adding defer
to the script
tag will also break all the Bootstrap goodies.
Previous answers missed this addition: a generator has a close
method, while typical iterators don’t. The close
method triggers a StopIteration
exception in the generator, which may be caught in a finally
clause in that iterator, to get a chance to run some clean-up. This abstraction makes it most usable in the large than simple iterators. One can close a generator as one could close a file, without having to bother about what’s underneath.
That said, my personal answer to the first question would be: iteratable has an __iter__
method only, typical iterators have a __next__
method only, generators has both an __iter__
and a __next__
and an additional close
.
For the second question, my personal answer would be: in a public interface, I tend to favor generators a lot, since it’s more resilient: the close
method an a greater composability with yield from
. Locally, I may use iterators, but only if it’s a flat and simple structure (iterators does not compose easily) and if there are reasons to believe the sequence is rather short especially if it may be stopped before it reach the end. I tend to look at iterators as a low level primitive, except as literals.
For control flow matters, generators are an as much important concept as promises: both are abstract and composable.
It happens cause of multiple reasons but the answer missing above there's the "className" while extending your controller.
Make sure your class name is the same as your controller name is your controllers. e.g., If your controller name is Settings.php, you must extend the controller like.
class Settings extends CI_Controller
{
// some actions like...
public function __construct(){
// and so and so...
}
}
Try to import import { CommonModule } from '@angular/common';
in angular final as *ngFor
,*ngIf
all are present in CommonModule
Start from pandas 0.13, this is the most efficient way.
df.query('Gender=="Male" & Year=="2014" ')
If you want to use something other than a shell script, try CLOC:
cloc counts blank lines, comment lines, and physical lines of source code in many programming languages. It is written entirely in Perl with no dependencies outside the standard distribution of Perl v5.6 and higher (code from some external modules is embedded within cloc) and so is quite portable.
use html link instead of asp link and you can use label in between html link for server side control
Another option I like, which can be generalized once I start seeing the code not conform to DRY, is to use one controller that redirects to another controller.
public ActionResult ClientIdSearch(int cid)
{
var action = String.Format("Details/{0}", cid);
return RedirectToAction(action, "Accounts");
}
I find this allows me to apply my logic in one location and re-use it without have to sprinkle JavaScript in the views to handle this. And, as I mentioned I can then refactor for re-use as I see this getting abused.
Either document.getElementById('i1')
, document.getElementById('i2')
, or document.getElementsByName("username")[0]
is returning no element. Check, that all elements exist.
I've done something like this:
class Cow extends React.Component {
constructor (props) {
super(props);
this.state = {text: 'hello'};
}
componentDidMount () {
if (this.props.onMounted) {
this.props.onMounted({
say: text => this.say(text)
});
}
}
render () {
return (
<pre>
___________________
< {this.state.text} >
-------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
</pre>
);
}
say (text) {
this.setState({text: text});
}
}
And then somewhere else:
class Pasture extends React.Component {
render () {
return (
<div>
<Cow onMounted={callbacks => this.cowMounted(callbacks)} />
<button onClick={() => this.changeCow()} />
</div>
);
}
cowMounted (callbacks) {
this.cowCallbacks = callbacks;
}
changeCow () {
this.cowCallbacks.say('moo');
}
}
I haven't tested this exact code, but this is along the lines of what I did in a project of mine and it works nicely :). Of course this is a bad example, you should just use props for this, but in my case the sub-component did an API call which I wanted to keep inside that component. In such a case this is a nice solution.
In Laravel 3, call path('storage')
.
In Laravel 4, use the storage_path()
helper function.
#define CTTimeStart() NSDate * __date = [NSDate date]
#define CTTimeEnd(MSG) NSLog(MSG " %g",[__date timeIntervalSinceNow]*-1)
Usage:
CTTimeStart();
...
CTTimeEnd(@"that was a long time:");
Output:
2013-08-23 15:34:39.558 App-Dev[21229:907] that was a long time: .0023
You want the (standard) POSIXt
type from base R that can be had in 'compact form' as a POSIXct
(which is essentially a double representing fractional seconds since the epoch) or as long form in POSIXlt
(which contains sub-elements). The cool thing is that arithmetic etc are defined on this -- see help(DateTimeClasses)
Quick example:
R> now <- Sys.time()
R> now
[1] "2009-12-25 18:39:11 CST"
R> as.numeric(now)
[1] 1.262e+09
R> now + 10 # adds 10 seconds
[1] "2009-12-25 18:39:21 CST"
R> as.POSIXlt(now)
[1] "2009-12-25 18:39:11 CST"
R> str(as.POSIXlt(now))
POSIXlt[1:9], format: "2009-12-25 18:39:11"
R> unclass(as.POSIXlt(now))
$sec
[1] 11.79
$min
[1] 39
$hour
[1] 18
$mday
[1] 25
$mon
[1] 11
$year
[1] 109
$wday
[1] 5
$yday
[1] 358
$isdst
[1] 0
attr(,"tzone")
[1] "America/Chicago" "CST" "CDT"
R>
As for reading them in, see help(strptime)
As for difference, easy too:
R> Jan1 <- strptime("2009-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
R> difftime(now, Jan1, unit="week")
Time difference of 51.25 weeks
R>
Lastly, the zoo package is an extremely versatile and well-documented container for matrix with associated date/time indices.
Java EE is a collection of specifications for developing and deploying enterprise applications.
In general, enterprise applications refer to software hosted on servers that provide the applications that support the enterprise.
The specifications (defined by Sun) describe services, application programming interfaces (APIs), and protocols.
The 13 core technologies that make up Java EE are:
The Java EE product provider is typically an application-server, web-server, or database-system vendor who provides classes that implement the interfaces defined in the specifications. These vendors compete on implementations of the Java EE specifications.
When a company requires Java EE experience what are they really asking for is experience using the technologies that make up Java EE. Frequently, a company will only be using a subset of the Java EE technologies.
You can do this by using the following css.
.scroll-thead{
width: 100%;
display: inline-table;
}
.scroll-tbody-y
{
display: block;
overflow-y: scroll;
}
.table-body{
height: /*fix height here*/;
}
Following is the HTML.
<table>
<thead class="scroll-thead">
<tr>
<th>Key</th>
<th>Value</th>
</tr>
</thead>
<tbody class="scroll-tbody-y table-body">
<tr>
<td>Blah</td>
<td>Blah</td>
</tr>
</tbody>
</table>
It seems to me that the chief difference between the MIT license and GPL is that the MIT doesn't require modifications be open sourced whereas the GPL does.
True - in general. You don't have to open-source your changes if you're using GPL. You could modify it and use it for your own purpose as long as you're not distributing it. BUT... if you DO distribute it, then your entire project that is using the GPL code also becomes GPL automatically. Which means, it must be open-sourced, and the recipient gets all the same rights as you - meaning, they can turn around and distribute it, modify it, sell it, etc. And that would include your proprietary code which would then no longer be proprietary - it becomes open source.
The difference with MIT is that even if you actually distribute your proprietary code that is using the MIT licensed code, you do not have to make the code open source. You can distribute it as a closed app where the code is encrypted or is a binary. Including the MIT-licensed code can be encrypted, as long as it carries the MIT license notice.
is the GPL is more restrictive than the MIT license?
Yes, very much so.
The following seemed to work well for me:
=DATEDIF(B2, Today(), "D")
A quick jump into Reflector.NET shows that the Close()
method on StreamWriter
is:
public override void Close()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
And StreamReader
is:
public override void Close()
{
this.Dispose(true);
}
The Dispose(bool disposing)
override in StreamReader
is:
protected override void Dispose(bool disposing)
{
try
{
if ((this.Closable && disposing) && (this.stream != null))
{
this.stream.Close();
}
}
finally
{
if (this.Closable && (this.stream != null))
{
this.stream = null;
/* deleted for brevity */
base.Dispose(disposing);
}
}
}
The StreamWriter
method is similar.
So, reading the code it is clear that that you can call Close()
& Dispose()
on streams as often as you like and in any order. It won't change the behaviour in any way.
So it comes down to whether or not it is more readable to use Dispose()
, Close()
and/or using ( ... ) { ... }
.
My personal preference is that using ( ... ) { ... }
should always be used when possible as it helps you to "not run with scissors".
But, while this helps correctness, it does reduce readability. In C# we already have plethora of closing curly braces so how do we know which one actually performs the close on the stream?
So I think it is best to do this:
using (var stream = ...)
{
/* code */
stream.Close();
}
It doesn't affect the behaviour of the code, but it does aid readability.
I did this in Excel 2000.
This statement should be: ms = Round(temp - Int(temp), 3) * 1000
You need to create a custom format for the result cell of [h]:mm:ss.000
Several sites provide reasonable cheat sheets or HOWTOs for tables and images. Top on my list are:
RStudio's RMarkdown, more details in basics (including tables) and a rewrite of pandoc's markdown.
Pictures are very simple to use but do not offer the ability to adjust the image to fit the page (see Update, below). To adjust the image properties (size, resolution, colors, border, etc), you'll need some form of image editor. I find I can do everything I need with one of ImageMagick, GIMP, or InkScape, all free and open source.
To add a picture, use:
![Caption for the picture.](/path/to/image.png)
I know pandoc supports PNG and JPG, which should meet most of your needs.
You do have control over image size if you are creating it in R (e.g., a plot). This can be done either directly in the command to create the image or, even better, via options if you are using knitr (highly recommended ... check out chunk options, specifically under Plots).
I strongly recommend perusing these tutorials; markdown is very handy and has many features most people don't use on a regular basis but really like once they learn it. (SO is not necessarily the best place to ask questions that are answered very directly in these tutorials.)
Some time ago, pandoc
incorporated "link_attributes" for images (apparently in 2015, with commit jgm/pandoc#244cd56). "Resizing images" can be done directly. For example:
![unchanged image](foo.jpg)
![much-smaller image](foo.jpg){#id .class width=30 height=20px}
![half-size image](foo.jpg){#id .class width=50% height=50%}
The dimensions can be provided with no units (pixels assumed), or with "px
, cm
, mm
, in
, inch
and %
" (ref: https://pandoc.org/MANUAL.html, search for link_attributes
).
(I'm not certain that CommonMark has implemented this, though there was a lengthy discussion.)
you can use the download attribute on an a tag ...
<a href="data:image/jpeg;base64,/9j/4AAQSkZ..." download="filename.jpg"></a>
see more: https://developer.mozilla.org/en/HTML/element/a#attr-download
I realize this is a later answer, but I found another reference to a way to address this issue that might help others in the future. This web page describes setting an environment variable (COMPLUS_ZapDisable=1) that prevents optimization, at least it did for me! (Don't forget the second part of disabling the Visual Studio hosting process.) In my case, this might have been even more relevant because I was debugging an external DLL thru a symbol server, but I'm not sure.