Up front .. I am a Hudson committer and author of the Hudson book, but I was not involved in the whole split of the projects.
In any case here is my advice:
Check out both and see what fits your needs better.
Hudson is going to complete the migration to be a top level Eclipse projects later this year and has gotten a whole bunch of full time developers, QA and others working on the project. It is still going strong and has a lot of users and with being the default CI server at Eclipse it will continue to serve the needs of many Java developers. Looking at the roadmap and plans for the future you can see that after the Maven 3 integration accomplished with the 2.1.0 release a whole bunch of other interesting feature are ahead.
Jenkins on the other side has won over many original Hudson users and has a large user community across multiple technologies and also has a whole bunch of developers working on it.
At this stage both CI servers are great tools to use and depending on your needs in terms of technology to integrate with one or the other might be better. Both products are available as open source and you can get commercial support from various companies for both.
In any case .. if you are not using a CI server yet.. start now with either of them and you will see huge benefits.
Update Jan 2013: After a long process of IP cleanup and further improvements Hudson 3.0 as the first Eclipse foundation approved release is now available.
I have same problem but in my case By mistake I added a context in server.xml ($Tomcat_Install_Dir/conf/) and doesn't deployed corresponing war in webapps($Tomcat_Install_Dir/webapps). As I removed that context and restarted tomcat it working fine.
Check if these free resources fit your need -
I think is this a very simple way with regards to all solutions above:
const elm = document.getElementById("myElement")
const allMyStyle = [
{ prop: "position", value: "fixed" },
{ prop: "boxSizing", value: "border-box" },
{ prop: "opacity", value: 0.9 },
{ prop: "zIndex", value: 1000 },
];
allMyStyle.forEach(({ prop, value }) => {
elm.style[prop] = value;
});
Just to be crystal clear, this works nicely with paragraphs and headers etc. You just need to specify display: block
.
For instance:
<h5 style="display: block; text-overflow: ellipsis; white-space: nowrap; overflow: hidden">
This is a really long title, but it won't exceed the parent width
</h5>
(forgive the inline styles)
Overriding and Return Types, and Covariant Returns
the subclass must define a method that matches the inherited version exactly. Or, as of Java 5, you're allowed to change the return type in the
class Alpha {
Alpha doStuff(char c) {
return new Alpha();
}
}
class Beta extends Alpha {
Beta doStuff(char c) { // legal override in Java 1.5
return new Beta();
}
} }
As of Java 5, this code will compile. If you were to attempt to compile this code with a 1.4 compiler will say attempting to use incompatible return type – sandeep1987 1 min ago
The answer is right in the MYSQL manual itself.
"DELETE FROM `table_name` WHERE `time_col` < ADDDATE(NOW(), INTERVAL -1 HOUR)"
Image.onload() will often work.
To use it, you'll need to be sure to bind the event handler before you set the src attribute.
Related Links:
Example Usage:
window.onload = function () {_x000D_
_x000D_
var logo = document.getElementById('sologo');_x000D_
_x000D_
logo.onload = function () {_x000D_
alert ("The image has loaded!"); _x000D_
};_x000D_
_x000D_
setTimeout(function(){_x000D_
logo.src = 'https://edmullen.net/test/rc.jpg'; _x000D_
}, 5000);_x000D_
};
_x000D_
<html>_x000D_
<head>_x000D_
<title>Image onload()</title>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<img src="#" alt="This image is going to load" id="sologo"/>_x000D_
_x000D_
<script type="text/javascript">_x000D_
_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
Simplest bullet-and-fool-proof way of doing a complete rename (including dropping the old database at the end so it's a rename rather than a copy):
mysqladmin -uroot -pmypassword create newdbname
mysqldump -uroot -pmypassword --routines olddbname | mysql -uroot -pmypassword newdbname
mysqladmin -uroot -pmypassword drop olddbname
Steps:
React has a concept of components state, so if you want to switch it, do a setState
:
constructor(props) {
super(props);
this.addActiveClass= this.addActiveClass.bind(this);
this.state = {
isActive: false
}
}
addActiveClass() {
this.setState({
isActive: true
})
}
In your component use this.state.isActive
to render what you need.
This gets more complicated when you want to set state in component#1 and use it in component#2. Just dig more into react unidirectional data flow and possibly redux that will help you handle it.
select top(3) min(Name),TotalSalary,ROW_NUMBER() OVER (Order by TotalSalary desc) AS RowNumber FROM tbl_EmployeeProfile group by TotalSalary
<div class="post_category">
<?php $category = get_the_category();
$allcategory = get_the_category();
foreach ($allcategory as $category) {
?>
<a class="btn"><?php echo $category->cat_name;; ?></a>
<?php
}
?>
</div>
Codeproject has a complete solution for this:
http://www.codeproject.com/Articles/17241/Capturing-the-Enter-key-to-cause-a-button-click
and like the article says: "decide which solution best fits your needs"
=================== EDITED ANSWER ============================
The link mentioned above, talks about two ways of capturing the "Enter Key" event:
Javascript (bind the onKeyPress event to the object and create a javascript function to check which key was pressed and do your logic)
_Page_Load in code behind:_
//Add the javascript so we know where we want the enter key press to go
if (!IsPostBack)
{
txtboxFirstName.Attributes.Add("onKeyPress",
"doClick('" + btnSearch.ClientID + "',event)");
txtboxLastName.Attributes.Add("onKeyPress",
"doClick('" + btnSearch.ClientID + "',event)");
}
Javascript code:
<SCRIPT type=text/javascript>
function doClick(buttonName,e)
{
//the purpose of this function is to allow the enter key to
//point to the correct button to click.
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
if (key == 13)
{
//Get the button the user wants to have clicked
var btn = document.getElementById(buttonName);
if (btn != null)
{ //If we find the button click it
btn.click();
event.keyCode = 0
}
}
}
</SCRIPT>
Panel Control
<asp:Panel ID="panSearch" runat="server" DefaultButton="btnSearch2" Width="100%" >
<asp:TextBox ID="txtboxFirstName2" runat="server" ></asp:TextBox>
</asp:Panel>
Quoting:
Notice that the Panel tag has a property called DefaultButton. You set this property to the button ID of the button you want to be clicked on an Enter key press event. So any text box inside of the Panel will direct its Enter key press to the button set in the DefaultButton property of the Panel
As this is specifically tagged for jQuery -
$("#myElement")[0].getBoundingClientRect();
or
$("#myElement").get(0).getBoundingClientRect();
(These are functionally identical, in some older browsers .get()
was slightly faster)
Note that if you try to get the values via jQuery calls then it will not take into account any css transform values, which can give unexpected results...
Note 2: In jQuery 3.0 it has changed to using the proper getBoundingClientRect()
calls for its own dimension calls (see the jQuery Core 3.0 Upgrade Guide) - which means that the other jQuery answers will finally always be correct - but only when using the new jQuery version - hence why it's called a breaking change...
Git is just trying to guess for you what you are trying to do. It is making every attempt to preserve unbroken history. Of course, it is not perfect. So git mv
allows you to be explicit with your intention and to avoid some errors.
Consider this example. Starting with an empty repo,
git init
echo "First" >a
echo "Second" >b
git add *
git commit -m "initial commit"
mv a c
mv b a
git status
Result:
# On branch master
# Changes not staged for commit:
# (use "git add/rm <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified: a
# deleted: b
#
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
#
# c
no changes added to commit (use "git add" and/or "git commit -a")
Autodetection failed :( Or did it?
$ git add *
$ git commit -m "change"
$ git log c
commit 0c5425be1121c20cc45df04734398dfbac689c39
Author: Sergey Orshanskiy <*****@gmail.com>
Date: Sat Oct 12 00:24:56 2013 -0400
change
and then
$ git log --follow c
Author: Sergey Orshanskiy <*****@gmail.com>
Date: Sat Oct 12 00:24:56 2013 -0400
change
commit 50c2a4604a27be2a1f4b95399d5e0f96c3dbf70a
Author: Sergey Orshanskiy <*****@gmail.com>
Date: Sat Oct 12 00:24:45 2013 -0400
initial commit
Now try instead (remember to delete the .git
folder when experimenting):
git init
echo "First" >a
echo "Second" >b
git add *
git commit -m "initial commit"
git mv a c
git status
So far so good:
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# renamed: a -> c
git mv b a
git status
Now, nobody is perfect:
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# modified: a
# deleted: b
# new file: c
#
Really? But of course...
git add *
git commit -m "change"
git log c
git log --follow c
...and the result is the same as above: only --follow
shows the full history.
Now, be careful with renaming, as either option can still produce weird effects. Example:
git init
echo "First" >a
git add a
git commit -m "initial a"
echo "Second" >b
git add b
git commit -m "initial b"
git mv a c
git commit -m "first move"
git mv b a
git commit -m "second move"
git log --follow a
commit 81b80f5690deec1864ebff294f875980216a059d
Author: Sergey Orshanskiy <*****@gmail.com>
Date: Sat Oct 12 00:35:58 2013 -0400
second move
commit f284fba9dc8455295b1abdaae9cc6ee941b66e7f
Author: Sergey Orshanskiy <*****@gmail.com>
Date: Sat Oct 12 00:34:54 2013 -0400
initial b
Contrast it with:
git init
echo "First" >a
git add a
git commit -m "initial a"
echo "Second" >b
git add b
git commit -m "initial b"
git mv a c
git mv b a
git commit -m "both moves at the same time"
git log --follow a
Result:
commit 84bf29b01f32ea6b746857e0d8401654c4413ecd
Author: Sergey Orshanskiy <*****@gmail.com>
Date: Sat Oct 12 00:37:13 2013 -0400
both moves at the same time
commit ec0de3c5358758ffda462913f6e6294731400455
Author: Sergey Orshanskiy <*****@gmail.com>
Date: Sat Oct 12 00:36:52 2013 -0400
initial a
Ups... Now the history is going back to initial a instead of initial b, which is wrong. So when we did two moves at a time, Git became confused and did not track the changes properly. By the way, in my experiments the same happened when I deleted/created files instead of using git mv
. Proceed with care; you've been warned...
If you have python various versions of python installed,you can launch any of them using pythonx.x.x
where x.x.x
represents your versions.
Haven't needed this much yet, but when I've used console application for Quick tests and required async I've just solved it like this:
class Program
{
static void Main(string[] args)
{
MainAsync(args).Wait();
}
static async Task MainAsync(string[] args)
{
// Code here
}
}
You set these configs either in the /etc/ansible/ansible.cfg
or ~/.ansible.cfg
or ansible.cfg
(in your current directory) file
[ssh_connection]
ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no
tested with ansible 2.9.6 in ubuntu 20.04
std::string::data
would seem to be sufficient and most efficient. If you want to have non-const memory to manipulate (strange for encryption) you can copy the data to a buffer using memcpy:
unsigned char buffer[mystring.length()];
memcpy(buffer, mystring.data(), mystring.length());
STL fanboys would encourage you to use std::copy instead:
std::copy(mystring.begin(), mystring.end(), buffer);
but there really isn't much of an upside to this. If you need null termination use std::string::c_str()
and the various string duplication techniques others have provided, but I'd generally avoid that and just query for the length
. Particularly with cryptography you just know somebody is going to try to break it by shoving nulls in to it, and using std::string::data()
discourages you from lazily making assumptions about the underlying bits in the string.
server.session.timeout=1200
server.servlet.session.timeout=10m
Assuming you still want to get the URL without the query args (if they are not set), just use a shorthand if statement to check with strpos
:
$request_uri = strpos( $_SERVER['REQUEST_URI'], '?' ) !== false ? strtok( $_SERVER["REQUEST_URI"], '?' ) : $_SERVER['REQUEST_URI'];
Just found this version of 3d noise for GPU, alledgedly it is the fastest one available:
#ifndef __noise_hlsl_
#define __noise_hlsl_
// hash based 3d value noise
// function taken from https://www.shadertoy.com/view/XslGRr
// Created by inigo quilez - iq/2013
// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
// ported from GLSL to HLSL
float hash( float n )
{
return frac(sin(n)*43758.5453);
}
float noise( float3 x )
{
// The noise function returns a value in the range -1.0f -> 1.0f
float3 p = floor(x);
float3 f = frac(x);
f = f*f*(3.0-2.0*f);
float n = p.x + p.y*57.0 + 113.0*p.z;
return lerp(lerp(lerp( hash(n+0.0), hash(n+1.0),f.x),
lerp( hash(n+57.0), hash(n+58.0),f.x),f.y),
lerp(lerp( hash(n+113.0), hash(n+114.0),f.x),
lerp( hash(n+170.0), hash(n+171.0),f.x),f.y),f.z);
}
#endif
This will work on SQL SERVER...
SELECT COL_LENGTH('Table', 'Column')
You can use following :
<p id="p1">Some Text here </p>
#p1{
font-weight: bold;
}
OR
<Strong><p>Some text here </p></strong>
OR
You can use <h1> tag
which is somewhat similar to bold
use this it works for me: "order": [[ 1, "ASC" ]],
For a single boxplot:
import seaborn as sb
sb.boxplot(data=Array).set_title('Title')
For more boxplot in the same plot:
import seaborn as sb
sb.boxplot(data=ArrayofArray).set_title('Title')
e.g.
import seaborn as sb
myarray=[78.195229, 59.104538, 19.884109, 25.941648, 72.234825, 82.313911]
sb.boxplot(data=myarray).set_title('myTitle')
"bad enough not having a traditional for(;;) looper"?? What?
Are you trying to do
import string
for c in string.lowercase:
...do something with c...
Or perhaps you're using string.uppercase
or string.letters
?
Python doesn't have for(;;)
because there are often better ways to do it. It also doesn't have character math because it's not necessary, either.
From here, you can do this:
/* Extend jQuery with functions for PUT and DELETE requests. */
function _ajax_request(url, data, callback, type, method) {
if (jQuery.isFunction(data)) {
callback = data;
data = {};
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
}
jQuery.extend({
put: function(url, data, callback, type) {
return _ajax_request(url, data, callback, type, 'PUT');
},
delete_: function(url, data, callback, type) {
return _ajax_request(url, data, callback, type, 'DELETE');
}
});
It's basically just a copy of $.post()
with the method parameter adapted.
var full_address = req.protocol + "://" + req.headers.host + req.originalUrl;
or
var full_address = req.protocol + "://" + req.headers.host + req.baseUrl;
y={'username':'admin','machine':['a','b','c']}
if 'c' in y['machine'] : del y['machine'][y['machine'].index('c')]
If you're doing this to several fields, or doing it quite often, then perhaps a plugin is the answer.
Here's the beginnings of a jQuery plugin that formats the value of a field to two decimal places.
It is triggered by the onchange event of the field. You may want something different.
<script type="text/javascript">
// mini jQuery plugin that formats to two decimal places
(function($) {
$.fn.currencyFormat = function() {
this.each( function( i ) {
$(this).change( function( e ){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(2);
});
});
return this; //for chaining
}
})( jQuery );
// apply the currencyFormat behaviour to elements with 'currency' as their class
$( function() {
$('.currency').currencyFormat();
});
</script>
<input type="text" name="one" class="currency"><br>
<input type="text" name="two" class="currency">
the shortest way for me is
file=filename_or_filepath;uuencode $file $file|mail -s "optional subject" email_address
so for your example it'll be
file=your_sql.log;gzip -c $file;uuencode ${file}.gz ${file}|mail -s "file with magnets" [email protected]
the good part is that I can recall it with Ctrl+r to send another file...
When a constructor is invoked, although there is no object created till that point, we still know the kind of object that is gonna be created because the specific constructor of the class to which the object belongs to has already been called.
Virtual
keyword associated with a function means the function of a particular object type is gonna be called.
So, my thinking says that there is no need to make the virtual constructor because already the desired constructor whose object is gonna be created has been invoked and making constructor virtual is just a redundant thing to do because the object-specific constructor has already been invoked and this is same as calling class-specific function which is achieved through the virtual keyword.
Although the inner implementation won’t allow virtual constructor for vptr and vtable related reasons.
Another reason is that C++ is a statically typed language and we need to know the type of a variable at compile-time.
The compiler must be aware of the class type to create the object. The type of object to be created is a compile-time decision.
If we make the constructor virtual then it means that we don’t need to know the type of the object at compile-time(that’s what virtual function provide. We don’t need to know the actual object and just need the base pointer to point an actual object call the pointed object’s virtual functions without knowing the type of the object) and if we don’t know the type of the object at compile time then it is against the statically typed languages. And hence, run-time polymorphism cannot be achieved.
Hence, Constructor won’t be called without knowing the type of the object at compile-time. And so the idea of making a virtual constructor fails.
Crawlers (or bots) are designed to crawl HTML content of web pages but due to AJAX operations for asynchronous data fetching, this became a problem as it takes sometime to render page and show dynamic content on it. Similarly, AngularJS
also use asynchronous model, which creates problem for Google crawlers.
Some developers create basic html pages with real data and serve these pages from server side at the time of crawling. We can render same pages with PhantomJS
on serve side which has _escaped_fragment_
(Because Google looks for #!
in our site urls and then takes everything after the #!
and adds it in _escaped_fragment_
query parameter). For more detail please read this blog .
To remove all columns after the one you want, below code should work. It will remove at index 10 (remember Columns are 0 based), until the Column count is 10 or less.
DataTable dt;
int desiredSize = 10;
while (dt.Columns.Count > desiredSize)
{
dt.Columns.RemoveAt(desiredSize);
}
i always use this cheap word for vertical spaces.
<p>Q1</p>
<br>
<p>Q2</p>
It is a bad idea to select * from anything, period. This is why SSMS adds every field name, even if there are hundreds, instead of select *. It is extremely inefficient regardless of how large the table is. If you don't know what the fields are, its still more efficient to pull them out of the INFORMATION_SCHEMA database than it is to select *.
A better query would be:
SELECT
COLUMN_NAME,
Case
When DATA_TYPE In ('varchar', 'char', 'nchar', 'nvarchar', 'binary')
Then convert(varchar(MAX), CHARACTER_MAXIMUM_LENGTH)
When DATA_TYPE In ('numeric', 'int', 'smallint', 'bigint', 'tinyint')
Then convert(varchar(MAX), NUMERIC_PRECISION)
When DATA_TYPE = 'bit'
Then convert(varchar(MAX), 1)
When DATA_TYPE IN ('decimal', 'float')
Then convert(varchar(MAX), Concat(Concat(NUMERIC_PRECISION, ', '), NUMERIC_SCALE))
When DATA_TYPE IN ('date', 'datetime', 'smalldatetime', 'time', 'timestamp')
Then ''
End As DATALEN,
DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
Where
TABLE_NAME = ''
newaxis
object in the selection tuple serves to expand the dimensions of the resulting selection by one unit-length dimension.
It is not just conversion of row matrix to column matrix.
Consider the example below:
In [1]:x1 = np.arange(1,10).reshape(3,3)
print(x1)
Out[1]: array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
Now lets add new dimension to our data,
In [2]:x1_new = x1[:,np.newaxis]
print(x1_new)
Out[2]:array([[[1, 2, 3]],
[[4, 5, 6]],
[[7, 8, 9]]])
You can see that newaxis
added the extra dimension here, x1 had dimension (3,3) and X1_new has dimension (3,1,3).
How our new dimension enables us to different operations:
In [3]:x2 = np.arange(11,20).reshape(3,3)
print(x2)
Out[3]:array([[11, 12, 13],
[14, 15, 16],
[17, 18, 19]])
Adding x1_new and x2, we get:
In [4]:x1_new+x2
Out[4]:array([[[12, 14, 16],
[15, 17, 19],
[18, 20, 22]],
[[15, 17, 19],
[18, 20, 22],
[21, 23, 25]],
[[18, 20, 22],
[21, 23, 25],
[24, 26, 28]]])
Thus, newaxis
is not just conversion of row to column matrix. It increases the dimension of matrix, thus enabling us to do more operations on it.
Another shortcut way to do this is press Ctrl+Shift+L and select which command you want to perform and hit enter
its best practice for beginner.
Don't know exactly what kind of dataset you have, so I provide general answer.
x <- c(1,2,NA,3,4,5)
y <- c(1,2,3,NA,6,8)
my.data <- data.frame(x, y)
> my.data
x y
1 1 1
2 2 2
3 NA 3
4 3 NA
5 4 6
6 5 8
# Exclude rows with NA values
my.data[complete.cases(my.data),]
x y
1 1 1
2 2 2
5 4 6
6 5 8
Just a little tip for the first answer. If your function is already defined, reference the function but don't call it!!! So don't put any parentheses after the function name. Just like:
my_function(){};
setInterval(my_function,10000);
For this purpose I would suggest just do the following thing -
int(round(x))
This will give you nearest integer.
Hope this helps!!
Although the given list comprehension / generator expression answers are ok, I find this easier to read and understand:
values = ','.join(map(str, value_list))
So many way to achieve this task some are below:-
1.
String text_view_str = "<b>Bolded text</b>, <i>italic text</i>, even <u>underlined</u>!";
TextView tv = (TextView)findViewById(R.id.ur_text_view_id);
tv.setText(Html.fromHtml(text_view_str));
2.
tv.setTypeface(null, Typeface.BOLD);
tv.setTypeface(null, Typeface.ITALIC);
tv.setTypeface(null, Typeface.BOLD_ITALIC);
tv.setTypeface(null, Typeface.NORMAL);
3.
SpannableString spannablecontent=new SpannableString(o.content.toString());
spannablecontent.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC),
0,spannablecontent.length(), 0);
// set Text here
tt.setText(spannablecontent);
4.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="boldText">
<item name="android:textStyle">bold|italic</item>
<item name="android:textColor">#FFFFFF</item>
</style>
<style name="normalText">
<item name="android:textStyle">normal</item>
<item name="android:textColor">#C0C0C0</item>
</style>
</resources>
tv.setTextAppearance(getApplicationContext(), R.style.boldText);
or if u want through xml
android:textStyle="normal"
android:textStyle="normal|bold"
android:textStyle="normal|italic"
android:textStyle="bold"
android:textStyle="bold|italic"
Try below:
let image = UIImage(named: "ImageName.png") as UIImage
var button = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.frame = CGRectMake(100, 100, 100, 100)
button .setBackgroundImage(image, forState: UIControlState.Normal)
button.addTarget(self, action: "Action:", forControlEvents:UIControlEvents.TouchUpInside)
menuView.addSubview(button)
Let me know whether if it works or not?
Use @SessionAttributes
See the docs: Using @SessionAttributes to store model attributes in the HTTP session between requests
"Understanding Spring MVC Model And Session Attributes" also gives a very good overview of Spring MVC sessions and explains how/when @ModelAttribute
s are transferred into the session (if the controller is @SessionAttributes
annotated).
That article also explains that it is better to use @SessionAttributes
on the model instead of setting attributes directly on the HttpSession because that helps Spring MVC to be view-agnostic.
Assume the date as milliseconds date is 1526813885836
, so you can access the date as string with this sample code:
console.log(new Date(1526813885836).toString());
For clearness see below code:
const theTime = new Date(1526813885836);
console.log(theTime.toString());
You are calling nextInt
statically by using Random.nextInt
.
Instead, create a variable, Random r = new Random();
and then call r.nextInt(10)
.
It would be definitely worth while to check out:
You really should replace this line,
Random Random = new Random();
with something like this,
Random r = new Random();
If you use variable names as class names you'll run into a boat load of problems. Also as a Java convention, use lowercase names for variables. That might help avoid some confusion.
The Pixastic library does exactly what you want. However, it will only work on browsers that have canvas support. For those older browsers, you'll either need to:
Of course, option #2 isn't very user-friendly. However, if your intent is to provide a pure client-only tool and/or you can't support a fallback back-end cropper (e.g. maybe you're writing a browser extension or offline Chrome app, or maybe you can't afford a decent hosting provider that provides image manipulation libraries), then it's probably fair to limit your user base to modern browsers.
EDIT: If you don't want to learn Pixastic, I have added a very simple cropper on jsFiddle here. It should be possible to modify and integrate and use the drawCroppedImage
function with Jcrop.
For the sake of completeness, isinstance will not work for type checking of a subtype that is not an instance. While that makes perfect sense, none of the answers (including the accepted one) covers it. Use issubclass for that.
>>> class a(list):
... pass
...
>>> isinstance(a, list)
False
>>> issubclass(a, list)
True
Here is an alternative method that worked for me without having to create a DirectoryInfo object. The key point is that GetFileName()
works when there is no trailing slash in the path.
var name = Path.GetFileName(path.TrimEnd(Path.DirectorySeparatorChar));
Example:
var list = Directory.EnumerateDirectories(path, "*")
.Select(p => new
{
id = "id_" + p.GetHashCode().ToString("x"),
text = Path.GetFileName(p.TrimEnd(Path.DirectorySeparatorChar)),
icon = "fa fa-folder",
children = true
})
.Distinct()
.OrderBy(p => p.text);
try this:
asort($array_to_sort, SORT_NUMERIC);
for reference see this: http://php.net/manual/en/function.asort.php
see various sort flags here: http://www.php.net/manual/en/function.sort.php
am using this simple one
´´´´ class Connect {
public $url;
public $path;
public $username;
public $password;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, "$this->username:$this->password");
//PROPFIND request that lists all requested properties.
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PROPFIND");
$response = curl_exec($ch);
curl_close($ch);
Was able to fix the issue by updating NVIDIA device drivers to the latest (v446.14). NVIDIA drivers download link here.
Add both javax.servlet.jsp.jstl-api-1.2.1.jar and standard-1.1.2.jar
Command line arguments is one way to pass the arguments in. This msdn sample is worth checking out. The MSDN Page for command line arguments is also worth reading.
From within visual studio you can set the command line arguments by Choosing the properties of your console application then selecting the Debug tab
Try this:
public void ringtone(){
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
You can implement this way
$resource('http://localhost\\:3000/realmen/:entryId', {entryId: '@entryId'}, {
UPDATE: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId' },
ACTION: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId/action' }
})
RealMen.query() //GET /realmen/
RealMen.save({entryId: 1},{post data}) // POST /realmen/1
RealMen.delete({entryId: 1}) //DELETE /realmen/1
//any optional method
RealMen.UPDATE({entryId:1}, {post data}) // PUT /realmen/1
//query string
RealMen.query({name:'john'}) //GET /realmen?name=john
Documentation: https://docs.angularjs.org/api/ngResource/service/$resource
Hope it helps
You can use:
System.Text.Encoding.ASCII.GetString(buf);
But sometimes you will get a weird number instead of the string you want. In that case, your original string may have some hexadecimal character when you see it. If it's the case, you may want to try this:
System.Text.Encoding.UTF8.GetString(buf);
Or as a last resort:
System.Text.Encoding.Default.GetString(bytearray);
They don't have the same structure... I can guarantee they are different
I know you've already created it... There is already an object named ‘tbltable1’ in the database
What you may want is this (which also fixes your other issue):
Drop table tblTable1
select * into tblTable1 from tblTable1_Link
append
returns None, so at the second iteration you are calling method append
of NoneType. Just remove the assignment:
for i in range(0, n):
list1.append([i])
Simple Oriented Object solution
$file = new \SplFileObject('file.extension');
while($file->valid()) $file->fgets();
var_dump($file->key());
Another way to make this is with PHP_INT_MAX
in SplFileObject::seek
method.
$file = new \SplFileObject('file.extension', 'r');
$file->seek(PHP_INT_MAX);
echo $file->key() + 1;
Here is another function that works great for me, returns distance in kilometers:
function distance(lat1, lng1, lat2, lng2) {
var radlat1 = Math.PI * lat1 / 180;
var radlat2 = Math.PI * lat2 / 180;
var radlon1 = Math.PI * lng1 / 180;
var radlon2 = Math.PI * lng2 / 180;
var theta = lng1 - lng2;
var radtheta = Math.PI * theta / 180;
var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
dist = Math.acos(dist);
dist = dist * 180 / Math.PI;
dist = dist * 60 * 1.1515;
//Get in in kilometers
dist = dist * 1.609344;
return dist;
}
You can use window.location.reload();
in your componentDidMount()
lifecycle method. If you are using react-router
, it has a refresh method to do that.
Edit: If you want to do that after a data update, you might be looking to a re-render
not a reload
and you can do that by using this.setState(). Here is a basic example of it to fire a re-render
after data is fetched.
import React from 'react'
const ROOT_URL = 'https://jsonplaceholder.typicode.com';
const url = `${ROOT_URL}/users`;
class MyComponent extends React.Component {
state = {
users: null
}
componentDidMount() {
fetch(url)
.then(response => response.json())
.then(users => this.setState({users: users}));
}
render() {
const {users} = this.state;
if (users) {
return (
<ul>
{users.map(user => <li>{user.name}</li>)}
</ul>
)
} else {
return (<h1>Loading ...</h1>)
}
}
}
export default MyComponent;
Tracking branches are local branches that have a direct relationship to a remote branch
Not exactly. The SO question "Having a hard time understanding git-fetch
" includes:
There's no such concept of local tracking branches, only remote tracking branches.
Soorigin/master
is a remote tracking branch formaster
in theorigin
repo.
But actually, once you establish an upstream branch relationship between:
master
origin/master
Then you can consider master
as a local tracking branch: It tracks the remote tracking branch origin/master
which, in turn, tracks the master branch of the upstream repo origin
.
This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End
and End Sub
are not the same. They don't perform the same task.
End
puts a stop to ALL code execution and you should almost always use Exit Sub
(or Exit Function
, respectively).
End halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)
See also the MSDN dox for the End Statement
When executed, the
End
statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use theStop
statement instead. You can then resume execution while preserving the value of those variables.Note The
End
statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.
Nor is End Sub
and Exit Sub
the same. End Sub
can't be called in the same way Exit Sub
can be, because the compiler doesn't allow it.
This again means you have to Exit Sub
, which is a perfectly legal operation:
Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.
Additionally, and once you get the feel for how procedures work, obviously, End Sub
does not clear any global variables. But it does clear local (Dim'd) variables:
End Sub
Terminates the definition of this procedure.
What I did when trying to send some data from several selected rows in DataTable to MVC action:
HTML At the beginning of a page:
@Html.AntiForgeryToken()
(just a row is shown, bind from model):
@foreach (var item in Model.ListOrderLines)
{
<tr data-orderid="@item.OrderId" data-orderlineid="@item.OrderLineId" data-iscustom="@item.IsCustom">
<td>@item.OrderId</td>
<td>@item.OrderDate</td>
<td>@item.RequestedDeliveryDate</td>
<td>@item.ProductName</td>
<td>@item.Ident</td>
<td>@item.CompanyName</td>
<td>@item.DepartmentName</td>
<td>@item.ProdAlias</td>
<td>@item.ProducerName</td>
<td>@item.ProductionInfo</td>
</tr>
}
Button which starts the JavaScript function:
<button class="btn waves-effect waves-light btn-success" onclick="ProcessMultipleRows();">Start</button>
JavaScript function:
function ProcessMultipleRows() {
if ($(".dataTables_scrollBody>tr.selected").length > 0) {
var list = [];
$(".dataTables_scrollBody>tr.selected").each(function (e) {
var element = $(this);
var orderid = element.data("orderid");
var iscustom = element.data("iscustom");
var orderlineid = element.data("orderlineid");
var folderPath = "";
var fileName = "";
list.push({ orderId: orderid, isCustomOrderLine: iscustom, orderLineId: orderlineid, folderPath: folderPath, fileName : fileName});
});
$.ajax({
url: '@Url.Action("StartWorkflow","OrderLines")',
type: "post", //<------------- this is important
data: { model: list }, //<------------- this is important
beforeSend: function (xhr) {//<--- This is important
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
showPreloader();
},
success: function (data) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
complete: function () {
hidePreloader();
}
});
}
}
MVC action:
[HttpPost]
[ValidateAntiForgeryToken] //<--- This is important
public async Task<IActionResult> StartWorkflow(IEnumerable<WorkflowModel> model)
And MODEL in C#:
public class WorkflowModel
{
public int OrderId { get; set; }
public int OrderLineId { get; set; }
public bool IsCustomOrderLine { get; set; }
public string FolderPath { get; set; }
public string FileName { get; set; }
}
CONCLUSION:
The reason for ERROR:
"Failed to load resource: the server responded with a status of 400 (Bad Request)"
Is attribute: [ValidateAntiForgeryToken]
for the MVC action StartWorkflow
Solution in Ajax call:
beforeSend: function (xhr) {//<--- This is important
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
To send List of objects you need to form data like in example (populating list object) and:
data: { model: list },
type: "post",
I also had this problem when trying to connect remotely via the Hamachi VPN. I had tried everything available on the internet (including this post) and it still did not work. Note that everything worked fine when the same database was installed on a machine on my local network. Finally I was able to achieve success using the following fix: on the remote machine, enable the IP address on the TCP/IP protocol, like so:
On the remote machine, start SQL Server Configuration Manager, expand SQL Server Network Configuration, select "Protocols for SQLEXPRESS" (or "MSSQLSERVER"), right-click on TCP/IP, on the resulting dialog box go to the IP Addresses tab, and make sure the "IP1" element is Active=Yes
and Enabled=Yes
. Make note of the IP address (for me it wasn't necessary to modify these). Then stop and start the SQL Server Services. After that, ensure that the firewall on the remote machine is either disabled, or an exception is allowed for port 1433 that includes both the local subnet and the subnet for the address noted in the previous dialog box. On your local machine you should be able to connect by setting the server name to 192.168.1.22\SQLEXPRESS
(or [ip address of remote machine]\[SQL server instance name]
).
Hope that helps.
4+ years later after the original reply in 2015, virtualbox.org now offers an official user manual in both html and pdf formats, which effectively deprecates the previous version of this answer:
Because there isn't an official answer yet and I literally just did this for my OS X/WinXP install, here's what I did:
Hope that helps.
The only case I could imagine is, that you run this on a webkit browser like Chrome or Safari and your return value in responseText
, contains a string value.
In that constelation, the value cannot be displayed (it would get blank)
Example: http://jsfiddle.net/BmhNL/2/
My point here is, that I expect a wrong/double encoded string value. Webkit browsers are more strict on the type
= number
. If there is "only" a white-space issue, you can try to implicitly call the Number()
constructor, like
document.getElementById("points").value = +request.responseText;
For Angular 5
app.module.ts
import {DatePipe} from '@angular/common';
.
.
.
providers: [DatePipe]
demo.component.ts
import { DatePipe } from '@angular/common';
.
.
constructor(private datePipe: DatePipe) {}
ngOnInit() {
var date = new Date();
console.log(this.datePipe.transform(date,"yyyy-MM-dd")); //output : 2018-02-13
}
more information angular/datePipe
JSON syntax is pretty much the JavaScript syntax for coding your object. Therefore, in terms of conciseness and speed, your own answer is the best bet.
I use this approach when populating dropdown lists in my KnockoutJS model. E.g.
var desktopGrpViewModel = {
availableComputeOfferings: ko.observableArray(@Html.Raw(JsonConvert.SerializeObject(ViewBag.ComputeOfferings))),
desktopGrpComputeOfferingSelected: ko.observable(),
};
ko.applyBindings(desktopGrpViewModel);
...
<select name="ComputeOffering" class="form-control valid" id="ComputeOffering" data-val="true"
data-bind="options: availableComputeOffering,
optionsText: 'Name',
optionsValue: 'Id',
value: desktopGrpComputeOfferingSelect,
optionsCaption: 'Choose...'">
</select>
Note that I'm using Json.NET NuGet package for serialization and the ViewBag to pass data.
This worked for me:
git fsck --full --no-reflogs --unreachable --lost-found
git show d6e883ff45be514397dcb641c5a914f40b938c86
git branch helpme 15e521b0f716269718bb4e4edc81442a6c11c139
I used the strip function to get rid of newline character as split lines was throwing memory errors on 4 gb File.
Sample Code:
with open('C:\\aapl.csv','r') as apple:
for apps in apple.readlines():
print(apps.strip())
I don't believe this is a good pattern to use in general. Link will run your onClick event and then navigate to the route, so there will be a slight delay navigating to the new route. A better strategy is to navigate to the new route with the 'to' prop as you have done, and in the new component's componentDidMount() function you can fire your hello function or any other function. It will give you the same result, but with a much smoother transition between routes.
For context, I noticed this while updating my redux store with an onClick event on Link like you have here, and it caused a ~.3 second blank-white-screen delay before mounting the new route's component. There was no api call involved, so I was surprised the delay was so big. However, if you're just console logging 'hello' the delay might not be noticeable.
After a long struggle, I found the solution.
Solution: Add a reference to System.Net.Http.Formatting.dll
. This assembly is also available in the C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies folder.
The method ReadAsAsync
is an extension method declared in the class HttpContentExtensions
, which is in the namespace System.Net.Http
in the library System.Net.Http.Formatting
.
Reflector came to rescue!
jQuery way to change value on text input field is:
$('#colorpickerField1').attr('value', '#000000')
this will change attribute value
for the DOM element with ID #colorpickerField1
from #EEEEEE
to #000000
you can use this:
box-shadow: inset 0 0 0 1000px rgba(0,0,0,.2);
as seen on: https://stackoverflow.com/a/24084708/8953378
This is unrelated to UTF-8/16 (in general, although it does convert to UTF16 and the BE/LE part can be set w/ a single line), yet below is the fastest way to convert String to byte[]. For instance: good exactly for the case provided (hash code). String.getBytes(enc) is relatively slow.
static byte[] toBytes(String s){
byte[] b=new byte[s.length()*2];
ByteBuffer.wrap(b).asCharBuffer().put(s);
return b;
}
A C++ reference is not a pointer nor a Java/C# style reference and cannot be NULL. They behave as if they were an alias to another existing object.
In some cases, if there are bugs in your code, you might get a reference into an already dead or non-existent object, but the best thing you can do is hope that the program dies soon enough to be able to debug what happened and why your program got corrupted.
That is, I have seen code checking for 'null references' doing something like: if ( &reference == 0 )
, but the standard is clear that there cannot be null references in a well-formed program. If a reference is bound to a null object the program is ill-formed and should be corrected. If you need optional values, use pointers (or some higher level construct like boost::optional
), not references.
find . -mindepth 1 -maxdepth 1 -type d -printf "%P\n"
awk -F "," '{print $0}' user.csv | sort -nk3 -t ','
This should work
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:focusableInTouchMode="true">
<requestFocus/>
</TextView>
<EditText android:layout_width="match_parent"
android:layout_height="wrap_content"/>
* Uses proxy env variable http_proxy == 'https://proxy.in.tum.de:8080' ^^^^^
The https://
is wrong, it should be http://
. The proxy itself should be accessed by HTTP and not HTTPS even though the target URL is HTTPS. The proxy will nevertheless properly handle HTTPS connection and keep the end-to-end encryption. See HTTP CONNECT method for details how this is done.
install mongodb in your linux machine with
apt install mongodb-client && apt install mongodb-server
change the database path instead of your system default path if you want.
so do the following steps and change it for yourself.
mongod --directoryperdb --dbpath /var/lib/mongodb/data/db --logpath /var/lib/mongodb/log/mongodb.log --logappend --rest
and in your windows machine do it just like that just put an --install flag. you have to get a successful message.
Best Regards...
Here is a more generic solution based on @Arun answer
public abstract class TextViewLinkHandler extends LinkMovementMethod {
public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
if (event.getAction() != MotionEvent.ACTION_UP)
return super.onTouchEvent(widget, buffer, event);
int x = (int) event.getX();
int y = (int) event.getY();
x -= widget.getTotalPaddingLeft();
y -= widget.getTotalPaddingTop();
x += widget.getScrollX();
y += widget.getScrollY();
Layout layout = widget.getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
URLSpan[] link = buffer.getSpans(off, off, URLSpan.class);
if (link.length != 0) {
onLinkClick(link[0].getURL());
}
return true;
}
abstract public void onLinkClick(String url);
}
To use it just implement onLinkClick
of TextViewLinkHandler
class. For instance:
textView.setMovementMethod(new TextViewLinkHandler() {
@Override
public void onLinkClick(String url) {
Toast.makeText(textView.getContext(), url, Toast.LENGTH_SHORT).show();
}
});
Another place you could stop the timer is the FormClosing event - this happens before the form is actually closed, so is a good place to stop things before they might access unavailable resources.
You could also post a notification via NSNotificationCenter. This let's you deal with a number of situations where traversing the view controller hierarchy might be tricky - for example when modals are being presented, etc.
E.g.,
// MyAppDelegate.h
NSString * const UIApplicationDidReceiveRemoteNotification;
// MyAppDelegate.m
NSString * const UIApplicationDidReceiveRemoteNotification = @"UIApplicationDidReceiveRemoteNotification";
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
[[NSNotificationCenter defaultCenter]
postNotificationName:UIApplicationDidReceiveRemoteNotification
object:self
userInfo:userInfo];
}
In each of your View Controllers:
-(void)viewDidLoad {
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(didReceiveRemoteNotification:)
name:UIApplicationDidReceiveRemoteNotification
object:nil];
}
-(void)viewDidUnload {
[[NSNotificationCenter defaultCenter]
removeObserver:self
name:UIApplicationDidReceiveRemoteNotification
object:nil];
}
-(void)didReceiveRemoteNotification:(NSDictionary *)userInfo {
// see http://stackoverflow.com/a/2777460/305149
if (self.isViewLoaded && self.view.window) {
// handle the notification
}
}
You could also use this approach to instrument controls which need to update when a notification is received and are used by several view controllers. In that case, handle the add/remove observer calls in the init and dealloc methods, respectively.
http://dl.google.com/android/ndk/android-ndk-r9d-linux-x86_64.tar.bz2
I successfully opened gstreamer SDK tutorials in Eclipse.
All I needed is to use an older version of ndk. specificly 9d.
(10c and 10d does not work, 10b - works just for tutorial-1 )
9d does work for all tutorials ! and you can:
Download it from: http://dl.google.com/android/ndk/android-ndk-r9d-linux-x86_64.tar.bz2
Extract it.
set it in eclipse->window->preferences->Android->NDK->NDK location.
build - (ctrl+b).
Try this:
Remove the constraint DF_Movies_Rating__48CFD27E before changing your field type.
The constraint is typically created automatically by the DBMS (SQL Server).
To see the constraint associated with the table, expand the table attributes in Object explorer, followed by the category Constraints as shown below:
You must remove the constraint before changing the field type.
If you pass a variable data
(dictionary type) as context to a template, then you code should be:
{% for key, value in data.items %}
<p>{{ key }} : {{ value }}</p>
{% endfor %}
To get a border on just one side of a drawable, apply a negative inset
to the other 3 sides (causing those borders to be drawn off-screen).
<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetTop="-2dp"
android:insetBottom="-2dp"
android:insetLeft="-2dp">
<shape android:shape="rectangle">
<stroke android:width="2dp" android:color="#FF0000" />
<solid android:color="#000000" />
</shape>
</inset>
This approach is similar to naykah's answer, but without the use of a layer-list
.
If you are looking for sending color data from backend
def color():
color = "#{:06x}".format(random.randint(0, 0xFFFFFF))
return color
You just need to add 'table-layout: fixed;'
.table {
display: table;
height: 100px;
width: 100%;
table-layout: fixed;
}
You can use the username variable: %USERNAME%
In the web development world, the term "redirect" is the act of sending the client an empty HTTP response with just a Location
header containing the new URL to which the client has to send a brand new GET request. So basically:
some.jsp
.Location: other.jsp
headerother.jsp
(this get reflected in browser address bar!)other.jsp
.You can track it with the web browser's builtin/addon developer toolset. Press F12 in Chrome/IE9/Firebug and check the "Network" section to see it.
Exactly the above is achieved by sendRedirect("other.jsp")
. The RequestDispatcher#forward()
doesn't send a redirect. Instead, it uses the content of the target page as HTTP response.
some.jsp
.other.jsp
.However, as the original HTTP request was to some.jsp
, the URL in browser address bar remains unchanged. Also, any request attributes set in the controller behind some.jsp
will be available in other.jsp
. This does not happen during a redirect because you're basically forcing the client to create a new HTTP request on other.jsp
, hereby throwing away the original request on some.jsp
including all of its attribtues.
The RequestDispatcher
is extremely useful in the MVC paradigm and/or when you want to hide JSP's from direct access. You can put JSP's in the /WEB-INF
folder and use a Servlet
which controls, preprocesses and postprocesses the requests. The JSPs in the /WEB-INF
folder are not directly accessible by URL, but the Servlet
can access them using RequestDispatcher#forward()
.
You can for example have a JSP file in /WEB-INF/login.jsp
and a LoginServlet
which is mapped on an url-pattern
of /login
. When you invoke http://example.com/context/login
, then the servlet's doGet()
will be invoked. You can do any preprocessing stuff in there and finally forward the request like:
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
When you submit a form, you normally want to use POST
:
<form action="login" method="post">
This way the servlet's doPost()
will be invoked and you can do any postprocessing stuff in there (e.g. validation, business logic, login the user, etc).
If there are any errors, then you normally want to forward the request back to the same page and display the errors there next to the input fields and so on. You can use the RequestDispatcher
for this.
If a POST
is successful, you normally want to redirect the request, so that the request won't be resubmitted when the user refreshes the request (e.g. pressing F5 or navigating back in history).
User user = userDAO.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user); // Login user.
response.sendRedirect("home"); // Redirects to http://example.com/context/home after succesful login.
} else {
request.setAttribute("error", "Unknown login, please try again."); // Set error.
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response); // Forward to same page so that you can display error.
}
A redirect thus instructs the client to fire a new GET
request on the given URL. Refreshing the request would then only refresh the redirected request and not the initial request. This will avoid "double submits" and confusion and bad user experiences. This is also called the POST-Redirect-GET
pattern.
Yes. It is possible :D
SELECT SUM(totalHours) totalHours
FROM
(
select sum(hours) totalHours from resource
UNION ALL
select sum(hours) totalHours from projects-time
) s
As a sidenote, the tablename projects-time
must be delimited to avoid syntax error. Delimiter symbols vary on RDBMS you are using.
You have to specify project_id
:
reverse('edit_project', kwargs={'project_id':4})
Doc here
**Reading the Excel File:**
string filePath = @"d:\MyExcel.xlsx";
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(filePath);
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Excel.Range xlRange = xlWorkSheet.UsedRange;
int totalRows = xlRange.Rows.Count;
int totalColumns = xlRange.Columns.Count;
string firstValue, secondValue;
for (int rowCount = 1; rowCount <= totalRows; rowCount++)
{
firstValue = Convert.ToString((xlRange.Cells[rowCount, 1] as Excel.Range).Text);
secondValue = Convert.ToString((xlRange.Cells[rowCount, 2] as Excel.Range).Text);
Console.WriteLine(firstValue + "\t" + secondValue);
}
xlWorkBook.Close();
xlApp.Quit();
**Writting the Excel File:**
Excel.Application xlApp = new Excel.Application();
object misValue = System.Reflection.Missing.Value;
Excel.Workbook xlWorkBook = xlApp.Workbooks.Add(misValue);
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "ID";
xlWorkSheet.Cells[1, 2] = "Name";
xlWorkSheet.Cells[2, 1] = "100";
xlWorkSheet.Cells[2, 2] = "John";
xlWorkSheet.Cells[3, 1] = "101";
xlWorkSheet.Cells[3, 2] = "Herry";
xlWorkBook.SaveAs(filePath, Excel.XlFileFormat.xlOpenXMLWorkbook, misValue, misValue, misValue, misValue,
Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close();
xlApp.Quit();
I just got through fighting with a table that I couldn't make any smaller no matter which element I tried to make smaller the width of the table stayed the same. I searched using firebug but couldn't find the element that was setting the width so high.
Finally I tried changing the size attribute of the input text elements and that fixed it. For some reason the size attribute over-rode the css widths. I was using jQuery to dynamically add rows to a table and it was these rows that contained the inputs. So perhaps when it comes to dynamically adding inputs using the appendTo() function maybe it is better to set the size attribute along with the width.
My usual trick is to simply print sys.path
in the actual context where the import problem happens. In your case it'd seem that the place for the print is in /home/hughdbrown/.local/bin/pserve
. Then check dirs & files in the places that path shows..
You do that by first having:
import sys
and in python 2 with print expression:
print sys.path
or in python 3 with the print function:
print(sys.path)
- (void)GetCurrentTimeStamp
{
NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
[objDateformat setDateFormat:@"yyyy-MM-dd"];
NSString *strTime = [objDateformat stringFromDate:[NSDate date]];
NSString *strUTCTime = [self GetUTCDateTimeFromLocalTime:strTime];//You can pass your date but be carefull about your date format of NSDateFormatter.
NSDate *objUTCDate = [objDateformat dateFromString:strUTCTime];
long long milliseconds = (long long)([objUTCDate timeIntervalSince1970] * 1000.0);
NSString *strTimeStamp = [Nsstring stringwithformat:@"%lld",milliseconds];
NSLog(@"The Timestamp is = %@",strTimestamp);
}
- (NSString *) GetUTCDateTimeFromLocalTime:(NSString *)IN_strLocalTime
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *objDate = [dateFormatter dateFromString:IN_strLocalTime];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSString *strDateTime = [dateFormatter stringFromDate:objDate];
return strDateTime;
}
NOTE :- The Timestamp must be in UTC Zone, So I convert our local Time to UTC Time.
SimpleListAdapter's are primarily used for static data! If you want to handle dynamic data, you're better off working with an ArrayAdapter, ListAdapter or with a CursorAdapter if your data is coming in from the database.
Here's a useful tutorial in understanding binding data in a ListAdapter
As referenced in this SO question
The selector should not be #input
. That means a field with id="input"
which is not your case. You want:
$('#chag_sort').val(sort2);
Or if your hidden input didn't have an unique id but only a name="chag_sort"
:
$('input[name="chag_sort"]').val(sort2);
If you want to use the back button, check this out. https://stackoverflow.com/questions/116446/what-is-the-best-back-button-jquery-plugin
Use document.location.href to change the page location, place it in the function on a successful ajax run.
I think you could do it by creating parameters in an object maybe?
var myObject = {}; for(var i=0;i<myArray.length;i++) { myObject[ myArray[i] ]; }
If you don't set them to anything, you'll just have an object with some parameters that are undefined. I'd have to write this myself to be sure though.
I would not suggest to use sll
or srl
with std_logic_vector.
During simulation sll
gave me 'U' value for those bits, where I expected 0's.
Use shift_left()
, shift_right()
functions.
For example:
OP1 : in std_logic_vector(7 downto 0);
signal accum: std_logic_vector(7 downto 0);
accum <= std_logic_vector(shift_left(unsigned(accum), to_integer(unsigned(OP1))));
accum <= std_logic_vector(shift_right(unsigned(accum), to_integer(unsigned(OP1))));
backdrop-filter
Unfortunately Mozilla has really dropped the ball and taken it's time with the feature. I'm personally hoping it makes it in to the next Firefox ESR as that is what the next major version of Waterfox will use.
MDN (Mozilla Developer Network) article: https://developer.mozilla.org/en-US/docs/Web/CSS/backdrop-filter
Mozilla implementation: https://bugzilla.mozilla.org/show_bug.cgi?id=1178765
From the MDN documentation page:
/* URL to SVG filter */
backdrop-filter: url(commonfilters.svg#filter);
/* <filter-function> values */
backdrop-filter: blur(2px);
backdrop-filter: brightness(60%);
backdrop-filter: contrast(40%);
backdrop-filter: drop-shadow(4px 4px 10px blue);
backdrop-filter: grayscale(30%);
backdrop-filter: hue-rotate(120deg);
backdrop-filter: invert(70%);
backdrop-filter: opacity(20%);
backdrop-filter: sepia(90%);
backdrop-filter: saturate(80%);
/* Multiple filters */
backdrop-filter: url(filters.svg#filter) blur(4px) saturate(150%);
I like @fubo's answer the best but I think this is much more elegant.
This method is more compatible because it doesn't manually store the length up front.
Also I've exposed extensions to support compression for string to string, byte[] to byte[], and Stream to Stream.
public static class ZipExtensions
{
public static string CompressToBase64(this string data)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(data).Compress());
}
public static string DecompressFromBase64(this string data)
{
return Encoding.UTF8.GetString(Convert.FromBase64String(data).Decompress());
}
public static byte[] Compress(this byte[] data)
{
using (var sourceStream = new MemoryStream(data))
using (var destinationStream = new MemoryStream())
{
sourceStream.CompressTo(destinationStream);
return destinationStream.ToArray();
}
}
public static byte[] Decompress(this byte[] data)
{
using (var sourceStream = new MemoryStream(data))
using (var destinationStream = new MemoryStream())
{
sourceStream.DecompressTo(destinationStream);
return destinationStream.ToArray();
}
}
public static void CompressTo(this Stream stream, Stream outputStream)
{
using (var gZipStream = new GZipStream(outputStream, CompressionMode.Compress))
{
stream.CopyTo(gZipStream);
gZipStream.Flush();
}
}
public static void DecompressTo(this Stream stream, Stream outputStream)
{
using (var gZipStream = new GZipStream(stream, CompressionMode.Decompress))
{
gZipStream.CopyTo(outputStream);
}
}
}
I realize this question is ancient and there is an accepted and an alternate answer. I also realize that my answer will only answer half of the question, but for anyone wanting to round to the nearest minute and still have a datetime compatible value using only a single function:
CAST(YourValueHere as smalldatetime);
For hours or seconds, use Jeff Ogata's answer (the accepted answer) above.
A much faster implementation would be to use list-comprehension
if you need to rename a single column.
df.columns = ['log(gdp)' if x=='gdp' else x for x in df.columns]
If the need arises to rename multiple columns, either use conditional expressions like:
df.columns = ['log(gdp)' if x=='gdp' else 'cap_mod' if x=='cap' else x for x in df.columns]
Or, construct a mapping using a dictionary
and perform the list-comprehension
with it's get
operation by setting default value as the old name:
col_dict = {'gdp': 'log(gdp)', 'cap': 'cap_mod'} ## key?old name, value?new name
df.columns = [col_dict.get(x, x) for x in df.columns]
Timings:
%%timeit
df.rename(columns={'gdp':'log(gdp)'}, inplace=True)
10000 loops, best of 3: 168 µs per loop
%%timeit
df.columns = ['log(gdp)' if x=='gdp' else x for x in df.columns]
10000 loops, best of 3: 58.5 µs per loop
I found to be the the askpass
command useful
password=$(/lib/cryptsetup/askpass "Give a password")
Every input character is replaced by *. See: Give a password ****
Can't comment yet, but I just wanted to disagree/clarify with erikkallen.
You should not just catch the exception in the situation you've described. If you KNEW that the file should be there and due to some exceptional case, it wasn't, then it would be acceptable to just attempt to access the file and catch any exception that occurs.
In this case, however, you are receiving input from a user and have little reason to believe that the file exists. Here you should always use File.Exists().
I know it is cliché, but you should only use Exceptions for an exceptional event, not as part as the normal flow of your application. It is expensive and makes code more difficult to read/follow.
The main difference is that, with interfaces, you must define the actual implementation of each method within each class that implements said interface, so you can have many classes implement the same interface but with different behavior, while traits are just chunks of code injected in a class; another important difference is that trait methods can only be class-methods or static-methods, unlike interface methods which can also (and usually are) be instance methods.
>>> class new_class():
... def __init__(self, number):
... self.multi = int(number) * 2
... self.str = str(number)
...
>>> a = new_class(2)
>>> a.__dict__
{'multi': 4, 'str': '2'}
>>> a.__dict__.keys()
dict_keys(['multi', 'str'])
You may also find pprint helpful.
If it is in RelativeLayout
you can use android:layout_toRightOf="@id/<id_of_desired_item>"
Or
If you want to align to the right
corner of the device the place android:layout_alignParentRight="true"
Size of all tables:
Suppose your database or TABLE_SCHEMA
name is "news_alert". Then this query will show the size of all tables in the database.
SELECT
TABLE_NAME AS `Table`,
ROUND(((DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024),2) AS `Size (MB)`
FROM
information_schema.TABLES
WHERE
TABLE_SCHEMA = "news_alert"
ORDER BY
(DATA_LENGTH + INDEX_LENGTH)
DESC;
Output:
+---------+-----------+
| Table | Size (MB) |
+---------+-----------+
| news | 0.08 |
| keyword | 0.02 |
+---------+-----------+
2 rows in set (0.00 sec)
For the specific table:
Suppose your TABLE_NAME
is "news". Then SQL query will be-
SELECT
TABLE_NAME AS `Table`,
ROUND(((DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024),2) AS `Size (MB)`
FROM
information_schema.TABLES
WHERE
TABLE_SCHEMA = "news_alert"
AND
TABLE_NAME = "news"
ORDER BY
(DATA_LENGTH + INDEX_LENGTH)
DESC;
Output:
+-------+-----------+
| Table | Size (MB) |
+-------+-----------+
| news | 0.08 |
+-------+-----------+
1 row in set (0.00 sec)
localStorage
This snippet will find the maximum length of a String that can be stored in localStorage
per domain.
//Clear localStorage
for (var item in localStorage) delete localStorage[item];
window.result = window.result || document.getElementById('result');
result.textContent = 'Test running…';
//Start test
//Defer running so DOM can be updated with "test running" message
setTimeout(function () {
//Variables
var low = 0,
high = 2e9,
half;
//Two billion may be a little low as a starting point, so increase if necessary
while (canStore(high)) high *= 2;
//Keep refining until low and high are equal
while (low !== high) {
half = Math.floor((high - low) / 2 + low);
//Check if we can't scale down any further
if (low === half || high === half) {
console.info(low, high, half);
//Set low to the maximum possible amount that can be stored
low = canStore(high) ? high : low;
high = low;
break;
}
//Check if the maximum storage is no higher than half
if (storageMaxBetween(low, half)) {
high = half;
//The only other possibility is that it's higher than half but not higher than "high"
} else {
low = half + 1;
}
}
//Show the result we found!
result.innerHTML = 'The maximum length of a string that can be stored in localStorage is <strong>' + low + '</strong> characters.';
//Functions
function canStore(strLen) {
try {
delete localStorage.foo;
localStorage.foo = Array(strLen + 1).join('A');
return true;
} catch (ex) {
return false;
}
}
function storageMaxBetween(low, high) {
return canStore(low) && !canStore(high);
}
}, 0);
<h1>LocalStorage single value max length test</h1>
<div id='result'>Please enable JavaScript</div>
Note that the length of a string is limited in JavaScript; if you want to view the maximum amount of data that can be stored in localStorage
when not limited to a single string, you can use the code in this answer.
Edit: Stack Snippets don't support localStorage
, so here is a link to JSFiddle.
Chrome (45.0.2454.101): 5242878 characters
Firefox (40.0.1): 5242883 characters
Internet Explorer (11.0.9600.18036): 16386 122066 122070 characters
I get different results on each run in Internet Explorer.
final keyword in the method input parameter is not needed. Java creates a copy of the reference to the object, so putting final on it doesn't make the object final but just the reference, which doesn't make sense
You should set it with C:\Program Files\Java\jdk1.8.0_12
.
\bin
is not required.
Kindly try below on postman :-
In header section example work for me..
Authorization : JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyIkX18iOnsic3RyaWN0TW9kZSI6dHJ1ZSwiZ2V0dGVycyI6e30sIndhc1BvcHVsYXRlZCI6ZmFsc2UsImFjdGl2ZVBhdGhzIjp7InBhdGhzIjp7InBhc3N3b3JkIjoiaW5pdCIsImVtYWlsIjoiaW5pdCIsIl9fdiI6ImluaXQiLCJfaWQiOiJpbml0In0sInN0YXRlcyI6eyJpZ25vcmUiOnt9LCJkZWZhdWx0Ijp7fSwiaW5pdCI6eyJfX3YiOnRydWUsInBhc3N3b3JkIjp0cnVlLCJlbWFpbCI6dHJ1ZSwiX2lkIjp0cnVlfSwibW9kaWZ5Ijp7fSwicmVxdWlyZSI6e319LCJzdGF0ZU5hbWVzIjpbInJlcXVpcmUiLCJtb2RpZnkiLCJpbml0IiwiZGVmYXVsdCIsImlnbm9yZSJdfSwiZW1pdHRlciI6eyJkb21haW4iOm51bGwsIl9ldmVudHMiOnt9LCJfZXZlbnRzQ291bnQiOjAsIl9tYXhMaXN0ZW5lcnMiOjB9fSwiaXNOZXciOmZhbHNlLCJfZG9jIjp7Il9fdiI6MCwicGFzc3dvcmQiOiIkMmEkMTAkdTAybWNnWHFjWVQvdE41MlkzZ2l3dVROd3ZMWW9ZTlFXejlUcThyaDIwR09IMlhHY3haZWUiLCJlbWFpbCI6Im1hZGFuLmRhbGUxQGdtYWlsLmNvbSIsIl9pZCI6IjU5MjEzYzYyYWM2ODZlMGMyNzI2MjgzMiJ9LCJfcHJlcyI6eyIkX19vcmlnaW5hbF9zYXZlIjpbbnVsbCxudWxsLG51bGxdLCIkX19vcmlnaW5hbF92YWxpZGF0ZSI6W251bGxdLCIkX19vcmlnaW5hbF9yZW1vdmUiOltudWxsXX0sIl9wb3N0cyI6eyIkX19vcmlnaW5hbF9zYXZlIjpbXSwiJF9fb3JpZ2luYWxfdmFsaWRhdGUiOltdLCIkX19vcmlnaW5hbF9yZW1vdmUiOltdfSwiaWF0IjoxNDk1MzUwNzA5LCJleHAiOjE0OTUzNjA3ODl9.BkyB0LjKB4FIsCtnM5FcpcBLvKed_j7rCCxZddwiYnU
console.log() just takes whatever you pass to it and writes it to a console's log window. If you pass in an array, you'll be able to inspect the array's contents. Pass in an object, you can examine the object's attributes/methods. pass in a string, it'll log the string. Basically it's "document.write" but can intelligently take apart its arguments and write them out elsewhere.
It's useful to outputting occasional debugging information, but not particularly useful if you have a massive amount of debugging output.
To watch as a script's executing, you'd use a debugger instead, which allows you step through the code line-by-line. console.log's used when you need to display what some variable's contents were for later inspection, but do not want to interrupt execution.
You have to make one ajax call to get the required result, in this case you can use Google API to get the same
http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true/false
Build this kind of url and replace the lat long with the one you want to. do the call and response will be in JSON, parse the JSON and you will get the complete address up to street level
anon and chepner's answers are on the right track. Python 3.x has a print function and this is what you will need if you want to embed print within a function (and, a fortiori, lambdas).
However, you can get the print function very easily in python 2.x by importing from the standard library's future module. Check it out:
>>>from __future__ import print_function
>>>
>>>iterable = ["a","b","c"]
>>>map(print, iterable)
a
b
c
[None, None, None]
>>>
I guess that looks kind of weird, so feel free to assign the return to _ if you would like to suppress [None, None, None]'s output (you are interested in the side-effects only, I assume):
>>>_ = map(print, iterable)
a
b
c
>>>
As mentioned by Zeeshan, the logrotate options size
, minsize
, maxsize
are triggers for rotation.
To better explain it. You can run logrotate as often as you like, but unless a threshold is reached such as the filesize being reached or the appropriate time passed, the logs will not be rotated.
The size options do not ensure that your rotated logs are also of the specified size. To get them to be close to the specified size you need to call the logrotate program sufficiently often. This is critical.
For log files that build up very quickly (e.g. in the hundreds of MB a day), unless you want them to be very large you will need to ensure logrotate is called often! this is critical.
Therefore to stop your disk filling up with multi-gigabyte log files you need to ensure logrotate is called often enough, otherwise the log rotation will not work as well as you want.
on Ubuntu, you can easily switch to hourly rotation by moving the script /etc/cron.daily/logrotate to /etc/cron.hourly/logrotate
Or add
*/5 * * * * /etc/cron.daily/logrotate
To your /etc/crontab file. To run it every 5 minutes.
The size
option ignores the daily, weekly, monthly time options. But minsize & maxsize take it into account.
The man page is a little confusing there. Here's my explanation.
minsize
rotates only when the file has reached an appropriate size and the set time period has passed. e.g. minsize 50MB + daily
If file reaches 50MB before daily time ticked over, it'll keep growing until the next day.
maxsize
will rotate when the log reaches a set size or the appropriate time has passed.
e.g. maxsize 50MB + daily.
If file is 50MB and we're not at the next day yet, the log will be rotated. If the file is only 20MB and we roll over to the next day then the file will be rotated.
size
will rotate when the log > size. Regardless of whether hourly/daily/weekly/monthly is specified. So if you have size 100M - it means when your log file is > 100M the log will be rotated if logrotate is run when this condition is true. Once it's rotated, the main log will be 0, and a subsequent run will do nothing.
So in the op's case. Specficially 50MB max I'd use something like the following:
/var/log/logpath/*.log {
maxsize 50M
hourly
missingok
rotate 8
compress
notifempty
nocreate
}
Which means he'd create 8hrs of logs max. And there would be 8 of them at no more than 50MB each. Since he's saying that he's getting multi gigabytes each day and assuming they build up at a fairly constant rate, and maxsize is used he'll end up with around close to the max reached for each file. So they will be likely close to 50MB each. Given the volume they build, he would need to ensure that logrotate is run often enough to meet the target size.
Since I've put hourly there, we'd need logrotate to be run a minimum of every hour. But since they build up to say 2 gigabytes per day and we want 50MB... assuming a constant rate that's 83MB per hour. So you can imagine if we run logrotate every hour, despite setting maxsize to 50 we'll end up with 83MB log's in that case. So in this instance set the running to every 30 minutes or less should be sufficient.
Ensure logrotate is run every 30 mins.
*/30 * * * * /etc/cron.daily/logrotate
If you're on a mac and not seeing the export tab or how to get the certificate this worked for me:
Click "Certificate Information"
Now you should see this:
Drag that little certificate icon do your desktop (or anywhere).
Double click the .cer file that was downloaded, this should import it into your keychain and open Keychain Access to your list of certificates.
In some cases, this is enough and you can now refresh the page.
Otherwise:
Now reload the page in question and it should be problem solved! Hope this helps.
To make this a little easier you can use the following script (source):
Save the following script as whitelist_ssl_certificate.ssh
:
#!/usr/bin/env bash -e
SERVERNAME=$(echo "$1" | sed -E -e 's/https?:\/\///' -e 's/\/.*//')
echo "$SERVERNAME"
if [[ "$SERVERNAME" =~ .*\..* ]]; then
echo "Adding certificate for $SERVERNAME"
echo -n | openssl s_client -connect $SERVERNAME:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | tee /tmp/$SERVERNAME.cert
sudo security add-trusted-cert -d -r trustRoot -k "/Library/Keychains/System.keychain" /tmp/$SERVERNAME.cert
else
echo "Usage: $0 www.site.name"
echo "http:// and such will be stripped automatically"
fi
Make the script executable (from the shell):
chmod +x whitelist_ssl_certificate.ssh
Run the script for the domain you want (simply copy/pasting the full url works):
./whitelist_ssl_certificate.ssh https://your_website/whatever
Running assembly Code on Mac is just 3 steps away from you. It could be done using XCODE but better is to use NASM Command Line Tool. For My Ease I have already installed Xcode, if you have Xcode installed its good.
But You can do it without XCode as well.
Just Follow:
brew install nasm
nasm -f macho64 myFile.asm
ld -macosx_version_min 10.7.0 -lSystem -o OutPutFile myFile.o && ./64
Simple Text File named myFile.asm is written below for your convenience.
global start
section .text
start:
mov rax, 0x2000004 ; write
mov rdi, 1 ; stdout
mov rsi, msg
mov rdx, msg.len
syscall
mov rax, 0x2000001 ; exit
mov rdi, 0
syscall
section .data
msg: db "Assalam O Alaikum Dear", 10
.len: equ $ - msg
We use something like this [use in one line]:
<a title="send to Facebook"
href="http://www.facebook.com/sharer.php?s=100&p[title]=YOUR_TITLE&p[summary]=YOUR_SUMMARY&p[url]=YOUR_URL&p[images][0]=YOUR_IMAGE_TO_SHARE_OBJECT"
target="_blank">
<span>
<img width="14" height="14" src="'icons/fb.gif" alt="Facebook" /> Facebook
</span>
</a>
I'm late to the game here, but this is how I am doing it, I spent a while hunting for a solution I was satisified with; this produces an UPDATE
statement ONLY for the fields that are changed, as you explicitly define what they are through a "white list" concept which is more secure to prevent web form injection anyway.
An excerpt from my ISession data repository:
public bool Update<T>(T item, params string[] changedPropertyNames) where T
: class, new()
{
_context.Set<T>().Attach(item);
foreach (var propertyName in changedPropertyNames)
{
// If we can't find the property, this line wil throw an exception,
//which is good as we want to know about it
_context.Entry(item).Property(propertyName).IsModified = true;
}
return true;
}
This could be wrapped in a try..catch if you so wished, but I personally like my caller to know about the exceptions in this scenario.
It would be called in something like this fashion (for me, this was via an ASP.NET Web API):
if (!session.Update(franchiseViewModel.Franchise, new[]
{
"Name",
"StartDate"
}))
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
As the name suggests 'untracked files' are the files which are not being tracked by git. They are not in your staging area, and were not part of any previous commits. If you want them to be versioned (or to be managed by git) you can do so by telling 'git' by using 'git add'. Check this chapter Recording Changes to the Repository in the Progit book which uses a nice visual to provide a good explanation about recording changes to git repo and also explaining the terms 'tracked' and 'untracked'.
Code Runner Extension will only let you "run" java files.
To truly debug 'Java' files follow the quick one-time setup:
.vscode
in the same folder..vscode
folder: tasks.json
and launch.json
tasks.json
:{ "version": "2.0.0", "type": "shell", "presentation": { "echo": true, "reveal": "always", "focus": false, "panel": "shared" }, "isBackground": true, "tasks": [ { "taskName": "build", "args": ["-g", "${file}"], "command": "javac" } ] }
launch.json
:{ "version": "0.2.0", "configurations": [ { "name": "Debug Java", "type": "java", "request": "launch", "externalConsole": true, //user input dosen't work if set it to false :( "stopOnEntry": true, "preLaunchTask": "build", // Runs the task created above before running this configuration "jdkPath": "${env:JAVA_HOME}/bin", // You need to set JAVA_HOME enviroment variable "cwd": "${workspaceRoot}", "startupClass": "${workspaceRoot}${file}", "sourcePath": ["${workspaceRoot}"], // Indicates where your source (.java) files are "classpath": ["${workspaceRoot}"], // Indicates the location of your .class files "options": [], // Additional options to pass to the java executable "args": [] // Command line arguments to pass to the startup class } ], "compounds": [] }
You are all set to debug java files, open any java file and press F5 (Debug->Start Debugging).
Tip: *To hide .class files in the side explorer of VS code, open settings
of VS code and paste the below config:
"files.exclude": {
"*.class": true
}
You could use the border-bottom
css property.
table {_x000D_
border-collapse: collapse;_x000D_
}_x000D_
_x000D_
table tr {_x000D_
border-bottom: 1px solid black;_x000D_
}_x000D_
_x000D_
table tr:last-child {_x000D_
border: 0;_x000D_
}
_x000D_
<table>_x000D_
<tr>_x000D_
<td>1</td>_x000D_
<td>Foo</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>2</td>_x000D_
<td>Bar</td>_x000D_
</tr>_x000D_
</table>
_x000D_
I needed to use a link with onLoad attribute in my head where div is not allowed so this caused me significant pain. My current workaround is to close the original script tag, do what I need to do, then open script tag (to be closed by the original). Hope this might help someone who has absolutely no other choice:
<script dangerouslySetInnerHTML={{ __html: `</script>
<link rel="preload" href="https://fonts.googleapis.com/css?family=Open+Sans" as="style" onLoad="this.onload=null;this.rel='stylesheet'" crossOrigin="anonymous"/>
<script>`,}}/>
what's the problem with:
field like "*AA*" and field not like "*BB*"
it should be working.
Could you post some example of your data?
Try ceiling...
SELECT Ceiling(45.01), Ceiling(45.49), Ceiling(45.99)
Try this:
// Hide the login modal
$('#login').modal('hide');
// Show the next modal after the fade effect is finished
setTimeout(function(){ $('#lost').modal('show'); }, 500);
This simple hack works for me.
Your error looks like you are duplicating an already existing Primary Key in your DB. You should modify your sql code to implement its own primary key by using something like the IDENTITY keyword.
CREATE TABLE [DB] (
[DBId] bigint NOT NULL IDENTITY,
...
CONSTRAINT [DB_PK] PRIMARY KEY ([DB] ASC),
);
On Spanish (Spain) keyboard with VS2012 is Ctrl + ¡ as stated by @Keith but if you use Ctrl + ¿ (typed as Ctrl + Shift + ¡) then goes to Matching Brace plus selects all the code within the two braces and then you can't go again to the other brace.
The preferred way is to always use the literal syntax with square brackets; its behaviour is predictable for any number of items, unlike Array
's. What's more, Array
is not a keyword, and although it is not a realistic situation, someone could easily overwrite it:
function Array() { return []; }
alert(Array(1, 2, 3)); // An empty alert box
However, the larger issue is that of consistency. Someone refactoring code could come across this function:
function fetchValue(n) {
var arr = new Array(1, 2, 3);
return arr[n];
}
As it turns out, only fetchValue(0)
is ever needed, so the programmer drops the other elements and breaks the code, because it now returns undefined
:
var arr = new Array(1);
If size of the JARs matters (e.g. in case of applet), one can also directly use httpmime with java.net.HttpURLConnection instead of HttpClient.
httpclient-4.2.4: 423KB
httpmime-4.2.4: 26KB
httpcore-4.2.4: 222KB
commons-codec-1.6: 228KB
commons-logging-1.1.1: 60KB
Sum: 959KB
httpmime-4.2.4: 26KB
httpcore-4.2.4: 222KB
Sum: 248KB
Code:
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
FileBody fileBody = new FileBody(new File(fileName));
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT);
multipartEntity.addPart("file", fileBody);
connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue());
OutputStream out = connection.getOutputStream();
try {
multipartEntity.writeTo(out);
} finally {
out.close();
}
int status = connection.getResponseCode();
...
Dependency in pom.xml:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.2.4</version>
</dependency>
var a = ['a','b','c'];
var b = ['d','e','f'];
var c = a.concat(b); //c is now an an array with: ['a','b','c','d','e','f']
console.log( c[3] ); //c[3] will be 'd'
Try this:
$("#cpa-form").submit(function(e){
return false;
});
This is a small adition to @Andrew Dunn's post above
Combining the 2 is possible to generate readable JS and matching output
var foo = "Bob\n\
is\n\
cool.\n\";
inspired by Joaquin Alberto, this worked for me:
public class SpinAdapter extends ArrayAdapter<User>{
public SpinAdapter(Context context, int textViewResourceId,
User[] values) {
super(context, textViewResourceId, values);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView label = (TextView) super.getView(position, convertView, parent);
label.setTextColor(Color.BLACK);
label.setText(this.getItem(position).getName());
return label;
}
@Override
public View getDropDownView(int position, View convertView,ViewGroup parent) {
TextView label = (TextView) super.getView(position, convertView, parent);
label.setTextColor(Color.BLACK);
label.setText(this.getItem(position).getName());
return label;
}
}
Following works in bootstrap 4 and displays well in CSS, mobile and has no issues with label spacing.
CSS
.checkbox-lg .custom-control-label::before,
.checkbox-lg .custom-control-label::after {
top: .8rem;
width: 1.55rem;
height: 1.55rem;
}
.checkbox-lg .custom-control-label {
padding-top: 13px;
padding-left: 6px;
}
.checkbox-xl .custom-control-label::before,
.checkbox-xl .custom-control-label::after {
top: 1.2rem;
width: 1.85rem;
height: 1.85rem;
}
.checkbox-xl .custom-control-label {
padding-top: 23px;
padding-left: 10px;
}
HTML
<div class="custom-control custom-checkbox checkbox-lg">
<input type="checkbox" class="custom-control-input" id="checkbox-3">
<label class="custom-control-label" for="checkbox-3">Large checkbox</label>
</div>
You can also make it extra large by declaring checkbox-xl
If anyone from BS team is reading this, it would be really good if you make this available right out of the box, I don't see anything for it in BS 5 either
I found another solution for this problem. This looks like another bug in WebKit (or probably Chrome), but it works. All you need to do - is to add a WebKit CSS Mask to the #wrapper element. You can use a single pixel png image and even include it to the CSS to save a HTTP request.
#wrapper {
width: 300px; height: 300px;
border-radius: 100px;
overflow: hidden;
position: absolute; /* this breaks the overflow:hidden in Chrome/Opera */
/* this fixes the overflow:hidden in Chrome */
-webkit-mask-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAA5JREFUeNpiYGBgAAgwAAAEAAGbA+oJAAAAAElFTkSuQmCC);
}
#box {
width: 300px; height: 300px;
background-color: #cde;
}?
Using array_walk
$a = array("item1"=>"object1", "item2"=>"object2","item-n"=>"object-n");
$r=array();
array_walk($a, create_function('$b, $c', 'global $r; $r[]="$c=$b";'));
echo implode(', ', $r);
Yeeeaaahhh.... you can now use var() function in CSS.....
The good news is you can change it using JavaScript access, which will change globally as well...
But how to declare them...
It's quite simple:
For example, you wanna assign a #ff0000
to a var()
, just simply assign it in :root
, also pay attention to --
:
:root {
--red: #ff0000;
}
html, body {
background-color: var(--red);
}
The good things are the browser support is not bad, also don't need to be compiled to be used in the browser like LESS
or SASS
...
Also, here is a simple JavaScript script, which changes the red value to blue:
const rootEl = document.querySelector(':root');
root.style.setProperty('--red', 'blue');
Use:
$("tr").find("td:first");
js fiddle - this example has .text()
on the end to show that it is returning the elements.
Alternatively, you can use:
$("td:first-child");
.find()
- jQuery API Documentation
Here is Simple Solution And Complete Example for Uploading File Using Volley Android
1) Gradle Import
compile 'dev.dworks.libs:volleyplus:+'
2)Now Create a Class RequestManager
public class RequestManager {
private static RequestManager mRequestManager;
/**
* Queue which Manages the Network Requests :-)
*/
private static RequestQueue mRequestQueue;
// ImageLoader Instance
private RequestManager() {
}
public static RequestManager get(Context context) {
if (mRequestManager == null)
mRequestManager = new RequestManager();
return mRequestManager;
}
/**
* @param context application context
*/
public static RequestQueue getnstance(Context context) {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(context);
}
return mRequestQueue;
}
}
3)Now Create a Class to handle Request for uploading File WebService
public class WebService {
private RequestQueue mRequestQueue;
private static WebService apiRequests = null;
public static WebService getInstance() {
if (apiRequests == null) {
apiRequests = new WebService();
return apiRequests;
}
return apiRequests;
}
public void updateProfile(Context context, String doc_name, String doc_type, String appliance_id, File file, Response.Listener<String> listener, Response.ErrorListener errorListener) {
SimpleMultiPartRequest request = new SimpleMultiPartRequest(Request.Method.POST, "YOUR URL HERE", listener, errorListener);
// request.setParams(data);
mRequestQueue = RequestManager.getnstance(context);
request.addMultipartParam("token", "text", "tdfysghfhsdfh");
request.addMultipartParam("parameter_1", "text", doc_name);
request.addMultipartParam("dparameter_2", "text", doc_type);
request.addMultipartParam("parameter_3", "text", appliance_id);
request.addFile("document_file", file.getPath());
request.setFixedStreamingMode(true);
mRequestQueue.add(request);
}
}
4) And Now Call The method Like This to Hit the service
public class Main2Activity extends AppCompatActivity implements Response.ErrorListener, Response.Listener<String>{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
uploadData();
}
});
}
private void uploadData() {
WebService.getInstance().updateProfile(getActivity(), "appl_doc", "appliance", "1", mChoosenFile, this, this);
}
@Override
public void onErrorResponse(VolleyError error) {
}
@Override
public void onResponse(String response) {
//Your response here
}
}
See, if you are creating an intent within a listiner in some method
override onClick (View v).
then call the context through this view as well:
v.getContext ()
There will not even need SetFlags ...
assertNotNull
asserts that the object is not null. If it is null the test fails, so you want that.
In case anyone else runs into this - the cause, in my case, was that I was using the (deprecated) docker compose
approach to push images. Switching to the expected docker push
resolved the issue for me.
If you're looking for preferred language code ("en", "de", "es" ...), and localized preferred language name (for current locale), here's a simple extension in Swift:
extension Locale {
static var preferredLanguageIdentifier: String {
let id = Locale.preferredLanguages.first!
let comps = Locale.components(fromIdentifier: id)
return comps.values.first!
}
static var preferredLanguageLocalizedString: String {
let id = Locale.preferredLanguages.first!
return Locale.current.localizedString(forLanguageCode: id)!
}
}
For mobile application i did a solution by injecting javascript in the dialog view. There is a hidden web view in my ios app. That load the fb message send dialog api .. then i inject some javascript to set the "to" and "message" field and submit the form.. So that end user need not to do anything. Message sent to facebook inbox silently...
The exists
keyword can be used in that way, but really it's intended as a way to avoid counting:
--this statement needs to check the entire table
select count(*) from [table] where ...
--this statement is true as soon as one match is found
exists ( select * from [table] where ... )
This is most useful where you have if
conditional statements, as exists
can be a lot quicker than count
.
The in
is best used where you have a static list to pass:
select * from [table]
where [field] in (1, 2, 3)
When you have a table in an in
statement it makes more sense to use a join
, but mostly it shouldn't matter. The query optimiser should return the same plan either way. In some implementations (mostly older, such as Microsoft SQL Server 2000) in
queries will always get a nested join plan, while join
queries will use nested, merge or hash as appropriate. More modern implementations are smarter and can adjust the plan even when in
is used.
For the offline tools that support multiple inputs, the best I've seen so far is https://github.com/wolverdude/GenSON/ I'd like to see a tool that takes filenames on standard input because I have thousands of files. However, I run out of open file descriptors, so make sure the files are closed. I'd also like to see JSON Schema generators that handle recursion. I am now working on generating Java classes from JSON objects in hopes of going to JSON Schema from my Java classes. Here is my GenSON script if you are curious or want to identify bugs in it.
#!/bin/sh
ulimit -n 4096
rm x3d*json
cat /dev/null > x3d.json
find ~/Downloads/www.web3d.org/x3d/content/examples -name '*json' - print| xargs node goodJSON.js | xargs python bin/genson.py -i 2 -s x3d.json >> x3d.json
split -p '^{' x3d.json x3d.json
python bin/genson.py -i 2 -s x3d.jsonaa -s x3d.jsonab /Users/johncarlson/Downloads/www.web3d.org/x3d/content/examples/X3dForWebAuthors/Chapter02-GeometryPrimitives/Box.json > x3dmerge.json
Yes, it does deserialize to List<>. No need to keep it in an array and wrap/encapsulate it in a list.
public class UserHolder
{
private List<User> users = null;
public UserHolder()
{
}
[XmlElement("user")]
public List<User> Users
{
get { return users; }
set { users = value; }
}
}
Deserializing code,
XmlSerializer xs = new XmlSerializer(typeof(UserHolder));
UserHolder uh = (UserHolder)xs.Deserialize(new StringReader(str));
use
background:red url(../images/samle.jpg) no-repeat left top;
You should declare a class Compare
and overload operator()
for it like this:
class Foo
{
};
class Compare
{
public:
bool operator() (Foo, Foo)
{
return true;
}
};
int main()
{
std::priority_queue<Foo, std::vector<Foo>, Compare> pq;
return 0;
}
Or, if you for some reasons can't make it as class, you could use std::function
for it:
class Foo
{
};
bool Compare(Foo, Foo)
{
return true;
}
int main()
{
std::priority_queue<Foo, std::vector<Foo>, std::function<bool(Foo, Foo)>> pq(Compare);
return 0;
}
Open the CSV file with a decent text editor like Notepad++ and add the following text in the first line:
sep=,
Now open it with excel again.
This will set the separator as a comma, or you can change it to whatever you need.
For Bootstrap 4.4+
Use the brand new row-cols-n
classes.
row-cols-5
class to your .row
div. No custom CSS needed.For Bootstrap 4 versions prior to Bootstrap 4.4
Copy CSS below (awesome CSS by Bootstrap authors) and add it to your project
Read the docs cited above to use it correctly.
.row-cols-1>*{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.row-cols-2>*{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.row-cols-3>*{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.row-cols-4>*{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.row-cols-5>*{-ms-flex:0 0 20%;flex:0 0 20%;max-width:20%}.row-cols-6>*{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}@media (min-width:576px){.row-cols-sm-1>*{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.row-cols-sm-2>*{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.row-cols-sm-3>*{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.row-cols-sm-4>*{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.row-cols-sm-5>*{-ms-flex:0 0 20%;flex:0 0 20%;max-width:20%}.row-cols-sm-6>*{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}}@media (min-width:768px){.row-cols-md-1>*{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.row-cols-md-2>*{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.row-cols-md-3>*{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.row-cols-md-4>*{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.row-cols-md-5>*{-ms-flex:0 0 20%;flex:0 0 20%;max-width:20%}.row-cols-md-6>*{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}}@media (min-width:992px){.row-cols-lg-1>*{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.row-cols-lg-2>*{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.row-cols-lg-3>*{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.row-cols-lg-4>*{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.row-cols-lg-5>*{-ms-flex:0 0 20%;flex:0 0 20%;max-width:20%}.row-cols-lg-6>*{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}}@media (min-width:1200px){.row-cols-xl-1>*{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.row-cols-xl-2>*{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.row-cols-xl-3>*{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.row-cols-xl-4>*{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.row-cols-xl-5>*{-ms-flex:0 0 20%;flex:0 0 20%;max-width:20%}.row-cols-xl-6>*{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}}
It seems nobody has addressed where the recursive function calls itself more than once in the body, and handles returning to a specific point in the recursion (i.e. not primitive-recursive). It is said that every recursion can be turned into iteration, so it appears that this should be possible.
I just came up with a C# example of how to do this. Suppose you have the following recursive function, which acts like a postorder traversal, and that AbcTreeNode is a 3-ary tree with pointers a, b, c.
public static void AbcRecursiveTraversal(this AbcTreeNode x, List<int> list) {
if (x != null) {
AbcRecursiveTraversal(x.a, list);
AbcRecursiveTraversal(x.b, list);
AbcRecursiveTraversal(x.c, list);
list.Add(x.key);//finally visit root
}
}
The iterative solution:
int? address = null;
AbcTreeNode x = null;
x = root;
address = A;
stack.Push(x);
stack.Push(null)
while (stack.Count > 0) {
bool @return = x == null;
if (@return == false) {
switch (address) {
case A://
stack.Push(x);
stack.Push(B);
x = x.a;
address = A;
break;
case B:
stack.Push(x);
stack.Push(C);
x = x.b;
address = A;
break;
case C:
stack.Push(x);
stack.Push(null);
x = x.c;
address = A;
break;
case null:
list_iterative.Add(x.key);
@return = true;
break;
}
}
if (@return == true) {
address = (int?)stack.Pop();
x = (AbcTreeNode)stack.Pop();
}
}
JavaScript with a few modifications:
function deleteRow(btn) {
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
}
And the HTML with a little difference:
<table id="dsTable">
<tbody>
<tr>
<td>Relationship Type</td>
<td>Date of Birth</td>
<td>Gender</td>
</tr>
<tr>
<td>Spouse</td>
<td>1980-22-03</td>
<td>female</td>
<td><input type="button" value="Add" onclick="add()"/></td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"/></td>
</tr>
<tr>
<td>Child</td>
<td>2008-23-06</td>
<td>female</td>
<td><input type="button" value="Add" onclick="add()"/></td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"/></td>
</tr>
</tbody>
</table>???????????????????????????????????
if ($('input:checkbox').filter(':checked').length < 1){
alert("Check at least one!");
return false;
}
As far as I know you can't do this with string.Format ... you would have to handle this yourself. You could just strip out all non-numeric characters and then do something like:
string.Format("({0}) {1}-{2}",
phoneNumber.Substring(0, 3),
phoneNumber.Substring(3, 3),
phoneNumber.Substring(6));
This assumes the data has been entered correctly, which you could use regular expressions to validate.
And in the meantime, there's a C source code library that will do all this for you, redirecting stdout or stderr. But the cool part is that it lets you assign as many callback functions as you want to the intercepted streams, allowing you then to very easily send a single message to multiple destinations, a DB, a text file, etc.
On top of that, it makes it trivial to create new streams that look and behave the same as stdout and stderr, where you can redirect these new streams to multiple locations as well.
look for U-Streams C library on *oogle.
Try to use anyMatch
of Lambda Expression. It is much better approach.
boolean idExists = tabPane.getTabs().stream()
.anyMatch(t -> t.getId().equals(idToCheck));
<% %>
: Executes the ruby code <%= %>
: Prints into Erb file. Or browser <% -%>
: Avoids line break after expression. <%# %>
: ERB commentThere is no difference in terms of functionality. In fact, both do this:
return this.Add(new SqlParameter(parameterName, value));
The reason they deprecated the old one in favor of AddWithValue
is to add additional clarity, as well as because the second parameter is object
, which makes it not immediately obvious to some people which overload of Add
was being called, and they resulted in wildly different behavior.
Take a look at this example:
SqlCommand command = new SqlCommand();
command.Parameters.Add("@name", 0);
At first glance, it looks like it is calling the Add(string name, object value)
overload, but it isn't. It's calling the Add(string name, SqlDbType type)
overload! This is because 0 is implicitly convertible to enum types. So these two lines:
command.Parameters.Add("@name", 0);
and
command.Parameters.Add("@name", 1);
Actually result in two different methods being called. 1
is not convertible to an enum implicitly, so it chooses the object
overload. With 0
, it chooses the enum overload.
To check if the javascript in nonexistant.js
returned no error you have to add a variable inside http://fail.org/nonexistant.js
like var isExecuted = true;
and then check if it exists when the script tag is loaded.
However if you only want to check that the nonexistant.js
returned without a 404 (meaning it exists), you can try with a isLoaded
variable ...
var isExecuted = false;
var isLoaded = false;
script_tag.onload = script_tag.onreadystatechange = function() {
if(!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete") {
// script successfully loaded
isLoaded = true;
if(isExecuted) // no error
}
}
This will cover both cases.
Try using this tool,which is just a simple js script https://github.com/shashwatsahai/CSSExtractor/ This tool helps in getting the CSS from a specific page listing all sources for active styles and save it to a JSON with source as key and rules as value. It loads all the CSS from the href links and tells all the styles applied from them You can modify the code to save all css into a .css file. Thereby combining all your css.
I faced this problem while trying to extend an existing class from GitHub. I'm gonna try to explain myself, first writing the class as I though it should be, and then the class as it is now.
What I though
namespace mycompany\CutreApi;
use mycompany\CutreApi\ClassOfVendor;
class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
public function whatever(): ClassOfVendor
{
return new ClassOfVendor();
}
}
What I've finally done
namespace mycompany\CutreApi;
use \vendor\AwesomeApi\ClassOfVendor;
class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
public function whatever(): ClassOfVendor
{
return new \mycompany\CutreApi\ClassOfVendor();
}
}
So seems that this errror raises also when you're using a method that return a namespaced class, and you try to return the same class but with other namespace. Fortunately I have found this solution, but I do not fully understand the benefit of this feature in php 7.2, for me it is normal to rewrite existing class methods as you need them, including the redefinition of input parameters and / or even behavior of the method.
One downside of the previous aproach, is that IDE's could not recognise the new methods implemented in \mycompany\CutreApi\ClassOfVendor(). So, for now, I will go with this implementation.
Currently done
namespace mycompany\CutreApi;
use mycompany\CutreApi\ClassOfVendor;
class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
public function getWhatever(): ClassOfVendor
{
return new ClassOfVendor();
}
}
So, instead of trying to use "whatever" method, I wrote a new one called "getWhatever". In fact both of them are doing the same, just returning a class, but with diferents namespaces as I've described before.
Hope this can help someone.
Create a css and set the value style="width:50px;"
in css code. Call the class of CSS in the drop down list. Then it will work.
You are implicitly returning undefined
. You need to return the element.
this.state.data.map(function(item, i){
console.log('test');
return <li>Test</li>
})
This worked for me in Windows:
{user}/.m2/repository
.lastupdated
". Windows will look through all subfolders for these files in the directory. .lastupdated
files. Maven > Update Project
.Force Update of Snapshots/Releases
". Try the following
typeField == typeof(string)
typeField == typeof(DateTime)
The typeof
operator in C# will give you a Type
object for the named type. Type
instances are comparable with the ==
operator so this is a good method for comparing them.
Note: If I remember correctly, there are some cases where this breaks down when the types involved are COM interfaces which are embedded into assemblies (via NoPIA). Doesn't sound like this is the case here.
If you are using 32-bit ubuntu (my case) then it is most likely that Android Studio has downloaded 64-bit version of adb
and fastboot
inside your sdk/platform-tools
folder. I think you already have installed adb (and fastboot). If you haven't then run these commands in terminal:
sudo add-apt-repository ppa:nilarimogard/webupd8
sudo apt-get update
sudo apt-get install android-tools-adb android-tools-fastboot
This will install 32-bit version of adb
and fastboot
. Now just replace the 64-bit adb
and fastboot
executable files in sdk/platform-tools
with the installed 32-bit versions:
cp /usr/bin/adb <path-to-your-adt-sdk-package>/sdk/platform-tools/adb
cp /usr/bin/fastboot <path-to-your-adt-sdk-package>/sdk/platformtools/fastboot
Now your android studio should be able to run your App in your device.
Python's print
function adds a newline character to its input. If you give it no input it will just print a newline character
print()
Will print an empty line. If you want to have an extra line after some text you're printing, you can a newline to your text
my_str = "hello world"
print(my_str + "\n")
If you're doing this a lot, you can also tell print
to add 2 newlines instead of just one by changing the end=
parameter (by default end="\n"
)
print("hello world", end="\n\n")
But you probably don't need this last method, the two before are much clearer.
I use Google Chart Tools https://developers.google.com/chart/ It's well documented and the charts look great. Being javascript, you can feed it json data via ajax.
When using Webpack you need to require
images in order for Webpack to process them, which would explain why external images load while internal do not, so instead of <img src={"/images/resto.png"} />
you need to use <img src={require('/images/image-name.png')} />
replacing image-name.png with the correct image name for each of them. That way Webpack is able to process and replace the source img.
Many of us know that the Popular Method of Escaping Single Quotes is by Doubling them up easily like below.
PRINT 'It''s me, Arul.';
we are going to look on some other alternate ways of escaping the single quotes.
1.UNICODE Characters
39 is the UNICODE character of Single Quote. So we can use it like below.
PRINT 'Hi,it'+CHAR(39)+'s Arul.';
PRINT 'Helo,it'+NCHAR(39)+'s Arul.';
2.QUOTED_IDENTIFIER
Another simple and best alternate solution is to use QUOTED_IDENTIFIER. When QUOTED_IDENTIFIER is set to OFF, the strings can be enclosed in double quotes. In this scenario, we don’t need to escape single quotes. So,this way would be very helpful while using lot of string values with single quotes. It will be very much helpful while using so many lines of INSERT/UPDATE scripts where column values having single quotes.
SET QUOTED_IDENTIFIER OFF;
PRINT "It's Arul."
SET QUOTED_IDENTIFIER ON;
CONCLUSION
The above mentioned methods are applicable to both AZURE and On Premises .
You need to grant SELECT permissions to the MySQL user who is connecting to MySQL. See:
http://dev.mysql.com/doc/refman/5.0/en/privilege-system.html
http://dev.mysql.com/doc/refman/5.0/en/user-account-management.html
You will need a reference to the specific frame you want to close but assuming you have the reference dispose()
should close the frame.
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
frameToClose.dispose();
}
});
The first thing you should do with date variables is confirm that R reads it as a Date. To do this, for the variable (i.e. vector/column) called Date, in the data frame called EPL2011_12, input
class(EPL2011_12$Date)
The output should read [1] "Date". If it doesn't, you should format it as a date by inputting
EPL2011_12$Date <- as.Date(EPL2011_12$Date, "%d-%m-%y")
Note that the hyphens in the date format ("%d-%m-%y") above can also be slashes ("%d/%m/%y"). Confirm that R sees it as a Date. If it doesn't, try a different formatting command
EPL2011_12$Date <- format(EPL2011_12$Date, format="%d/%m/%y")
Once you have it in Date format, you can use the subset
command, or you can use brackets
WhateverYouWant <- EPL2011_12[EPL2011_12$Date > as.Date("2014-12-15"),]
I think cl
isn't in your path. You need to add it there. The recommended way to do this is to launch a developer command prompt.
Quoting the article Setting the Path and Environment Variables for Command-Line Builds:
To open a Developer Command Prompt window
With the Windows 8 Start screen showing, type Visual Studio Tools. Notice that the search results change as you type; when Visual Studio Tools appears, choose it.
On earlier versions of Windows, choose Start, and then in the search box, type Visual Studio Tools. When Visual Studio Tools appears in the search results, choose it.
In the Visual Studio Tools folder, open the Developer Command Prompt for your version of Visual Studio. (To run as administrator, open the shortcut menu for the Developer Command Prompt and choose Run as Administrator.)
As the article notes, there are several different shortcuts for setting up different toolsets - you need to pick the suitable one.
If you already have a plain Command Prompt window open, you can run the batch file vcvarsall.bat
with the appropriate argument to set up the environment variables. Quoting the same article:
To run vcvarsall.bat
At the command prompt, change to the Visual C++ installation directory. (The location depends on the system and the Visual Studio installation, but a typical location is C:\Program Files (x86)\Microsoft Visual Studio version\VC.) For example, enter:
cd "\Program Files (x86)\Microsoft Visual Studio 12.0\VC"
To configure this Command Prompt window for 32-bit x86 command-line builds, at the command prompt, enter:
vcvarsall x86
From the article, the possible arguments are the following:
x86
(x86 32-bit native)x86_amd64
(x64 on x86 cross)x86_arm
(ARM on x86 cross)amd64
(x64 64-bit native)amd64_x86
(x86 on x64 cross)amd64_arm
(ARM on x64 cross)NOTE: The below solution no longer works on iOS 13+ devices - it will return garbage data.
Please use following code instead:
+ (NSString *)hexadecimalStringFromData:(NSData *)data
{
NSUInteger dataLength = data.length;
if (dataLength == 0) {
return nil;
}
const unsigned char *dataBuffer = (const unsigned char *)data.bytes;
NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
for (int i = 0; i < dataLength; ++i) {
[hexString appendFormat:@"%02x", dataBuffer[i]];
}
return [hexString copy];
}
Solution that worked prior to iOS 13:
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"<>"]];
token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
NSLog(@"this will return '32 bytes' in iOS 13+ rather than the token", token);
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
let tokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print("this will return '32 bytes' in iOS 13+ rather than the token \(tokenString)")
}
If the above issue occurs in Windows 7 or 10 based OS, the problem occurs because Tomcat is running as Windows Service. To stop Tomcat running as Windows Services, Open Windows Control Panel. Find the service "Apache Tomcat" and Stop it. The Another way is to kill the process running on port 8080 using cmd.
Open cmd running it as administrator.
library(caret)
intrain<-createDataPartition(y=sub_train$classe,p=0.7,list=FALSE)
training<-m_train[intrain,]
testing<-m_train[-intrain,]
You need to add a Serializable
attribute to the class which you want to serialize.
[Serializable]
public class OrgPermission
If you want to upload videos programatically, check the YouTube Data API for PHP
May be it is because you have applied some changes in your project and did not update their all references.
In my case I was getting this error because I have updated package names in my project but I forgot to update their references in TestNG.xml file. By correcting it, I solved this error.
Like this :
imageCreateFromPNG($var);
//I don't know where from you get your image, here it's in the png case
// and then :
list($width, $height) = getimagesize($image);
echo $width;
echo $height;
SHORTEST and FASTEST: str.replace(/ /g, '');
Benchmark:
Here my results - (2018.07.13) MacOs High Sierra 10.13.3 on Chrome 67.0.3396 (64-bit), Safari 11.0.3 (13604.5.6), Firefox 59.0.2 (64-bit) ):
Short string similar to examples from OP question
The fastest solution on all browsers is / /g
(regexp1a) - Chrome 17.7M (operation/sec), Safari 10.1M, Firefox 8.8M. The slowest for all browsers was split-join
solution. Change
to \s
or add +
or i
to regexp slows down processing.
For string about ~3 milion character results are:
You can run it on your machine: https://jsperf.com/remove-string-spaces/1
def updateJsonFile():
jsonFile = open("replayScript.json", "r") # Open the JSON file for reading
data = json.load(jsonFile) # Read the JSON into the buffer
jsonFile.close() # Close the JSON file
## Working with buffered content
tmp = data["location"]
data["location"] = path
data["mode"] = "replay"
## Save our changes to JSON file
jsonFile = open("replayScript.json", "w+")
jsonFile.write(json.dumps(data))
jsonFile.close()
After looking at this and trying it out I found it actually didn't allow more than one instance of jquery to run at a time. After searching around I found that this did just the trick and was a whole lot less code.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script>var $j = jQuery.noConflict(true);</script>
<script>
$(document).ready(function(){
console.log($().jquery); // This prints v1.4.2
console.log($j().jquery); // This prints v1.9.1
});
</script>
So then adding the "j" after the "$" was all I needed to do.
$j(function () {
$j('.button-pro').on('click', function () {
var el = $('#cnt' + this.id.replace('btn', ''));
$j('#contentnew > div').not(el).animate({
height: "toggle",
opacity: "toggle"
}, 100).hide();
el.toggle();
});
});
The documentation for required()
states:
To force a user to select an option from a select box, provide an empty options like
<option value="">Choose...</option>
By having value="none"
in your <option>
tag, you are preventing the validation call from ever being made. You can also remove your custom validation rule, simplifying your code. Here's a jsFiddle showing it in action:
If you can't change the value
attribute to the empty string, I don't know what to tell you...I couldn't find any way to get it to validate otherwise.