In simple words
v-model
is for two way bindings means: if you change input value, the bound data will be changed and vice versa.
but v-bind:value
is called one way binding that means: you can change input value by changing bound data but you can't change bound data by changing input value through the element.
check out this simple example: https://jsfiddle.net/gs0kphvc/
I think this is also the answer that you need. In addition, Here I add the required attributes. onChange attributes of Each input components are functions. You need to add your own logic there.
handleEmailChange: function(e) {
this.setState({email: e.target.value});
},
handlePasswordChange: function(e) {
this.setState({password: e.target.value});
},
formSubmit : async function(e) {
e.preventDefault();
// Form submit Logic
},
render : function() {
return (
<form onSubmit={(e) => this.formSubmit(e)}>
<input type="text" name="email" placeholder="Email" value={this.state.email} onChange={this.handleEmailChange} required />
<input type="password" name="password" placeholder="Password" value={this.state.password} onChange={this.handlePasswordChange} required />
<button type="button">Login</button>
</form>);
},
handleLogin: function() {
//Login Function
}
props.children
represents the content between the opening and the closing tags when invoking/rendering a component:
const Foo = props => (
<div>
<p>I'm {Foo.name}</p>
<p>abc is: {props.abc}</p>
<p>I have {props.children.length} children.</p>
<p>They are: {props.children}.</p>
<p>{Array.isArray(props.children) ? 'My kids are an array.' : ''}</p>
</div>
);
const Baz = () => <span>{Baz.name} and</span>;
const Bar = () => <span> {Bar.name}</span>;
invoke/call/render Foo
:
<Foo abc={123}>
<Baz />
<Bar />
</Foo>
I heartily recommended dbVis. The client runs on Mac, Windows and Linux and supports a variety of database servers, including PostgreSQL.
Bootstrap, as I know it, is a well defined CSS. Although using Bootstrap you could also use JavaScript, jQuery etc. But the main difference is that, using Bootstrap you can just call the class name and then you get the output on the HTML form. for eg. coloring of buttons shaping of text, using layouts. For all this you do not have to write a CSS file rather you just have to use the correct class name for shaping your HTML form.
First, write npm install --save nodemon then in package.json write the followings
"scripts": {
"server": "nodemon server.js"
},
then write
npm run server
By Using map
var values = $("input[name='pname[]']")
.map(function(){return $(this).val();}).get();
You can use .toString()
to join an array with a comma.
var array = ['a', 'b', 'c'];
array.toString(); // result: a,b,c
Or, set the separator with array.join('; '); // result: a; b; c
.
Note that dangerouslySetInnerHTML
can be dangerous if you do not know what is in the HTML string you are injecting. This is because malicious client side code can be injected via script tags.
It is probably a good idea to sanitize the HTML string via a utility such as DOMPurify if you are not 100% sure the HTML you are rendering is XSS (cross-site scripting) safe.
Example:
import DOMPurify from 'dompurify'
const thisIsMyCopy = '<p>copy copy copy <strong>strong copy</strong></p>';
render: function() {
return (
<div className="content" dangerouslySetInnerHTML={{__html: DOMPurify.sanitize(thisIsMyCopy)}}></div>
);
}
Headings are normally bold-faced; that has been turned off for this demonstration of size correspondence. MSIE and Opera interpret these sizes the same, but note that Gecko browsers and Chrome interpret Heading 6 as 11 pixels instead of 10 pixels/font size 1, and Heading 3 as 19 pixels instead of 18 pixels/font size 4 (though it's difficult to tell the difference even in a direct comparison and impossible in use). It seems Gecko also limits text to no smaller than 10 pixels.
Updated on March 21 2019
Add GuzzleHttp
package using composer require guzzlehttp/guzzle:~6.3.3
Or you can specify Guzzle as a dependency in your project's composer.json
{
"require": {
"guzzlehttp/guzzle": "~6.3.3"
}
}
Include below line in the top of the class where you are calling the API
use GuzzleHttp\Client;
Add below code for making the request
$client = new Client();
$res = $client->request('POST', 'http://www.exmple.com/mydetails', [
'form_params' => [
'name' => 'george',
]
]);
if ($res->getStatusCode() == 200) { // 200 OK
$response_data = $res->getBody()->getContents();
}
you can used this way: create extension
extension UIView {
func addTapGesture(action : @escaping ()->Void ){
let tap = MyTapGestureRecognizer(target: self , action: #selector(self.handleTap(_:)))
tap.action = action
tap.numberOfTapsRequired = 1
self.addGestureRecognizer(tap)
self.isUserInteractionEnabled = true
}
@objc func handleTap(_ sender: MyTapGestureRecognizer) {
sender.action!()
}
}
class MyTapGestureRecognizer: UITapGestureRecognizer {
var action : (()->Void)? = nil
}
and use this way:
@IBOutlet weak var testView: UIView!
testView.addTapGesture{
// ...
}
There is a blog post on MSDN about why an exponent operator does NOT exists from the C# team.
It would be possible to add a power operator to the language, but performing this operation is a fairly rare thing to do in most programs, and it doesn't seem justified to add an operator when calling Math.Pow() is simple.
You asked:
Do I have to write a loop or include another namespace to handle exponential operations? If so, how do I handle exponential operations using non-integers?
Math.Pow
supports double parameters so there is no need for you to write your own.
changing templateUrl: ''
to template: ''
fixed it
.push() will add elements to the end of an array.
Use .unshift() if need to add some element to the beginning of array i.e:
items.unshift({'id':5});
Demo:
items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];_x000D_
items.unshift({'id': 0});_x000D_
console.log(items);
_x000D_
And use .splice() in case you want to add object at a particular index i.e:
items.splice(2, 0, {'id':5});
// ^ Given object will be placed at index 2...
Demo:
items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];_x000D_
items.splice(2, 0, {'id': 2.5});_x000D_
console.log(items);
_x000D_
Keep in mind, that 'Country/Zone' is not working sometimes... This issue is not OS, MySQL version and hardware dependent - I've met it since FreeBSD 4 and Slackware Linux in year 2003 till today. MySQL from version 3 till latest source trunk. It is ODD, but it DOES happens. For example:
root@Ubuntu# ls -la /usr/share/zoneinfo/US
total 8
drwxr-xr-x 2 root root 4096 Apr 10 2013 .
drwxr-xr-x 22 root root 4096 Apr 10 2013 ..
lrwxrwxrwx 1 root root 18 Jul 8 22:33 Alaska -> ../SystemV/YST9YDT
lrwxrwxrwx 1 root root 21 Jul 8 22:33 Aleutian -> ../posix/America/Adak
lrwxrwxrwx 1 root root 15 Jul 8 22:33 Arizona -> ../SystemV/MST7
lrwxrwxrwx 1 root root 18 Jul 8 22:33 Central -> ../SystemV/CST6CDT
lrwxrwxrwx 1 root root 18 Jul 8 22:33 Eastern -> ../SystemV/EST5EDT
lrwxrwxrwx 1 root root 37 Jul 8 22:33 East-Indiana -> ../posix/America/Indiana/Indianapolis
lrwxrwxrwx 1 root root 19 Jul 8 22:33 Hawaii -> ../Pacific/Honolulu
lrwxrwxrwx 1 root root 24 Jul 8 22:33 Indiana-Starke -> ../posix/America/Knox_IN
lrwxrwxrwx 1 root root 24 Jul 8 22:33 Michigan -> ../posix/America/Detroit
lrwxrwxrwx 1 root root 18 Jul 8 22:33 Mountain -> ../SystemV/MST7MDT
lrwxrwxrwx 1 root root 18 Jul 8 22:33 Pacific -> ../SystemV/PST8PDT
lrwxrwxrwx 1 root root 18 Jul 8 22:33 Pacific-New -> ../SystemV/PST8PDT
lrwxrwxrwx 1 root root 20 Jul 8 22:33 Samoa -> ../Pacific/Pago_Pago
root@Ubuntu#
And a statement like that is supposed to work:
SET time_zone='US/Eastern';
But you have this problem:
Error Code: 1298. Unknown or incorrect time zone: 'EUS/Eastern'
Take a look at the subfolder in your zone information directory, and see the ACTUAL filename for symlink, in this case it's EST5EDT. Then try this statement instead:
SET time_zone='EST5EDT';
And it's actually working as it is supposed to! :) Keep this trick in mind; I haven't seen it to be documented in MySQL manuals and official documentation. But reading the corresponding documentation is must-do thing: MySQL 5.5 timezone official documentation - and don't forget to load timezone data into your server just like that (run as root user!):
mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root mysql
Trick number one - it must be done exactly under MySQL root user. It can fail or produce non-working result even from the user that has full access to a MySQL database - I saw the glitch myself.
This is based off of "default locale"'s answer but it will remove invalid column names prior to setting ordinal. This is because if you accidentally send an invalid column name then it would fail and if you put a check to prevent it from failing then the index would be wrong since it would skip indices wherever an invalid column name was passed in.
public static class DataTableExtensions
{
/// <summary>
/// SetOrdinal of DataTable columns based on the index of the columnNames array. Removes invalid column names first.
/// </summary>
/// <param name="table"></param>
/// <param name="columnNames"></param>
/// <remarks> http://stackoverflow.com/questions/3757997/how-to-change-datatable-colums-order</remarks>
public static void SetColumnsOrder(this DataTable dtbl, params String[] columnNames)
{
List<string> listColNames = columnNames.ToList();
//Remove invalid column names.
foreach (string colName in columnNames)
{
if (!dtbl.Columns.Contains(colName))
{
listColNames.Remove(colName);
}
}
foreach (string colName in listColNames)
{
dtbl.Columns[colName].SetOrdinal(listColNames.IndexOf(colName));
}
}
If you decide to use Underscore.js you better do
var obj = {
key1: 'value1',
key2: 'value2',
key3: 'value3',
key4: 'value4'
}
var keys = [];
_.each( obj, function( val, key ) {
keys.push(key);
});
console.log(keys.lenth, keys);
The accepted answer is not complete without the remainder of instructions (paraphrased below) from the forum thread linked to:
cd /etc/php5/conf.d
cat > sqlite3.ini
# configuration for php SQLite3 module
extension=sqlite3.so
^D
sudo /etc/init.d/apache2 restart
I ran into the same issue. I was able to get my results to a CSV using the following solution:
This video does an excellent job of showing you how to set breakpoints and watch variables in the Eclipse Debugger. http://youtu.be/9gAjIQc4bPU
Deparse tells us this is what is being executed:
$find = 'start (.*) end';
$replace = "foo \cA bar";
$var = 'start middle end';
$var =~ s/$find/$replace/;
However,
/$find/foo \1 bar/
Is interpreted as :
$var =~ s/$find/foo $1 bar/;
Unfortunately it appears there is no easy way to do this.
You can do it with a string eval, but thats dangerous.
The most sane solution that works for me was this:
$find = "start (.*) end";
$replace = 'foo \1 bar';
$var = "start middle end";
sub repl {
my $find = shift;
my $replace = shift;
my $var = shift;
# Capture first
my @items = ( $var =~ $find );
$var =~ s/$find/$replace/;
for( reverse 0 .. $#items ){
my $n = $_ + 1;
# Many More Rules can go here, ie: \g matchers and \{ }
$var =~ s/\\$n/${items[$_]}/g ;
$var =~ s/\$$n/${items[$_]}/g ;
}
return $var;
}
print repl $find, $replace, $var;
As I said in my answer, I avoid evals for a reason.
$find="start (.*) end";
$replace='do{ print "I am a dirty little hacker" while 1; "foo $1 bar" }';
$var = "start middle end";
$var =~ s/$find/$replace/ee;
print "var: $var\n";
this code does exactly what you think it does.
If your substitution string is in a web application, you just opened the door to arbitrary code execution.
Good Job.
Also, it WON'T work with taints turned on for this very reason.
$find="start (.*) end";
$replace='"' . $ARGV[0] . '"';
$var = "start middle end";
$var =~ s/$find/$replace/ee;
print "var: $var\n"
$ perl /tmp/re.pl 'foo $1 bar'
var: foo middle bar
$ perl -T /tmp/re.pl 'foo $1 bar'
Insecure dependency in eval while running with -T switch at /tmp/re.pl line 10.
However, the more careful technique is sane, safe, secure, and doesn't fail taint. ( Be assured tho, the string it emits is still tainted, so you don't lose any security. )
Definition:
JOINS are way to query the data that combined together from multiple tables simultaneously.
Concern to RDBMS there are 5-types of joins:
Equi-Join: Combines common records from two tables based on equality condition. Technically, Join made by using equality-operator (=) to compare values of Primary Key of one table and Foreign Key values of another table, hence result set includes common(matched) records from both tables. For implementation see INNER-JOIN.
Natural-Join: It is enhanced version of Equi-Join, in which SELECT operation omits duplicate column. For implementation see INNER-JOIN
Non-Equi-Join: It is reverse of Equi-join where joining condition is uses other than equal operator(=) e.g, !=, <=, >=, >, < or BETWEEN etc. For implementation see INNER-JOIN.
Self-Join:: A customized behavior of join where a table combined with itself; This is typically needed for querying self-referencing tables (or Unary relationship entity). For implementation see INNER-JOINs.
Cartesian Product: It cross combines all records of both tables without any condition. Technically, it returns the result set of a query without WHERE-Clause.
As per SQL concern and advancement, there are 3-types of joins and all RDBMS joins can be achieved using these types of joins.
INNER-JOIN: It merges(or combines) matched rows from two tables. The matching is done based on common columns of tables and their comparing operation. If equality based condition then: EQUI-JOIN performed, otherwise Non-EQUI-Join.
OUTER-JOIN: It merges(or combines) matched rows from two tables and unmatched rows with NULL values. However, can customized selection of un-matched rows e.g, selecting unmatched row from first table or second table by sub-types: LEFT OUTER JOIN and RIGHT OUTER JOIN.
2.1. LEFT Outer JOIN (a.k.a, LEFT-JOIN): Returns matched rows from two tables and unmatched from the LEFT table(i.e, first table) only.
2.2. RIGHT Outer JOIN (a.k.a, RIGHT-JOIN): Returns matched rows from two tables and unmatched from the RIGHT table only.
2.3. FULL OUTER JOIN (a.k.a OUTER JOIN): Returns matched and unmatched from both tables.
CROSS-JOIN: This join does not merges/combines instead it performs Cartesian product.
Note: Self-JOIN can be achieved by either INNER-JOIN, OUTER-JOIN and CROSS-JOIN based on requirement but the table must join with itself.
1.1: INNER-JOIN: Equi-join implementation
SELECT *
FROM Table1 A
INNER JOIN Table2 B ON A.<Primary-Key> =B.<Foreign-Key>;
1.2: INNER-JOIN: Natural-JOIN implementation
Select A.*, B.Col1, B.Col2 --But no B.ForeignKeyColumn in Select
FROM Table1 A
INNER JOIN Table2 B On A.Pk = B.Fk;
1.3: INNER-JOIN with NON-Equi-join implementation
Select *
FROM Table1 A INNER JOIN Table2 B On A.Pk <= B.Fk;
1.4: INNER-JOIN with SELF-JOIN
Select *
FROM Table1 A1 INNER JOIN Table1 A2 On A1.Pk = A2.Fk;
2.1: OUTER JOIN (full outer join)
Select *
FROM Table1 A FULL OUTER JOIN Table2 B On A.Pk = B.Fk;
2.2: LEFT JOIN
Select *
FROM Table1 A LEFT OUTER JOIN Table2 B On A.Pk = B.Fk;
2.3: RIGHT JOIN
Select *
FROM Table1 A RIGHT OUTER JOIN Table2 B On A.Pk = B.Fk;
3.1: CROSS JOIN
Select *
FROM TableA CROSS JOIN TableB;
3.2: CROSS JOIN-Self JOIN
Select *
FROM Table1 A1 CROSS JOIN Table1 A2;
//OR//
Select *
FROM Table1 A1,Table1 A2;
faster way (without pyspark.sql.functions
)
df.filter((df.d<5)&((df.col1 != df.col3) |
(df.col2 != df.col4) &
(df.col1 ==df.col3)))\
.show()
// Step 1 :- Register NotificationCenter
ViewDidLoad() {
self.yourtextfield.becomefirstresponder()
// Register your Notification, To know When Key Board Appears.
NotificationCenter.default.addObserver(self, selector: #selector(SelectVendorViewController.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
// Register your Notification, To know When Key Board Hides.
NotificationCenter.default.addObserver(self, selector: #selector(SelectVendorViewController.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
// Step 2 :- These Methods will be called Automatically when Keyboard appears Or Hides
func keyboardWillShow(notification:NSNotification) {
let userInfo:NSDictionary = notification.userInfo! as NSDictionary
let keyboardFrame:NSValue = userInfo.value(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
tblViewListData.frame.size.height = fltTblHeight-keyboardHeight
}
func keyboardWillHide(notification:NSNotification) {
tblViewListData.frame.size.height = fltTblHeight
}
You could use limitTo
filter with -1
for find the last element
Example :
<div ng-repeat="friend in friends | limitTo: -1">
{{friend.name}}
</div>
In droupDown list there are two item add property.
1) Text 2) value
If you want to get text property then u use selecteditem.text
and If you want to select value property then use selectedvalue property
In your case i thing both value and text property are the same so no matter if u use selectedvalue or selecteditem.text
If both are different then they give us different results
There is a limit, yes. See ulimit
.
Also you need to consider the TIMED_WAIT
state. Once a TCP socket is closed (by default) the port remains occupied in TIMED_WAIT
status for 2 minutes. This value is tunable. This will also "run you out of sockets" even though they are closed.
Run netstat
to see the TIMED_WAIT
stuff in action.
P.S. The reason for TIMED_WAIT
is to handle the case of packets arriving after the socket is closed. This can happen because packets are delayed or the other side just doesn't know that the socket has been closed yet. This allows the OS to silently drop those packets without a chance of "infecting" a different, unrelated socket connection.
Full Working HTML Code. Cut+Paste into new .HTML file:
Contains Two Examples:
Tested In:
<!DOCTYPE HTML >
<html lang="en">
<head>
<meta charset="UTF-8">
<title> #SAVE_CANVAS_TEST# </title>
<meta
name ="author"
content="John Mark Isaac Madison"
>
<!-- EMAIL: J4M4I5M7 -[AT]- Hotmail.com -->
</head>
<body>
<div id="about_the_code">
Illustrates:
<ol>
<li>How to save a canvas from HTML page. </li>
<li>How to save a dynamically created canvas.</li>
</ol>
</div>
<canvas id="DOM_CANVAS"
width ="300"
height="300"
></canvas>
<div id="controls">
<button type="button" style="width:300px;"
onclick="obj.SAVE_CANVAS()">
SAVE_CANVAS ( Dynamically Made Canvas )
</button>
<button type="button" style="width:300px;"
onclick="obj.SAVE_CANVAS('DOM_CANVAS')">
SAVE_CANVAS ( Canvas In HTML Code )
</button>
</div>
<script>
var obj = new MyTestCodeClass();
function MyTestCodeClass(){
//Publically exposed functions:
this.SAVE_CANVAS = SAVE_CANVAS;
//:Private:
var _canvas;
var _canvas_id = "ID_OF_DYNAMIC_CANVAS";
var _name_hash_counter = 0;
//:Create Canvas:
(function _constructor(){
var D = document;
var CE = D.createElement.bind(D);
_canvas = CE("canvas");
_canvas.width = 300;
_canvas.height= 300;
_canvas.id = _canvas_id;
})();
//:Before saving the canvas, fill it so
//:we can see it. For demonstration of code.
function _fillCanvas(input_canvas, r,g,b){
var ctx = input_canvas.getContext("2d");
var c = input_canvas;
ctx.fillStyle = "rgb("+r+","+g+","+b+")";
ctx.fillRect(0, 0, c.width, c.height);
}
//:Saves canvas. If optional_id supplied,
//:will save canvas off the DOM. If not,
//:will save the dynamically created canvas.
function SAVE_CANVAS(optional_id){
var c = _getCanvas( optional_id );
//:Debug Code: Color canvas from DOM
//:green, internal canvas red.
if( optional_id ){
_fillCanvas(c,0,255,0);
}else{
_fillCanvas(c,255,0,0);
}
_saveCanvas( c );
}
//:If optional_id supplied, get canvas
//:from DOM. Else, get internal dynamically
//:created canvas.
function _getCanvas( optional_id ){
var c = null; //:canvas.
if( typeof optional_id == "string"){
var id = optional_id;
var d = document;
var c = d.getElementById( id );
}else{
c = _canvas;
}
return c;
}
function _saveCanvas( canvas ){
if(!window){ alert("[WINDOW_IS_NULL]"); }
//:We want to give the window a unique
//:name so that we can save multiple times
//:without having to close previous
//:windows.
_name_hash_counter++ ;
var NHC = _name_hash_counter ;
var URL = 'about:blank' ;
var name= 'UNIQUE_WINDOW_ID' + NHC;
var w=window.open( URL, name ) ;
if(!w){ alert("[W_IS_NULL]");}
//:Create the page contents,
//:THEN set the tile. Order Matters.
var DW = "" ;
DW += "<img src='" ;
DW += canvas.toDataURL("image/png");
DW += "' alt='from canvas'/>" ;
w.document.write(DW) ;
w.document.title = "NHC"+NHC ;
}
}//:end class
</script>
</body>
<!-- In IE: Script cannot be outside of body. -->
</html>
Simplest solution in Swift 3.0 & Swift 4.0 & Swift 5.0
func delayWithSeconds(_ seconds: Double, completion: @escaping () -> ()) {
DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
completion()
}
}
Usage
delayWithSeconds(1) {
//Do something
}
The Reason for Warning is your using Old ADT (Android development tools), so Update your ADT by following the procedures below
Procedure 1:
Procedure 2:
Click Help > Install New Software. In the Work with field, enter: https://dl-ssl.google.com/android/eclipse/ Select Developer Tools / Android Development Tools. Click Next and complete the wizard.
For a portable (ISO C90) implementation, you could use double parentheses, like this;
#include <stdio.h>
#include <stdarg.h>
#ifndef NDEBUG
# define debug_print(msg) stderr_printf msg
#else
# define debug_print(msg) (void)0
#endif
void
stderr_printf(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
}
int
main(int argc, char *argv[])
{
debug_print(("argv[0] is %s, argc is %d\n", argv[0], argc));
return 0;
}
or (hackish, wouldn't recommend it)
#include <stdio.h>
#define _ ,
#ifndef NDEBUG
# define debug_print(msg) fprintf(stderr, msg)
#else
# define debug_print(msg) (void)0
#endif
int
main(int argc, char *argv[])
{
debug_print("argv[0] is %s, argc is %d"_ argv[0] _ argc);
return 0;
}
Found it:
~/Library/Application Support/iPhone Simulator/User/
Oh must add my own pick here, you will use this when you encode/decode some string obj you transfer between two programs.
Lets say you use base64encode some array in python, and then you want to decode that into c++. Once you have the string you decode from base64decode in c++. In order to get it back to array of float, all you need to do here is
float arr[1024];
memcpy(arr, ur_string.c_str(), sizeof(float) * 1024);
This is pretty common use I suppose.
u can use this:
protected void btnConfirm_Click(object sender, EventArgs e)
{
Response.Redirect("Confirm.aspx");
}
Based on Aladin Q's solution, here is a helper function that I wrote, that will change the image in an imageview while running a little fade out / fade in animation:
public static void ImageViewAnimatedChange(Context c, final ImageView v, final Bitmap new_image) {
final Animation anim_out = AnimationUtils.loadAnimation(c, android.R.anim.fade_out);
final Animation anim_in = AnimationUtils.loadAnimation(c, android.R.anim.fade_in);
anim_out.setAnimationListener(new AnimationListener()
{
@Override public void onAnimationStart(Animation animation) {}
@Override public void onAnimationRepeat(Animation animation) {}
@Override public void onAnimationEnd(Animation animation)
{
v.setImageBitmap(new_image);
anim_in.setAnimationListener(new AnimationListener() {
@Override public void onAnimationStart(Animation animation) {}
@Override public void onAnimationRepeat(Animation animation) {}
@Override public void onAnimationEnd(Animation animation) {}
});
v.startAnimation(anim_in);
}
});
v.startAnimation(anim_out);
}
If you are starting with something that has a .Length
or .Count
(such as ICollection<T>
, IList<T>
, List<T>
, etc) - then this will be the fastest option, since it doesn't need to go through the GetEnumerator()
/MoveNext()
/Dispose()
sequence required by Any()
to check for a non-empty IEnumerable<T>
sequence.
For just IEnumerable<T>
, then Any()
will generally be quicker, as it only has to look at one iteration. However, note that the LINQ-to-Objects implementation of Count()
does check for ICollection<T>
(using .Count
as an optimisation) - so if your underlying data-source is directly a list/collection, there won't be a huge difference. Don't ask me why it doesn't use the non-generic ICollection
...
Of course, if you have used LINQ to filter it etc (Where
etc), you will have an iterator-block based sequence, and so this ICollection<T>
optimisation is useless.
In general with IEnumerable<T>
: stick with Any()
;-p
Yes, the moment jQuery sees the URL belongs to a different domain, it assumes that call as a cross domain call, thus crossdomain:true
is not required here.
Also, important to note that you cannot make a synchronous call with $.ajax
if your URL belongs to a different domain (cross domain) or you are using JSONP. Only async calls are allowed.
Note: you can call the service synchronously if you specify the async:false
with your request.
Just use GETDATE()
or GETUTCDATE()
(if you want to get the "universal" UTC time, instead of your local server's time-zone related time).
INSERT INTO [Business]
([IsDeleted]
,[FirstName]
,[LastName]
,[LastUpdated]
,[LastUpdatedBy])
VALUES
(0, 'Joe', 'Thomas',
GETDATE(), <LastUpdatedBy, nvarchar(50),>)
If you don't prefer the sticky bottom effect i would put it in viewDidLoad()
https://stackoverflow.com/a/38176479/4127670
Edited: Just realized that I should specify that this works only if both of them exists. Otherwise the string is not considered quoted. Such scenario appeared for me when working with CSV files.
org.apache.commons.lang3.StringUtils.unwrap("\"abc\"", "\"") = "abc"
org.apache.commons.lang3.StringUtils.unwrap("\"abc", "\"") = "\"abc"
org.apache.commons.lang3.StringUtils.unwrap("abc\"", "\"") = "abc\""
It does work by just taking the argument 'rb' read binary instead of 'r' read
If you have multiple recurrences from a single string and you have different [start] and [\end] pattern. Here's a function which output an array.
function get_string_between($string, $start, $end){
$split_string = explode($end,$string);
foreach($split_string as $data) {
$str_pos = strpos($data,$start);
$last_pos = strlen($data);
$capture_len = $last_pos - $str_pos;
$return[] = substr($data,$str_pos+1,$capture_len);
}
return $return;
}
<input type="file" id="picfile" name="picf" />
<input type="text" id="txtName" style="width: 144px;" />
$("#btncatsave").click(function () {
var Name = $("#txtName").val();
var formData = new FormData();
var totalFiles = document.getElementById("picfile").files.length;
var file = document.getElementById("picfile").files[0];
formData.append("FileUpload", file);
formData.append("Name", Name);
$.ajax({
type: "POST",
url: '/Category_Subcategory/Save_Category',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (msg) {
alert(msg);
},
error: function (error) {
alert("errror");
}
});
});
[HttpPost]
public ActionResult Save_Category()
{
string Name=Request.Form[1];
if (Request.Files.Count > 0)
{
HttpPostedFileBase file = Request.Files[0];
}
}
You can also use git diff HEAD file
to show the diff for a specific file.
See the EXAMPLE
section under git-diff(1)
CURLOPT_POSTFIELDS
as the name suggests, is for the body (payload) of a POST
request. For GET
requests, the payload is part of the URL in the form of a query string.
In your case, you need to construct the URL with the arguments you need to send (if any), and remove the other options to cURL.
curl_setopt($ch, CURLOPT_URL, $this->service_url.'user/'.$id_user);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
//$body = '{}';
//curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
//curl_setopt($ch, CURLOPT_POSTFIELDS,$body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
An easy way to pull of the p-values is to use statsmodels regression:
import statsmodels.api as sm
mod = sm.OLS(Y,X)
fii = mod.fit()
p_values = fii.summary2().tables[1]['P>|t|']
You get a series of p-values that you can manipulate (for example choose the order you want to keep by evaluating each p-value):
I have a simpler solution. In your destination page (irc_online.php) add an auto-refresh tag in the header.
I had the same issue in Vagrant.
I have used sudo to run the command to install.
sudo npm install -g grunt-cli
It worked for me.
I'm afraid that most voted solution (https://stackoverflow.com/a/19271434/3283279) is not working properly. The fourth test case (var_dump(validateDate('2012-2-25')); // false) is wrong. The date is correct, because it corresponds to the format - the m allows a month with or without leading zero (see: http://php.net/manual/en/datetime.createfromformat.php). Therefore a date 2012-2-25 is in format Y-m-d and the test case must be true not false.
I believe that better solution is to test possible error as follows:
function validateDate($date, $format = 'Y-m-d') {
DateTime::createFromFormat($format, $date);
$errors = DateTime::getLastErrors();
return $errors['warning_count'] === 0 && $errors['error_count'] === 0;
}
Change name
attribute in pubspec.yaml
(line 1)
For the name of apk, change android:label
in AndroidManifest.xml
If you don't mind using 3rd party libraries, AOL's cyclops-react lib (disclosure I am a contributor) has extensions for all JDK Collection types, including List. The ListX interface extends java.util.List and adds a large number of useful operators, including filter.
You can simply write-
ListX<Long> sourceLongList = ListX.of(1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L);
ListX<Long> targetLongList = sourceLongList.filter(l -> l > 100);
ListX also can be created from an existing List (via ListX.fromIterable)
Another alternative, if you already have an instance of the object created and you want to add it as an @autowired dependency to initialize all the internal @autowired variables, could be the following:
@Autowired
private AutowireCapableBeanFactory autowireCapableBeanFactory;
public void doStuff() {
YourObject obj = new YourObject("Value X", "etc");
autowireCapableBeanFactory.autowireBean(obj);
}
You can also use Rsync
and find
. For find
:
find $FOLDER -type f | cut -d/ -f2- | sort > /tmp/file_list_$FOLDER
But files with the same names and in the same subfolders, but with different content, will not be shown in the lists.
If you are a fan of GUI, you may check Meld that @Alexander mentioned. It works fine in both windows and linux.
// This file is PHP.
<html>
<?php
if ($_POST['submit']) {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$confirmpassword = $_POST['confirmpassword'];
$strtadd1 = $_POST['strtadd1'];
$strtadd2 = $_POST['strtadd2'];
$city = $_POST['city'];
$country = $_POST['country'];
$success = '';
// Upon Success.
if ($firstname != '' && $lastname != '' && $email != '' && $password != '' && $confirmpassword != '' && $strtadd1 != '' && $strtadd2 != '' && $city != '' && $country != '') {
// Change $success variable from an empty string.
$success = 'success';
// Insert whatever you want to do upon success.
} else {
// Upon Failure.
echo '<p class="error">Fill in all fields.</p>';
// Set $success variable to an empty string.
$success = '';
}
}
?>
<form method="POST" action="#">
<label class="w">Plan :</label>
<select autofocus="" name="plan" required="required">
<option value="">Select One</option>
<option value="FREE Account">FREE Account</option>
<option value="Premium Account Monthly">Premium Account Monthly</option>
<option value="Premium Account Yearly">Premium Account Yearly</option>
</select>
<br>
<label class="w">First Name :</label><input name="firstname" type="text" placeholder="First Name" required="required" value="<?php if (isset($firstname) && $success == '') {echo $firstname;} ?>"><br>
<label class="w">Last Name :</label><input name="lastname" type="text" placeholder="Last Name" required="required" value="<?php if (isset($lastname) && $success == '') {echo $lastname;} ?>"><br>
<label class="w">E-mail ID :</label><input name="email" type="email" placeholder="Enter Email" required="required" value="<?php if (isset($email) && $success == '') {echo $email;} ?>"><br>
<label class="w">Password :</label><input name="password" type="password" placeholder="********" required="required" value="<?php if (isset($password) && $success == '') {echo $password;} ?>"><br>
<label class="w">Re-Enter Password :</label><input name="confirmpassword" type="password" placeholder="********" required="required" value="<?php if (isset($confirmpassword) && $success == '') {echo $confirmpassword;} ?>"><br>
<label class="w">Street Address 1 :</label><input name="strtadd1" type="text" placeholder="street address first" required="required" value="<?php if (isset($strtadd1) && $success == '') {echo $strtadd1;} ?>"><br>
<label class="w">Street Address 2 :</label><input name="strtadd2" type="text" placeholder="street address second" value="<?php if (isset($strtadd2) && $success == '') {echo $strtadd2;} ?>"><br>
<label class="w">City :</label><input name="city" type="text" placeholder="City" required="required" value="<?php if (isset($city) && $success == '') {echo $city;} ?>"><br>
<label class="w">Country :</label><select autofocus="" id="a1_txtBox1" name="country" required="required" placeholder="select one" value="<?php if (isset($country) && $success == '') {echo $country;} ?>">
<input type="submit" name="submit">
</form>
</html>
Use value="<?php if (isset($firstname) && $success == '') {echo $firstname;} ?>"
You'll then have to create the $success variable--as I did in my example.
Sure, that is why python implements the following methods where the first parameter is a function:
//add cookie
var panelIdCookie = new HttpCookie("panelIdCookie");
panelIdCookie.Values.Add("panelId", panelId.ToString(CultureInfo.InvariantCulture));
panelIdCookie.Expires = DateTime.Now.AddMonths(2);
Response.Cookies.Add(panelIdCookie);
//read cookie
var httpCookie = Request.Cookies["panelIdCookie"];
if (httpCookie != null)
{
panelId = Convert.ToInt32(httpCookie["panelId"]);
}
I got blur working with SVG blur filter:
CSS
-webkit-filter: url(#svg-blur);
filter: url(#svg-blur);
SVG
<svg id="svg-filter">
<filter id="svg-blur">
<feGaussianBlur in="SourceGraphic" stdDeviation="4"></feGaussianBlur>
</filter>
</svg>
Working example:
https://jsfiddle.net/1k5x6dgm/
Please note - this will not work in IE versions
You don't need to change the delimiter to display the right part of the string with cut
.
The -f
switch of the cut
command is the n-TH element separated by your delimiter : :
, so you can just type :
grep puddle2_1557936 | cut -d ":" -f2
Another solutions (adapt it a bit) if you want fun :
Using grep :
grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or still with look around regex
grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with perl :
perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or using ruby (thanks to glenn jackman)
ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with awk :
awk -F'puddle2_1557936:' '{print $2}' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with python :
python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or using only bash :
IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2
js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2
php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
As noted in the release email, linked to from the release tweet and noted in large orange warning that appears on the front page of the documentation, and less orange, but still present, in the readme on the repository and the release on pypi:
xlrd has explicitly removed support for anything other than xls files.
In your case, the solution is to:
openpyxl
: https://openpyxl.readthedocs.io/en/stable/df1 = pd.read_excel(
os.path.join(APP_PATH, "Data", "aug_latest.xlsm"),
engine='openpyxl',
)
I had a similar problem, I solved it by explicitly adding the file's directory to the path list:
import os
import sys
file_dir = os.path.dirname(__file__)
sys.path.append(file_dir)
After that, I had no problem importing from the same directory.
There is a useful difference between call
and start /wait
when calling regsvr32.exe /s
for example, also referenced by Gary in
in his answer to how-do-i-get-the-application-exit-code-from-a-windows-command-line
call regsvr32.exe /s broken.dll
echo %errorlevel%
will always return 0 but
start /wait regsvr32.exe /s broken.dll
echo %errorlevel%
will return the error level from regsvr32.exe
Check this: https://github.com/angular/material2/issues/5808
Since material2 is using flex layout, you can just set fxFlex="40"
(or the value you want for fxFlex) to md-cell
and md-header-cell
.
iframe is also vulnerable to Cross Frame Scripting:
You can try the c++ open source project WinRobot @git, a powerful screen capturer
CComPtr<IWinRobotService> pService;
hr = pService.CoCreateInstance(__uuidof(ServiceHost) );
//get active console session
CComPtr<IUnknown> pUnk;
hr = pService->GetActiveConsoleSession(&pUnk);
CComQIPtr<IWinRobotSession> pSession = pUnk;
// capture screen
pUnk = 0;
hr = pSession->CreateScreenCapture(0,0,1280,800,&pUnk);
// get screen image data(with file mapping)
CComQIPtr<IScreenBufferStream> pBuffer = pUnk;
Support :
I too got the same error am using xcode version 4.0.2 so what i did was selected the xcode project file and from their i selected the Target option their i could see the app of my project so i clicked on it and went to the build settings option.
Their in the search option i typed Framework search path, and deleted all the settings and then clicked the build button and that worked for me just fine,
Thanks and Regards
document.form.p_id.length
... not count().
You really should give your form an id
<form id="myform">
Then refer to it using:
var theForm = document.getElementById("myform");
Then refer to the elements like:
for(var i = 0; i < theForm.p_id.length; i++){
if (rs == null || !rs.first()) { //empty } else { //not empty }
Note that after this method call, if the resultset is not empty, it is at the beginning.
When you call test
with &nKByte
, the address-of operator creates a temporary value, and you can't normally have references to temporary values because they are, well, temporary.
Either do not use a reference for the argument, or better yet don't use a pointer.
To detach from the container you simply hold Ctrl and press P + Q.
To attach to a running container you use:
$ docker container attach "container_name"
Updated this answer with recent information (from CSS Tricks). Kudos to Matt and Douglas for pointing out the filter implementation.
.rotate {
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
-ms-transform: rotate(-90deg);
-o-transform: rotate(-90deg);
transform: rotate(-90deg);
/* also accepts left, right, top, bottom coordinates; not required, but a good idea for styling */
-webkit-transform-origin: 50% 50%;
-moz-transform-origin: 50% 50%;
-ms-transform-origin: 50% 50%;
-o-transform-origin: 50% 50%;
transform-origin: 50% 50%;
/* Should be unset in IE9+ I think. */
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
}
Old answer:
For FF 3.5 or Safari/Webkit 3.1, check out: -moz-transform (and -webkit-transform). IE has a Matrix filter(v5.5+), but I'm not certain how to use it. Opera has no transformation capabilities yet.
.rot-neg-90 {
/* rotate -90 deg, not sure if a negative number is supported so I used 270 */
-moz-transform: rotate(270deg);
-moz-transform-origin: 50% 50%;
-webkit-transform: rotate(270deg);
-webkit-transform-origin: 50% 50%;
/* IE support too convoluted for the time I've got on my hands... */
}
Another all-too-common reason for this problem is if you attempt to load a directory on a drive that is no longer connected. For example, Say you program in C:\Code\Java, but occasionally work off of a flash drive, H:\Code\Java. If you do not have the drive connected it can be easy to believe you are trying to load a valid directory without noticing your typo.
If you have jQuery enabled you can use an escapeXml function and not have to worry about escaping arrows or special characters.
<pre>
${fn:escapeXml('
<!-- all your code -->
')};
</pre>
When you say pair[0]
, that gives you ("a", 1)
. The thing in parentheses is a tuple, which, like a list, is a type of collection. So you can access the first element of that thing by specifying [0]
or [1]
after its name. So all you have to do to get the first element of the first element of pair
is say pair[0][0]
. Or if you want the second element of the third element, it's pair[2][1]
.
fun rotateArrow(view: View): Boolean {
return if (view.rotation == 0F) {
view.animate().setDuration(200).rotation(180F)
true
} else {
view.animate().setDuration(200).rotation(0F)
false
}
}
Use WSDL.EXE utility to generate a Web Service proxy from WSDL.
You'll get a long C# source file that contains a class that looks like this:
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="MyService", Namespace="http://myservice.com/myservice")]
public partial class MyService : System.Web.Services.Protocols.SoapHttpClientProtocol {
...
}
In your client-side, Web-service-consuming code:
When using mongoose .
A representation of the _id is usually in the form (recieved client side)
{ _id:
{ _bsontype: 'ObjectID',
id: <Buffer 5a f1 8f 4b c7 17 0e 76 9a c0 97 aa> },
As you can see there's a buffer in there. The easiest way to convert it is just doing <obj>.toString()
or String(<obj>._id)
So for example
var mongoose = require('mongoose')
mongoose.connect("http://localhost/test")
var personSchema = new mongoose.Schema({ name: String })
var Person = mongoose.model("Person", personSchema)
var guy = new Person({ name: "someguy" })
Person.find().then((people) =>{
people.forEach(person => {
console.log(typeof person._id) //outputs object
typeof person._id == 'string'
? null
: sale._id = String(sale._id) // all _id s will be converted to strings
})
}).catch(err=>{ console.log("errored") })
To switch to other branch without committing the changes when git stash doesn't work. You can use the below command:
git checkout -f branch-name
Here is another approach.
class orbisius_custom_string {
/**
* The reverse of nl2br. Handles <br/> <br/> <br />
* usage: orbisius_custom_string::br2nl('Your buffer goes here ...');
* @param str $buff
* @return str
* @author Slavi Marinov | http://orbisius.com
*/
public static function br2nl($buff = '') {
$buff = preg_replace('#<br[/\s]*>#si', "\n", $buff);
$buff = trim($buff);
return $buff;
}
}
This question have been resolved and also got a lot of responses, but i want to add something to it. I was trying to figure out, why my click element his firing 77 times, and not one time.
in my code, i had an each, running a json response and displaying it as divs with buttons. And then i declared the click event inside the each.
$(data).each(function(){
button = $('<button>');
button.addClass('test-button');
button.appendTo("body");
$('.test-button').click(function(){
console.log('i was clicked');
})
})
If you write your your code like this, the class .test-button will get multiple click events. For example, my data has 77 lines, so the each will run 77 times, that means i will decline the click event on the class 77 times. When you click the element, it will be fired 77 times.
But if you wirte it like this:
$(data).each(function(){
button = $('<button>');
button.addClass('test-button');
button.appendTo("body");
})
$('.test-button').click(function(){
console.log('i was clicked');
})
you are declaring the click element after the each. That means, the each will run its 77 times, and the click element will be declared only one time. So, if you click the element, it will be fired only one time.
psql -U username -d mydatabase -c 'SELECT * FROM mytable'
If you're new to postgresql and unfamiliar with using the command line tool psql
then there is some confusing behaviour you should be aware of when you've entered an interactive session.
For example, initiate an interactive session:
psql -U username mydatabase
mydatabase=#
At this point you can enter a query directly but you must remember to terminate the query with a semicolon ;
For example:
mydatabase=# SELECT * FROM mytable;
If you forget the semicolon then when you hit enter you will get nothing on your return line because psql
will be assuming that you have not finished entering your query. This can lead to all kinds of confusion. For example, if you re-enter the same query you will have most likely create a syntax error.
As an experiment, try typing any garble you want at the psql prompt then hit enter. psql
will silently provide you with a new line. If you enter a semicolon on that new line and then hit enter, then you will receive the ERROR:
mydatabase=# asdfs
mydatabase=# ;
ERROR: syntax error at or near "asdfs"
LINE 1: asdfs
^
The rule of thumb is:
If you received no response from psql
but you were expecting at least SOMETHING, then you forgot the semicolon ;
I suppose that 255 in 227./255 is perceived as an integer and divide is always return 0
You could do this but it is hacky
.application-title {
background:url("/path/to/image.png");
/* set these dims according to your image size */
width:500px;
height:500px;
}
.application-title img {
display:none;
}
Here is a working example:
I don't know how to programmatically solve this, but the first thing people do is that we sample the algorithm for certain patterns in the number of operations done, say 4n^2 + 2n + 1 we have 2 rules:
If we simplify f(x), where f(x) is the formula for number of operations done, (4n^2 + 2n + 1 explained above), we obtain the big-O value [O(n^2) in this case]. But this would have to account for Lagrange interpolation in the program, which may be hard to implement. And what if the real big-O value was O(2^n), and we might have something like O(x^n), so this algorithm probably wouldn't be programmable. But if someone proves me wrong, give me the code . . . .
Try:
$result = curl_exec($cURL);
$result = json_decode($result,true);
Now you can access MessageID
from $result['MessageID']
.
As for the database, it's simply using a query like so:
INSERT INTO `tableName`(`Cancelled`,`Queued`,`SMSError`,`SMSIncommingMessage`,`Sent`,`SentDateTime`) VALUES('?','?','?','?','?');
Prepared.
This is what I've used:
::Date Variables - replace characters that are not legal as part of filesystem file names (to produce name like "backup_04.15.08.7z")
SET DT=%date%
SET DT=%DT:/=.%
SET DT=%DT:-=.%
If you want further ideas for automating backups to 7-Zip archives, I have a free/open project you can use or review for ideas: http://wittman.org/ziparcy/
How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:
Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.
According to the book PHP and MySQL for Dynamic Web Sites (4th edition)
Example:
$r = mysqli_query($dbc, $q);
For simple queries like INSERT, UPDATE, DELETE, etc. (which do not return records), the $r
variable—short for result—will be either TRUE or FALSE, depending upon whether the query executed successfully.
Keep in mind that “executed successfully” means that it ran without error; it doesn’t mean that the query’s execution necessarily had the desired result; you’ll need to test for that.
Then how to test?
While the mysqli_num_rows()
function will return the number of rows generated by a SELECT query, mysqli_affected_rows()
returns the number of rows affected by an INSERT, UPDATE, or DELETE query. It’s used like so:
$num = mysqli_affected_rows($dbc);
Unlike mysqli_num_rows()
, the one argument the function takes is the database connection ($dbc), not the results of the previous query ($r).
Yes:
>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})
Using the sorted keyword key and a lambda function:
>>> sorted(x.items(), key=lambda i: i[1])
[('b', 3), ('a', 5), ('c', 7)]
>>> sorted(x.items(), key=lambda i: i[1], reverse=True)
[('c', 7), ('a', 5), ('b', 3)]
This works for all dictionaries. However Counter
has a special function which already gives you the sorted items (from most frequent, to least frequent). It's called most_common()
:
>>> x.most_common()
[('c', 7), ('a', 5), ('b', 3)]
>>> list(reversed(x.most_common())) # in order of least to most
[('b', 3), ('a', 5), ('c', 7)]
You can also specify how many items you want to see:
>>> x.most_common(2) # specify number you want
[('c', 7), ('a', 5)]
"Just set the MaxSelectionCount
to 1 so that users cannot select more than one day. Then in the SelectionRange.Start.ToString()
. There is nothing available to show the selection of only one day." - Justin Etheredge
From here.
If you mean using a literal, you simply have to create a binary string:
insert into Files (FileId, FileData) values (1, 0x010203040506)
And you will have a record with a six byte value for the FileData field.
You indicate in the comments that you want to just specify the file name, which you can't do with SQL Server 2000 (or any other version that I am aware of).
You would need a CLR stored procedure to do this in SQL Server 2005/2008 or an extended stored procedure (but I'd avoid that at all costs unless you have to) which takes the filename and then inserts the data (or returns the byte string, but that can possibly be quite long).
In regards to the question of only being able to get data from a SP/query, I would say the answer is yes, because if you give SQL Server the ability to read files from the file system, what do you do when you aren't connected through Windows Authentication, what user is used to determine the rights? If you are running the service as an admin (God forbid) then you can have an elevation of rights which shouldn't be allowed.
You may also want to read "Why getter and setter methods are evil":
Though getter/setter methods are commonplace in Java, they are not particularly object oriented (OO). In fact, they can damage your code's maintainability. Moreover, the presence of numerous getter and setter methods is a red flag that the program isn't necessarily well designed from an OO perspective.
This article explains why you shouldn't use getters and setters (and when you can use them) and suggests a design methodology that will help you break out of the getter/setter mentality.
I am not sure if this is efficient, but this is one of the possible ways:
Read json from url use url.openStream()
and read contents into a string.
construct a JSON object with this string (more at json.org)
JSONObject(java.lang.String source)
Construct a JSONObject from a source JSON text string.
Here is a visual supplement to the other answers. My fuller answer with the code and explanations is here.
You can do this in jEdit, by using the "Return value of a BeanShell snippet" option in jEdit's find and replace dialog. Just search for " [a-z]"
and replace it by " _0.toUpperCase()"
(without quotes)
I encountered this same error: ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ', completed)' at line 1
This was the input I had entered on terminal: mysql> create table todos (description, completed);
Solution: For each column type you must specify the type of content they will contain. This could either be text, integer, variable, boolean there are many different types of data.
mysql> create table todos (description text, completed boolean);
Query OK, 0 rows affected (0.02 sec)
It now passed successfully.
Best way to get rid of this file forever and never have to worry about it again is
make a global .gitignore file:
echo .DS_Store >> ~/.gitignore_global
And let git know that you want to use this file for all of your repositories:
git config --global core.excludesfile ~/.gitignore_global And that’s it! .DS_Store is out of your way.
For a functional programming Ramda has a nice method for this. The same method works going from positive to negative and vice versa.
The built-in webserver is hardwired to use Default.aspx as the default page.
The project must have atleast an empty Default.aspx
file to overcome the Directory Listing problem for Global.asax
.
:)
Once you add that empty file all requests can be handled in one location.
public class Global : System.Web.HttpApplication
{
protected void Application_BeginRequest(object sender, EventArgs e)
{
this.Response.Write("hi@ " + this.Request.Path + "?" + this.Request.QueryString);
this.Response.StatusCode = 200;
this.Response.ContentType = "text/plain";
this.Response.End();
}
}
To adjust the length of the samples:
set key samplen X
(default is 4)
To adjust the vertical spacing of the samples:
set key spacing X
(default is 1.25)
and (for completeness), to adjust the fontsize:
set key font "<face>,<size>"
(default depends on the terminal)
And of course, all these can be combined into one line:
set key samplen 2 spacing .5 font ",8"
Note that you can also change the position of the key using set key at <position>
or any one of the pre-defined positions (which I'll just defer to help key
at this point)
Imports System.IO
Public Class Form1
Public line, counter As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
counter += 1
If TextBox1.Text = "" Then
MsgBox("Enter a DNS address to ping")
Else
'line = ":start" + vbNewLine
'line += "ping " + TextBox1.Text
'MsgBox(line)
Dim StreamToWrite As StreamWriter
StreamToWrite = New StreamWriter("C:\Desktop\Ping" + counter + ".bat")
StreamToWrite.Write(":start" + vbNewLine + _
"Ping -t " + TextBox1.Text)
StreamToWrite.Close()
Dim p As New System.Diagnostics.Process()
p.StartInfo.FileName = "C:\Desktop\Ping" + counter + ".bat"
p.Start()
End If
End Sub
End Class
This works as well
There may be other ways to get your desired result.
Declare @a int
Declare @b int
SET @a = 3
SET @b=2
SELECT cast((cast(@a as float)/ cast(@b as float)) as float)
You could use something like a set from Programming in Lua:
function Set (list)
local set = {}
for _, l in ipairs(list) do set[l] = true end
return set
end
Then you could put your list in the Set and test for membership:
local items = Set { "apple", "orange", "pear", "banana" }
if items["orange"] then
-- do something
end
Or you could iterate over the list directly:
local items = { "apple", "orange", "pear", "banana" }
for _,v in pairs(items) do
if v == "orange" then
-- do something
break
end
end
You can experiment with model.summary()
(notice the concatenate_XX (Concatenate) layer size)
# merge samples, two input must be same shape
inp1 = Input(shape=(10,32))
inp2 = Input(shape=(10,32))
cc1 = concatenate([inp1, inp2],axis=0) # Merge data must same row column
output = Dense(30, activation='relu')(cc1)
model = Model(inputs=[inp1, inp2], outputs=output)
model.summary()
# merge row must same column size
inp1 = Input(shape=(20,10))
inp2 = Input(shape=(32,10))
cc1 = concatenate([inp1, inp2],axis=1)
output = Dense(30, activation='relu')(cc1)
model = Model(inputs=[inp1, inp2], outputs=output)
model.summary()
# merge column must same row size
inp1 = Input(shape=(10,20))
inp2 = Input(shape=(10,32))
cc1 = concatenate([inp1, inp2],axis=1)
output = Dense(30, activation='relu')(cc1)
model = Model(inputs=[inp1, inp2], outputs=output)
model.summary()
You can view notebook here for detail: https://nbviewer.jupyter.org/github/anhhh11/DeepLearning/blob/master/Concanate_two_layer_keras.ipynb
The latest version of elementtree supports XPath pretty well. Not being an XPath expert I can't say for sure if the implementation is full but it has satisfied most of my needs when working in Python. I've also use lxml and PyXML and I find etree nice because it's a standard module.
NOTE: I've since found lxml and for me it's definitely the best XML lib out there for Python. It does XPath nicely as well (though again perhaps not a full implementation).
Omit the where
clause:
update mytable set
column1 = value1,
column2 = value2,
-- other column values etc
;
This will give all rows the same values.
This might not be what you want - consider truncate
then a mass insert
:
truncate mytable; -- delete all rows efficiently
insert into mytable (column1, column2, ...) values
(row1value1, row1value2, ...), -- row 1
(row2value1, row2value2, ...), -- row 2
-- etc
;
Pelo Hyper-V:
private PerformanceCounter theMemCounter = new PerformanceCounter(
"Hyper-v Dynamic Memory VM",
"Physical Memory",
Process.GetCurrentProcess().ProcessName);
I think pi has ssh server enabled by default. Mine have always worked out of the box. Depends which operating system version maybe.
Most of the time when it fails for me it is because the ip address has been changed. Perhaps you are pinging something else now? Also sometimes they just refuse to connect and need a restart.
In your third point, "T" cannot be resolved because its not declared, usually when you declare a generic class you can use "T" as the name of the bound type parameter, many online examples including oracle's tutorials use "T" as the name of the type parameter, say for example, you declare a class like:
public class FooHandler<T>
{
public void operateOnFoo(T foo) { /*some foo handling code here*/}
}
you are saying that FooHandler's
operateOnFoo
method expects a variable of type "T" which is declared on the class declaration itself, with this in mind, you can later add another method like
public void operateOnFoos(List<T> foos)
in all the cases either T, E or U there all identifiers of the type parameter, you can even have more than one type parameter which uses the syntax
public class MyClass<Atype,AnotherType> {}
in your forth ponint although efectively Sting is a sub type of Object, in generics classes there is no such relation, List<String>
is not a sub type of List<Object>
they are two diferent types from the compiler point of view, this is best explained in this blog entry
Try this one if you are working with python 2.7:
from __future__ import print_function
For those who may be running WAMP 3.1.4 with Apache 2.4.35 on Windows 10 (64-bit)
If you're having issues with external devices connecting to your localhost, and receiving a 403 Forbidden error, it may be an issue with your httpd.conf and the httpd-vhosts.conf files and the "Require local" line they both have within them.
[Before] httpd-vhosts.conf
<VirtualHost *:80>
ServerName localhost
ServerAlias localhost
DocumentRoot "${INSTALL_DIR}/www"
<Directory "${INSTALL_DIR}/www/">
Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require local <--- This is the offending line.
</Directory>
</VirtualHost>
[After] httpd-vhosts.conf
<VirtualHost *:80>
ServerName localhost
ServerAlias localhost
DocumentRoot "${INSTALL_DIR}/www"
<Directory "${INSTALL_DIR}/www/">
Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
</Directory>
</VirtualHost>
Additionally, you'll need to update your httpd.conf file as follows:
[Before] httpd.conf
DocumentRoot "${INSTALL_DIR}/www"
<Directory "${INSTALL_DIR}/www/">
# onlineoffline tag - don't remove
Require local #<--- This is the offending line.
</Directory>
[After] httpd.conf
DocumentRoot "${INSTALL_DIR}/www"
<Directory "${INSTALL_DIR}/www/">
# onlineoffline tag - don't remove
# Require local
</Directory>
Make sure to restart your WAMP server via (System tray at bottom-right of screen --> left-click WAMP icon --> "Restart all Services").
Then refresh your machine's browser on localhost to ensure you've still got proper connectivity there, and then refresh your other external devices that you were previously attempting to connect.
Disclaimer: If you're in a corporate setting, this is untested from a security perspective; please ensure you're keenly aware of your local development environment's access protocols before implementing any sweeping changes.
use this
final int childCount = mainL.getChildCount();
for (int i = 0; i < childCount; i++) {
View element = mainL.getChildAt(i);
// EditText
if (element instanceof EditText) {
EditText editText = (EditText)element;
System.out.println("ELEMENTS EditText getId=>"+editText.getId()+ " getTag=>"+element.getTag()+
" getText=>"+editText.getText());
}
// CheckBox
if (element instanceof CheckBox) {
CheckBox checkBox = (CheckBox)element;
System.out.println("ELEMENTS CheckBox getId=>"+checkBox.getId()+ " getTag=>"+checkBox.getTag()+
" getText=>"+checkBox.getText()+" isChecked=>"+checkBox.isChecked());
}
// DatePicker
if (element instanceof DatePicker) {
DatePicker datePicker = (DatePicker)element;
System.out.println("ELEMENTS DatePicker getId=>"+datePicker.getId()+ " getTag=>"+datePicker.getTag()+
" getDayOfMonth=>"+datePicker.getDayOfMonth());
}
// Spinner
if (element instanceof Spinner) {
Spinner spinner = (Spinner)element;
System.out.println("ELEMENTS Spinner getId=>"+spinner.getId()+ " getTag=>"+spinner.getTag()+
" getSelectedItemId=>"+spinner.getSelectedItemId()+
" getSelectedItemPosition=>"+spinner.getSelectedItemPosition()+
" getTag(key)=>"+spinner.getTag(spinner.getSelectedItemPosition()));
}
}
Best way to send html formatted Email
This code will be in "Customer.htm"
<table>
<tr>
<td>
Dealer's Company Name
</td>
<td>
:
</td>
<td>
#DealerCompanyName#
</td>
</tr>
</table>
Read HTML file Using System.IO.File.ReadAllText. get all HTML code in string variable.
string Body = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("EmailTemplates/Customer.htm"));
Replace Particular string to your custom value.
Body = Body.Replace("#DealerCompanyName#", _lstGetDealerRoleAndContactInfoByCompanyIDResult[0].CompanyName);
call SendEmail(string Body) Function and do procedure to send email.
public static void SendEmail(string Body)
{
MailMessage message = new MailMessage();
message.From = new MailAddress(Session["Email"].Tostring());
message.To.Add(ConfigurationSettings.AppSettings["RequesEmail"].ToString());
message.Subject = "Request from " + SessionFactory.CurrentCompany.CompanyName + " to add a new supplier";
message.IsBodyHtml = true;
message.Body = Body;
SmtpClient smtpClient = new SmtpClient();
smtpClient.UseDefaultCredentials = true;
smtpClient.Host = ConfigurationSettings.AppSettings["SMTP"].ToString();
smtpClient.Port = Convert.ToInt32(ConfigurationSettings.AppSettings["PORT"].ToString());
smtpClient.EnableSsl = true;
smtpClient.Credentials = new System.Net.NetworkCredential(ConfigurationSettings.AppSettings["USERNAME"].ToString(), ConfigurationSettings.AppSettings["PASSWORD"].ToString());
smtpClient.Send(message);
}
Derivation of delete queries using given method name is supported starting with version 1.6.0.RC1 of Spring Data JPA. The keywords remove
and delete
are supported. As return value one can choose between the number or a list of removed entities.
Long removeByLastname(String lastname);
List<User> deleteByLastname(String lastname);
Since this would be a common task I would suggest wrapping a switch/case inside of a function call.
function getVocationName($vocation){
switch($vocation){
case 1: return "Sorcerer";
case 2: return 'Druid';
case 3: return 'Paladin';
case 4: return 'Knight';
case 5: return 'Master Sorcerer';
case 6: return 'Elder Druid';
case 7: return 'Royal Paladin';
default: return 'Elite Knight';
}
}
echo getVocationName($result->vocation);
Updated version for Swift 3:
@IBDesignable
class FormTextField: UITextField {
@IBInspectable var paddingLeft: CGFloat = 0
@IBInspectable var paddingRight: CGFloat = 0
override func textRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(x: bounds.origin.x + paddingLeft, y: bounds.origin.y, width: bounds.size.width - paddingLeft - paddingRight, height: bounds.size.height)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return textRect(forBounds: bounds)
}
}
I uninstalled all extension I had already installed, and it turns out JavaScript and TypeScript IntelliSense extension from below address caused the issue. https://marketplace.visualstudio.com/items?itemName=sourcegraph.javascript-typescript
the point here is when you visit the website you see there is a yellow label, telling you it is in preview release, but when you browse in vs extensions, you don't see that label.
But if you are using Plesk, change your settings in :
/usr/local/psa/admin/htdocs/domains/databases/phpMyAdmin/libraries/config.default.php
Change $cfg['ExecTimeLimit'] = 300;
to $cfg['ExecTimeLimit'] = 0;
And restart with Plesk UI or use:
/etc/init.d/psa restart
and
/etc/init.d/httpd restart
I just had to dig through this issue myself and succeeded. Contrary to what others have offered as solutions, the path to my happy ending was directly correlated to JavaDoc. No "src.zip" files necessary. My trials and tribulations in the process involved finding the CORRECT JavaDoc to point at. Pointing a Java 1.7 project at Java 8 Javadoc does NOT work. (Even if "jre8" appears to be the only installed JRE available.) Thus, I beat my head against the brick wall unnecessarily.
Window > Preferences > Java > Installed JREs
If the JRE of your project is not listed (as happened to me when I migrated a jre7 project to a new jre8 workspace), you will need to add it here. Click "Add..." and point your Workspace at the desired jre folder. (Mine was C://Program Files/Java/jre7). Then "Edit..." the now-available JRE, select the rt.jar, and click "Javadoc Location..." and aim it at the correct javadoc location. For my use:
For jre7 -- http://docs.oracle.com/javase/7/docs/api/ For jre8 -- http://docs.oracle.com/javase/8/docs/api/
Voila, hover tooltip javadoc is re-enabled. I hope this helps anyone else trying to figure this problem out.
I would emphasize the importance of limiting the ::ng-deep
to only children of a component by requiring the parent to be an encapsulated css class.
For this to work it's important to use the ::ng-deep
after the parent, not before otherwise it would apply to all the classes with the same name the moment the component is loaded.
Using the :host
keyword before ::ng-deep
will handle this automatically:
:host ::ng-deep .mat-checkbox-layout
Alternatively you can achieve the same behavior by adding a component scoped CSS class before the ::ng-deep
keyword:
.my-component ::ng-deep .mat-checkbox-layout {
background-color: aqua;
}
Component template:
<h1 class="my-component">
<mat-checkbox ....></mat-checkbox>
</h1>
Resulting (Angular generated) css will then include the uniquely generated name and apply only to its own component instance:
.my-component[_ngcontent-c1] .mat-checkbox-layout {
background-color: aqua;
}
Below code will help you to generate random numbers between two numbers in the given range:
private void generateRandomNumbers(int min, int max) {
// min & max will be changed as per your requirement. In my case, I've taken min = 2 & max = 32
int randomNumberCount = 10;
int dif = max - min;
if (dif < (randomNumberCount * 3)) {
dif = (randomNumberCount * 3);
}
int margin = (int) Math.ceil((float) dif / randomNumberCount);
List<Integer> randomNumberList = new ArrayList<>();
Random random = new Random();
for (int i = 0; i < randomNumberCount; i++) {
int range = (margin * i) + min; // 2, 5, 8
int randomNum = random.nextInt(margin);
if (randomNum == 0) {
randomNum = 1;
}
int number = (randomNum + range);
randomNumberList.add(number);
}
Collections.sort(randomNumberList);
Log.i("generateRandomNumbers", "RandomNumberList: " + randomNumberList);
}
Expanding on Ehsan's Answer....
If you are using .Net framework 4.5 then you can have a simple method to verify email address using EmailAddressAttribute
Class in code.
private static bool IsValidEmailAddress(string emailAddress)
{
return new System.ComponentModel.DataAnnotations
.EmailAddressAttribute()
.IsValid(emailAddress);
}
If you are considering REGEX to verify email address then read:
I Knew How To Validate An Email Address Until I Read The RFC By Phil Haack
I had a similar problem and I ended up writing a node extension for this. You can check out the git repository. It's open source and free and all that good stuff !
https://github.com/aponxi/npm-execxi
ExecXI is a node extension written in C++ to execute shell commands one by one, outputting the command's output to the console in real-time. Optional chained, and unchained ways are present; meaning that you can choose to stop the script after a command fails (chained), or you can continue as if nothing has happened !
Usage instructions are in the ReadMe file. Feel free to make pull requests or submit issues!
I thought it was worth to mention it.
Whatever you set in crontab
will be available in the cronjobs, both directly and using the variables in the scripts.
You can configure crontab
so that it sets variables that then the can cronjob use:
$ crontab -l
myvar="hi man"
* * * * * echo "$myvar. date is $(date)" >> /tmp/hello
Now the file /tmp/hello
shows things like:
$ cat /tmp/hello
hi man. date is Thu May 12 12:10:01 CEST 2016
hi man. date is Thu May 12 12:11:01 CEST 2016
You can configure crontab
so that it sets variables that then the scripts can use:
$ crontab -l
myvar="hi man"
* * * * * /bin/bash /tmp/myscript.sh
And say script /tmp/myscript.sh
is like this:
echo "Now is $(date). myvar=$myvar" >> /tmp/myoutput.res
It generates a file /tmp/myoutput.res
showing:
$ cat /tmp/myoutput.res
Now is Thu May 12 12:07:01 CEST 2016. myvar=hi man
Now is Thu May 12 12:08:01 CEST 2016. myvar=hi man
...
Swift 2.2
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let userDefaults = NSUserDefaults.standardUserDefaults()
if userDefaults.objectForKey("ApplicationIdentifier") == nil {
let UUID = NSUUID().UUIDString
userDefaults.setObject(UUID, forKey: "ApplicationIdentifier")
userDefaults.synchronize()
}
return true
}
//Retrieve
print(NSUserDefaults.standardUserDefaults().valueForKey("ApplicationIdentifier")!)
$request = [System.Net.WebRequest]::Create('http://stackoverflow.com/questions/20259251/powershell-script-to-check-the-status-of-a-url')
$response = $request.GetResponse()
$response.StatusCode
$response.Close()
The easiest way to create a list where all values are the same is multiplying a one-element list by n
.
>>> [0] * 4
[0, 0, 0, 0]
So for your loop:
for i in range(10):
print [0] * i
Standard CSS3 rotate should work in IE9, but I believe you need to give it a vendor prefix, like so:
-ms-transform: rotate(10deg);
It is possible that it may not work in the beta version; if not, try downloading the current preview version (preview 7), which is a later revision that the beta. I don't have the beta version to test against, so I can't confirm whether it was in that version or not. The final release version is definitely slated to support it.
I can also confirm that the IE-specific filter
property has been dropped in IE9.
[Edit]
People have asked for some further documentation. As they say, this is quite limited, but I did find this page: http://css3please.com/ which is useful for testing various CSS3 features in all browsers.
But testing the rotate feature on this page in IE9 preview caused it to crash fairly spectacularly.
However I have done some independant tests using -ms-transform:rotate()
in IE9 in my own test pages, and it is working fine. So my conclusion is that the feature is implemented, but has got some bugs, possibly related to setting it dynamically.
Another useful reference point for which features are implemented in which browsers is www.canIuse.com -- see http://caniuse.com/#search=rotation
[EDIT]
Reviving this old answer because I recently found out about a hack called CSS Sandpaper which is relevant to the question and may make things easier.
The hack implements support for the standard CSS transform
for for old versions of IE. So now you can add the following to your CSS:
-sand-transform: rotate(10deg);
...and have it work in IE 6/7/8, without having to use the filter
syntax. (of course it still uses the filter syntax behind the scenes, but this makes it a lot easier to manage because it's using similar syntax to other browsers)
what platform are you running?..
if its unix, maybe adding
alias java='java -Xmx1g'
to .bashrc (or similar) work
edit: Changing XmX to Xmx
Here is another possible way:
void main() {
var s1 = Singleton.instance;
s1.somedata = 123;
var s2 = Singleton.instance;
print(s2.somedata); // 123
print(identical(s1, s2)); // true
print(s1 == s2); // true
//var s3 = new Singleton(); //produces a warning re missing default constructor and breaks on execution
}
class Singleton {
static final Singleton _singleton = new Singleton._internal();
Singleton._internal();
static Singleton get instance => _singleton;
var somedata;
}
Swift 4 and Above
add below code into you tableview's didselect row delegate method
tableView.beginUpdates()
tableView.setNeedsLayout()
tableView.endUpdates()
function GetPixel(context, x, y)
{
var p = context.getImageData(x, y, 1, 1).data;
var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
return hex;
}
function rgbToHex(r, g, b) {
if (r > 255 || g > 255 || b > 255)
throw "Invalid color component";
return ((r << 16) | (g << 8) | b).toString(16);
}
At the time you emit the very first line,
Artist Title Price Genre Disc Sale Tax Cash
to achieve "alignment", you have to know "in advance" how wide each column will need to be (otherwise, alignment is impossible). Once you do know the needed width for each column (there are several possible ways to achieve that depending on where your data's coming from), then the setw
function mentioned in the other answer will help, or (more brutally;-) you could emit carefully computed number of extra spaces (clunky, to be sure), etc. I don't recommend tabs anyway as you have no real control on how the final output device will render those, in general.
Back to the core issue, if you have each column's value in a vector<T>
of some sort, for example, you can do a first formatting pass to determine the maximum width of the column, for example (be sure to take into account the width of the header for the column, too, of course).
If your rows are coming "one by one", and alignment is crucial, you'll have to cache or buffer the rows as they come in (in memory if they fit, otherwise on a disk file that you'll later "rewind" and re-read from the start), taking care to keep updated the vector of "maximum widths of each column" as the rows do come. You can't output anything (not even the headers!), if keeping alignment is crucial, until you've seen the very last row (unless you somehow magically have previous knowledge of the columns' widths, of course;-).
I guess you're coming from a windows background. So i'll contrast them (i'm kind of new to linux too). I found user's reply to my comment, to be useful in figuring things out.
In Windows, a variable can be permanent or not. The term Environment variable includes a variable set in the cmd shell with the SET command, as well as when the variable is set within the windows GUI, thus set in the registry, and becoming viewable in new cmd windows. e.g. documentation for the set command in windows https://technet.microsoft.com/en-us/library/bb490998.aspx "Displays, sets, or removes environment variables. Used without parameters, set displays the current environment settings." In Linux, set does not display environment variables, it displays shell variables which it doesn't call/refer to as environment variables. Also, Linux doesn't use set to set variables(apart from positional parameters and shell options, which I explain as a note at the end), only to display them and even then only to display shell variables. Windows uses set for setting and displaying e.g. set a=5, linux doesn't.
In Linux, I guess you could make a script that sets variables on bootup, e.g. /etc/profile
or /etc/.bashrc
but otherwise, they're not permanent. They're stored in RAM.
There is a distinction in Linux between shell variables, and environment variables. In Linux, shell variables are only in the current shell, and Environment variables, are in that shell and all child shells.
You can view shell variables with the set
command (though note that unlike windows, variables are not set in linux with the set command).
set -o posix; set
(doing that set -o posix once first, helps not display too much unnecessary stuff). So set
displays shell variables.
You can view environment variables with the env
command
shell variables are set with e.g. just a = 5
environment variables are set with export, export also sets the shell variable
Here you see shell variable zzz set with zzz = 5, and see it shows when running set
but doesn't show as an environment variable.
Here we see yyy set with export, so it's an environment variable. And see it shows under both shell variables and environment variables
$ zzz=5
$ set | grep zzz
zzz=5
$ env | grep zzz
$ export yyy=5
$ set | grep yyy
yyy=5
$ env | grep yyy
yyy=5
$
other useful threads
https://unix.stackexchange.com/questions/176001/how-can-i-list-all-shell-variables
https://askubuntu.com/questions/26318/environment-variable-vs-shell-variable-whats-the-difference
Note- one point which elaborates a bit and is somewhat corrective to what i've written, is that, in linux bash, 'set' can be used to set "positional parameters" and "shell options/attributes", and technically both of those are variables, though the man pages might not describe them as such. But still, as mentioned, set won't set shell variables or environment variables). If you do set asdf
then it sets $1 to asdf, and if you do echo $1
you see asdf. If you do set a=5
it won't set the variable a, equal to 5. It will set the positional parameter $1 equal to the string of "a=5". So if you ever saw set a=5 in linux it's probably a mistake unless somebody actually wanted that string a=5, in $1. The other thing that linux's set can set, is shell options/attributes. If you do set -o you see a list of them. And you can do for example set -o verbose
, off, to turn verbose on(btw the default happens to be off but that makes no difference to this). Or you can do set +o verbose
to turn verbose off. Windows has no such usage for its set command.
Only managed Languages like c#
and Java
can be decompiled completely.You can view complete source code.
For Win32 dll
you cannot get source code.
For CSharp dll Use DotPeek becoz it free and works same as ReDgate .Net Compiler
Have fun.
As you are not trying to move the files around in the tree, you should be able to just checkout the directory:
git checkout master -- dirname
While the instructions on the Boost web site are helpful, here is a condensed version that also builds x64 libraries.
This installs the Boost header files under C:\Boost\include\boost-(version)
, and the 32-bit libraries under C:\Boost\lib\i386
. Note that the default location for the libraries is C:\Boost\lib
but you’ll want to put them under an i386
directory if you plan to build for multiple architectures.
bootstrap
Run: b2 toolset=msvc-12.0 --build-type=complete --libdir=C:\Boost\lib\i386 install
toolset=msvc-11.0
toolset=msvc-10.0
toolset=msvc-14.1
Add C:\Boost\include\boost-(version)
to your include path.
C:\Boost\lib\i386
to your libs path.This installs the Boost header files under C:\Boost\include\boost-(version)
, and the 64-bit libraries under C:\Boost\lib\x64
. Note that the default location for the libraries is C:\Boost\lib
but you’ll want to put them under an x64
directory if you plan to build for multiple architectures.
bootstrap
b2 toolset=msvc-12.0 --build-type=complete --libdir=C:\Boost\lib\x64 architecture=x86 address-model=64 install
toolset=msvc-11.0
toolset=msvc-10.0
C:\Boost\include\boost-(version)
to your include path.C:\Boost\lib\x64
to your libs path.DECLARE @Number int = 1;
SELECT RIGHT('0'+ CONVERT(VARCHAR, @Number), 2)
--OR
SELECT RIGHT(CONVERT(VARCHAR, 100 + @Number), 2)
GO
In one of our API project we decide to set a 409 Status to some request, when we can't full fill it at 100% because of missing parameter.
HTTP Status Code "409 Conflict" was for us a good try because it's definition require to include enough information for the user to recognize the source of the conflict.
Reference: w3.org/Protocols/
So among other response like 400 or 404 we chose 409 to enforce the need for looking over some notes in the request helpful to set up a new and right request.
Any way our case it was particular because we need to send out some data eve if the request was not completely correct, and we need to enforce the client to look at the message and understand what was wrong in the request.
In general if we have only some missing parameter we go for a 400 and an array of missing parameter. But when we need to send some more information, like a particular case message and we want to be more sure the client will take care of it we send a 409
Yes! exit()
. It's in <cstdlib>
.
Reference taken from this post:
You can also use this script to find lock in MySQL.
SELECT
pl.id
,pl.user
,pl.state
,it.trx_id
,it.trx_mysql_thread_id
,it.trx_query AS query
,it.trx_id AS blocking_trx_id
,it.trx_mysql_thread_id AS blocking_thread
,it.trx_query AS blocking_query
FROM information_schema.processlist AS pl
INNER JOIN information_schema.innodb_trx AS it
ON pl.id = it.trx_mysql_thread_id
INNER JOIN information_schema.innodb_lock_waits AS ilw
ON it.trx_id = ilw.requesting_trx_id
AND it.trx_id = ilw.blocking_trx_id
this method also encounter a deprecate warning:
org.junit.Assert.assertEquals(float expected,float actual) //deprecated
It is because currently junit prefer a third parameter rather than just two float variables input.
The third parameter is delta:
public static void assertEquals(double expected,double actual,double delta) //replacement
this is mostly used to deal with inaccurate Floating point calculations
for more information, please refer this problem: Meaning of epsilon argument of assertEquals for double values
The easiest way:
Step 1: Open AndroidManifest.xml file
Step 2: Locate android:theme="@style/AppTheme" >
Step 3: Change to android:theme="@style/Theme.AppCompat.NoActionBar" >
Step 4: Then Add ImageView & Image
Step 4: That's it!
I'd use something like:
dim customer = (from c in xmldoc...<Customer>
where c.<ID>.Value=22
select c).SingleOrDefault
Edit:
missed the c# tag, sorry......the example is in VB.NET
If you want to save it as .fig file, hgsave is the function in Matlab R2012a. In later versions, savefig may also work.
There is no need for any External libraries, the JRE System libraries provide all you need.
I am infering that you have a org.w3c.dom.Document
object you would like to write to a file
To do that, you use a javax.xml.transform.Transformer
:
import org.w3c.dom.Document
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
public class XMLWriter {
public static void writeDocumentToFile(Document document, File file) {
// Make a transformer factory to create the Transformer
TransformerFactory tFactory = TransformerFactory.newInstance();
// Make the Transformer
Transformer transformer = tFactory.newTransformer();
// Mark the document as a DOM (XML) source
DOMSource source = new DOMSource(document);
// Say where we want the XML to go
StreamResult result = new StreamResult(file);
// Write the XML to file
transformer.transform(source, result);
}
}
Source: http://docs.oracle.com/javaee/1.4/tutorial/doc/JAXPXSLT4.html
If you are using foreach
inside a function and you are expecting an array or a Traversable object you can type hint that function with:
function myFunction(array $a)
function myFunction(Traversable)
If you are not using foreach
inside a function or you are expecting both you can simply use this construct to check if you can iterate over the variable:
if (is_array($a) or ($a instanceof Traversable))
What you're using in the python code is called a list in python, and it's tottaly different from R vectors, if i get what you wanna do:
# you can do like this if you'll put them manually
v <- c("a", "b", "c")
# if your values are in a list
v <- as.vector(your_list)
# if you just need to append
v <- append(v, value, after=length(v))
If you really want to use PHP as your backend for socket.io ,here are what I found. Two socket.io php server side alternative.
https://github.com/walkor/phpsocket.io
https://github.com/RickySu/phpsocket.io
Exmaple codes for the first repository like this.
use PHPSocketIO\SocketIO;
// listen port 2021 for socket.io client
$io = new SocketIO(2021);
$io->on('connection', function($socket)use($io){
$socket->on('chat message', function($msg)use($io){
$io->emit('chat message', $msg);
});
});
Before the problem arises, try to avoid it as much as possible:
Use appropriate tools for debugging. On Unix:
-fsanitize=address
flag.Finally I would recommend the usual things. The more your program is readable, maintainable, clear and neat, the easiest it will be to debug.
Also this is a cause too: If you built a jQuery collection (via .map() or something similar) then you shouldn't use this collection in .ajax()'s data. Because it's still a jQuery object, not plain JavaScript Array. You should use .get() at the and to get plain js array and should use it on the data setting on .ajax().
Comparator
provides a way for you to provide custom comparison logic for types that you have no control over.
Comparable
allows you to specify how objects that you are implementing get compared.
Obviously, if you don't have control over a class (or you want to provide multiple ways to compare objects that you do have control over) then use Comparator
.
Otherwise you can use Comparable
.
Model.select(:rating).distinct
This problem is because of the fact that eclipse is not able to find Java ,
Check the java directory cd /Library/Java/JavaVirtualMachines///Contents/Home/jre/bin
If thats not present down JDK from http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
Once JDK is installed change eclipse.ini file
On Mac: Right click on Eclipse icon and click "Show package Content"
Navigate to eclipse>Contents>Eclipse>eclipse.ini
Open the file and replace the java path after "-vm" with this
/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/bin
You could use setInterval
for this.
<script type="text/javascript">
function myFunction () {
console.log('Executed!');
}
var interval = setInterval(function () { myFunction(); }, 60000);
</script>
Disable the timer by setting clearInterval(interval)
.
See this Fiddle: http://jsfiddle.net/p6NJt/2/
(This is my third answer because I misunderstood what your code was doing in my original, and then made a small but crucial mistake in my second—hopefully three's a charm.
Edits: Since this seems to be a popular answer, I've made a few modifications to improve its implementation over the years—most not too major. This is so if folks use it as template, it will provide an even better basis.
As others have pointed out, your MemoryError
problem is most likely because you're attempting to read the entire contents of huge files into memory and then, on top of that, effectively doubling the amount of memory needed by creating a list of lists of the string values from each line.
Python's memory limits are determined by how much physical ram and virtual memory disk space your computer and operating system have available. Even if you don't use it all up and your program "works", using it may be impractical because it takes too long.
Anyway, the most obvious way to avoid that is to process each file a single line at a time, which means you have to do the processing incrementally.
To accomplish this, a list of running totals for each of the fields is kept. When that is finished, the average value of each field can be calculated by dividing the corresponding total value by the count of total lines read. Once that is done, these averages can be printed out and some written to one of the output files. I've also made a conscious effort to use very descriptive variable names to try to make it understandable.
try:
from itertools import izip_longest
except ImportError: # Python 3
from itertools import zip_longest as izip_longest
GROUP_SIZE = 4
input_file_names = ["A1_B1_100000.txt", "A2_B2_100000.txt", "A1_B2_100000.txt",
"A2_B1_100000.txt"]
file_write = open("average_generations.txt", 'w')
mutation_average = open("mutation_average", 'w') # left in, but nothing written
for file_name in input_file_names:
with open(file_name, 'r') as input_file:
print('processing file: {}'.format(file_name))
totals = []
for count, fields in enumerate((line.split('\t') for line in input_file), 1):
totals = [sum(values) for values in
izip_longest(totals, map(float, fields), fillvalue=0)]
averages = [total/count for total in totals]
for print_counter, average in enumerate(averages):
print(' {:9.4f}'.format(average))
if print_counter % GROUP_SIZE == 0:
file_write.write(str(average)+'\n')
file_write.write('\n')
file_write.close()
mutation_average.close()
First save your program as program.c
.
Now you need the compiler, so you need to go to App Store and install Xcode which is Apple's compiler and development tools. How to find App Store? Do a "Spotlight Search" by typing ⌘Space and start typing App Store
and hit Enter when it guesses correctly.
App Store looks like this:
Xcode looks like this on App Store:
Then you need to install the command-line tools in Terminal. How to start Terminal? You need to do another "Spotlight Search", which means you type ⌘Space and start typing Terminal
and hit Enter when it guesses Terminal
.
Now install the command-line tools like this:
xcode-select --install
Then you can compile your code with by simply running gcc
as in the next line without having to fire up the big, ugly software development GUI called Xcode
:
gcc -Wall -o program program.c
Note: On newer versions of OS X, you would use clang
instead of gcc
, like this:
clang program.c -o program
Then you can run it with:
./program
Hello, world!
If your program is C++, you'll probably want to use one of these commands:
clang++ -o program program.cpp
g++ -std=c++11 -o program program.cpp
g++-7 -std=c++11 -o program program.cpp
My solution for this problem when I have to copy all the files (including .
files) to a target directory retaining the permissions is: (overwrite if already exists)
yes | cp -rvp /source/directory /destination/directory/
yes
is for automatically overwriting destination files,
r
recursive,
v
verbose,
p
retain permissions.
Notice that the source path is not ending with a /
(so all the files/directory and . files are copied)
Destination directory ends with /
as we are placing contents of the source folder to destination as a whole.
You have a certificate which is self-signed, so it's non-trusted by default, that's why OpenSSL complains. This warning is actually a good thing, because this scenario might also rise due to a man-in-the-middle attack.
To solve this, you'll need to install it as a trusted server. If it's signed by a non-trusted CA, you'll have to install that CA's certificate as well.
Have a look at this link about installing self-signed certificates.
use
Objective-C
[headingButton setTitleColor:[UIColor colorWithRed:36/255.0 green:71/255.0 blue:113/255.0 alpha:1.0] forState:UIControlStateNormal];
Swift
headingButton.setTitleColor(.black, for: .normal)
(update: 2018)
Note that pd.Timegrouper
is depreciated and will be removed. Use instead:
df.groupby(pd.Grouper(freq='M'))
All the answers above are really good but I needed a way to type as little as possible in the terminal so I created a gem for that. You can install the gem only once and run the command 'shutup' every time you wanna kill the Rails process (while being in the current folder).
gem install shutup
then go in the current folder of your rails project and run
shutup
# this will kill the Rails process currently running
You can use the command 'shutup' every time you want
DICLAIMER: I am the creator of this gem
NOTE: if you are using rvm install the gem globally
rvm @global do gem install shutup
Just found another solutions worked for me. You can use '\' sign before your one special.
passwd=\@31\&3*J
For me the problem was due to using rbenv
and forgetting to set the proper version globally.
So I had to set it with rbenv global xxx
In my case I installed 2.0.0-p247
so I had to issue the command:
rbenv global 2.0.0-p247
rbenv rehash
Then all was working fine.
Just so it be noted: If the requirement to preserve the elements order is relaxed it is much more efficient to replace the element being removed with the last element.
I believe what are you asking about is a variable interpolation in PHP.
Let's do a simple fixture:
$obj = (object) array('foo' => array('bar'), 'property' => 'value');
$var = 'foo';
Now we have an object, where:
print_r($obj);
Will give output:
stdClass Object
(
[foo] => Array
(
[0] => bar
)
[property] => value
)
And we have variable $var
containing string "foo".
If you'll try to use:
$give_me_foo = $obj->$var[0];
Instead of:
$give_me_foo = $obj->foo[0];
You get "Cannot use string offset as an array [...]" error message as a result, because what you are trying to do, is in fact sending message $var[0]
to object $obj
. And - as you can see from fixture - there is no content of $var[0]
defined. Variable $var
is a string and not an array.
What you can do in this case is to use curly braces, which will assure that at first is called content of $var
, and subsequently the rest of message-sent:
$give_me_foo = $obj->{$var}[0];
The result is "bar"
, as you would expect.
do this , please note that you will have to define the regex for 'test'!!!
string s = "7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false";
string[] parts = (new Regex("")).Split(s);
//just do a count on parts
<style>
p{
width: 70%
word-wrap: break-word;
}
</style>
This wasn't working in my case. It worked fine after adding following style.
<style>
p{
width: 70%
word-break: break-all;
}
</style>
For the security reason you can't do that. You must choose Flash for copying to the clipboard.
I suggest this one: http://zeroclipboard.org/
I have a simple idea, something like this:
#!/bin/sh
echo `xrandr --current | grep current | awk '{print $8}'` >> RES1
echo `xrandr --current | grep current | awk '{print $10}'` >> RES2
cat RES2 | sed -i 's/,//g' RES2
P1RES=$(cat RES1)
P2RES=$(cat RES2)
rm RES1 RES2
echo "$P1RES"'x'"$P2RES" >> RES
RES=$(cat RES)
# Play The Game
# Finish The Game with Lower Resolution
xrandr -s $RES
Well, I need a better solution for all display devices under Linux and Similars S.O
If you get the "Failed to find DDMS files..." do this:
Don't be alarmed that its not https, this helps to fetch stuff over http. This trick helped me to resolve the issue on MAC, I believe that this also should work on Windows / Linux
Hope this helps !
I don't like absolute positioning, either, because there is almost always some collateral damage, i.e. unintended side effects. Especially when you are working with a responsive design. There seems to be an alternative - the sandbag technique. By inserting a "helper" element, either in the markup of via CSS, we can push elements down to the bottom of the container. See http://community.sitepoint.com/t/css-floating-divs-to-the-bottom-inside-a-div/20932 for examples.
Based on this blog, one could share a docker image without a docker registry by executing:
docker save --output latestversion-1.0.0.tar dockerregistry/latestversion:1.0.0
Once this command has been completed, one could copy the image to a server and import it as follows:
docker load --input latestversion-1.0.0.tar
$("a").click(function(event) {
event.preventDefault();
});
If this method is called, the default action of the event will not be triggered.
I'm facing the same problem trying to geocode 140 addresses.
My workaround was adding usleep(100000) for each loop of next geocoding request. If status of the request is OVER_QUERY_LIMIT, the usleep is increased by 50000 and request is repeated, and so on.
And of cause all received data (lat/long) are stored in XML file not to run request every time the page is loading.
package com.app;
public class SiftNumberAndEvenNumber {
public static void main(String[] args) {
int arr[] = {1,2,3,4,5};
int arr1[] = new int[arr.length];
int shiftAmount=3;
for(int i = 0; i < arr.length; i++){
int newLocation = (i + (arr.length - shiftAmount)) % arr.length;
arr1[newLocation] = arr[i];
}
for(int i=0;i<arr1.length;i++) {
if(i==arr1.length-1) {
System.out.print(arr1[i]);
}else {
System.out.print(arr1[i]+",");
}
}
System.out.println();
for(int i=0;i<arr1.length;i++) {
if(arr1[i]%2==0) {
System.out.print(arr1[i]+" ");
}
}
}
}
select case when IsNull(CONVERT(DATE, StartDate),'')='' then 'NA' else Convert(varchar(10),StartDate,121) end from table1
Give the buttons a value attribute and then retrieve the values using this:
$("button").click(function(){
var value=$(this).attr("value");
});
Use format string
intNum = 123
print "0x%x"%(intNum)
or hex
function.
intNum = 123
print hex(intNum)
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
public class Stopwatch {
static int interval;
static Timer timer;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Input seconds => : ");
String secs = sc.nextLine();
int delay = 1000;
int period = 1000;
timer = new Timer();
interval = Integer.parseInt(secs);
System.out.println(secs);
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println(setInterval());
}
}, delay, period);
}
private static final int setInterval() {
if (interval == 1)
timer.cancel();
return --interval;
}
}
Try this.
Here is simple example. you can use it like
wget -q -O - http://example.com/backup >/dev/null 2>&1
and in start you can add your option like (*****). Its up to your system requirements either you want to run it every minute or hours etc.
This is The Simplest Method to get both Filename & Extension in just a single line.
fName, ext = 'C:/folder name/Flower.jpeg'.split('/')[-1].split('.')
>>> print(fName)
Flower
>>> print(ext)
jpeg
Unlike other solutions, you don't need to import any package for this.
If by all permissions you mean 777
Navigate to folder and
chmod -R 777 .
I ran into the same error. My web app was pointed towards report viewer version 10.0 however if 11.0 is installed it adds a redirect in the 10.0 .dll to 11.0. This became an issue when 11.0 was uninstalled as this does not correct the redirect in the 10.0 .dll. The fix in my case was to simply uninstall and reinstall 10.0.
Assuming your script is something like the below snippet and named testargs.ps1
param ([string]$w)
Write-Output $w
You can call this at the commandline as:
PowerShell.Exe -File C:\scripts\testargs.ps1 "Test String"
This will print "Test String" (w/o quotes) at the console. "Test String" becomes the value of $w in the script.
You are echoing outside the body tag of your HTML. Put your echos there, and you should be fine.
Also, remove the onclick="alert()"
from your submit. This is the cause for your first undefined
message.
<?php
$posted = false;
if( $_POST ) {
$posted = true;
// Database stuff here...
// $result = mysql_query( ... )
$result = $_POST['name'] == "danny"; // Dummy result
}
?>
<html>
<head></head>
<body>
<?php
if( $posted ) {
if( $result )
echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
else
echo "<script type='text/javascript'>alert('failed!')</script>";
}
?>
<form action="" method="post">
Name:<input type="text" id="name" name="name"/>
<input type="submit" value="submit" name="submit"/>
</form>
</body>
</html>
You can use mkdir:
#include <sys/stat.h>
#include <sys/types.h>
int result = mkdir("/home/me/test.txt", 0777);
You can use the document.createElement()
function like this:
function addScript( src ) {
var s = document.createElement( 'script' );
s.setAttribute( 'src', src );
document.body.appendChild( s );
}
From what I saw in Express 4.0 this works for me. This is example of authentication required middleware.
function apiDemandLoggedIn(req, res, next) {
// if user is authenticated in the session, carry on
console.log('isAuth', req.isAuthenticated(), req.user);
if (req.isAuthenticated())
return next();
// If not return 401 response which means unauthroized.
var err = new Error();
err.status = 401;
next(err);
}
As Charles Duffey has stated, XML parsers are best parsed with a proper XML parsing tools. For one time job the following should work.
grep -oPm1 "(?<=<title>)[^<]+"
$ echo "$data"
<item>
<title>15:54:57 - George:</title>
<description>Diane DeConn? You saw Diane DeConn!</description>
</item>
<item>
<title>15:55:17 - Jerry:</title>
<description>Something huh?</description>
$ title=$(grep -oPm1 "(?<=<title>)[^<]+" <<< "$data")
$ echo "$title"
15:54:57 - George:
If I understand you correctly you are asking about including nested properties. If so :
.Include(x => x.ApplicationsWithOverrideGroup.NestedProp)
or
.Include("ApplicationsWithOverrideGroup.NestedProp")
or
.Include($"{nameof(ApplicationsWithOverrideGroup)}.{nameof(NestedProp)}")
You can only change the language on the whole server, not individual databases. However if you need to support the UK you can run the following command before all inputs and outputs:
set language 'british english'
Or if you are having issues entering datatimes from your application you might want to consider a universal input type such as
1-Dec-2008
I got the error as, "svn: Commit blocked by pre-commit hook (exit code 1) with output: Failed with exception: Lost connection to MySQL server at 'reading initial communication packet', system error: 104."
I tried 'svn commit' after 'svn cleanup'. And It works fine!.
web.xml
they are in the servlet container configuration files (server.xml
on tomcat)No. But the default servlet (mapped in a web.xml at a common location in your servlet container) should preferably disable file listings (so that users don't see the contents of your web folders):
listings true
Look here.
Basically you have to do bind params:
$sql = "SELECT username FROM users WHERE locationid IN (SELECT locationid FROM locations WHERE countryid=?)";
$this->db->query($sql, '__COUNTRY_NAME__');
But, like Mr.E said, use joins:
$sql = "select username from users inner join locations on users.locationid = locations.locationid where countryid = ?";
$this->db->query($sql, '__COUNTRY_NAME__');
startup chrome with --disable-web-security
On Windows:
chrome.exe --disable-web-security
On Mac:
open /Applications/Google\ Chrome.app/ --args --disable-web-security
This will allow for cross-domain requests.
I'm not aware of if this also works for local files, but let us know !
And mention, this does exactly what you expect, it disables the web security, so be careful with it.
use this function to get the capture image path
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Uri mImageCaptureUri = intent.getData();
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
knop.setVisibility(Button.VISIBLE);
System.out.println(mImageCaptureUri);
//getImgPath(mImageCaptureUri);// it will return the Capture image path
}
}
public String getImgPath(Uri uri) {
String[] largeFileProjection = { MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA };
String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
Cursor myCursor = this.managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
largeFileProjection, null, null, largeFileSort);
String largeImagePath = "";
try {
myCursor.moveToFirst();
largeImagePath = myCursor
.getString(myCursor
.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
} finally {
myCursor.close();
}
return largeImagePath;
}
Interestingly, if you're just typing at the python interactive interpreter, you have to follow a function with a blank line. This does not work:
def foo(x):
return x+1
print "last"
although it is perfectly legal python syntax in a file. There are other syntactic differences when typing to the interpreter too, so beware.
I think you can put it like this.
var a = "10:20:45";_x000D_
var b = "5:10:10";_x000D_
_x000D_
var timeA = new Date();_x000D_
timeA.setHours(a.split(":")[0],a.split(":")[1],a.split(":")[2]);_x000D_
timeB = new Date();_x000D_
timeB.setHours(b.split(":")[0],b.split(":")[1],b.split(":")[2]);_x000D_
_x000D_
var x= "B is later than A";_x000D_
if(timeA>timeB) x = "A is later than B";_x000D_
document.getElementById("demo").innerHTML = x;
_x000D_
<p id="demo"></p>
_x000D_
Expanding on patszim's answer for those in a rush.
add the following code:
Function RegxFunc(strInput As String, regexPattern As String) As String
Dim regEx As New RegExp
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.pattern = regexPattern
End With
If regEx.Test(strInput) Then
Set matches = regEx.Execute(strInput)
RegxFunc = matches(0).Value
Else
RegxFunc = "not matched"
End If
End Function
The regex pattern is placed in one of the cells and absolute referencing is used on it.
Function will be tied to workbook that its created in.
If there's a need for it to be used in different workbooks, store the function in Personal.XLSB
LinkedIn has updated their api and the sharing url's no longer works. Now you can only use the url
query parameter. Any other parameter is going to be removed from the url by LinkedIn.
Now you're forced to use oAuth and interact with the linkedin API to share content on behalf of a user.
mysqladmin version
OR mysqladmin -V
In such cases, you can convert the values of enum to a List and stream through it. Something like below examples. I would recommend using filter().
Using ForEach:
List<Category> category = Arrays.asList(Category.values());
category.stream().forEach(eachCategory -> {
if(eachCategory.toString().equals("3")){
String name = eachCategory.name();
}
});
Or, using Filter:
When you want to find with code:
List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.toString().equals("3")).findAny().orElse(null);
System.out.println(category.toString() + " " + category.name());
When you want to find with name:
List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.name().equals("Apple")).findAny().orElse(null);
System.out.println(category.toString() + " " + category.name());
Hope it helps! I know this is a very old post, but someone can get help.
The web.xml
file is the deployment descriptor for a Servlet-based Java web application (which most Java web apps are). Among other things, it declares which Servlets exist and which URLs they handle.
The part you cite defines a Servlet Filter. Servlet filters can do all kinds of preprocessing on requests. Your specific example is a filter had the Wicket framework uses as its entry point for all requests because filters are in some way more powerful than Servlets.
dictionary['key'] = dictionary.get('key', []) + list_to_append
I resorted to creating 2 style cascades using inline-block for input that pretty much override the field:
.input-sm {
height: 2.1em;
display: inline-block;
}
and a series of fixed sizes as opposed to %
.input-10 {
width: 10em;
}
.input-32 {
width: 32em;
}
I collected some information on the internet and prepared the script that requires no external tool: See my response here. Hope it's helpful.