It's impossible to say without seeing your actual code. Likely the reason is a code path through your function that doesn't execute a return
statement. When the code goes down that path, the function ends with no value returned, and so returns None
.
Updated: It sounds like your code looks like this:
def b(self, p, data):
current = p
if current.data == data:
return True
elif current.data == 1:
return False
else:
self.b(current.next, data)
That else clause is your None
path. You need to return the value that the recursive call returns:
else:
return self.b(current.next, data)
BTW: using recursion for iterative programs like this is not a good idea in Python. Use iteration instead. Also, you have no clear termination condition.
**add the icon top button like this **
#copy_btn{_x000D_
align-items: center;_x000D_
position: absolute;_x000D_
width: 30px;_x000D_
height: 30px;_x000D_
background-color: Transparent;_x000D_
background-repeat:no-repeat;_x000D_
border: none;_x000D_
cursor:pointer;_x000D_
overflow: hidden;_x000D_
outline:none;_x000D_
}_x000D_
.icon_copy{_x000D_
position: absolute;_x000D_
padding: 0px;_x000D_
top:0;_x000D_
left: 0;_x000D_
width: 25px;_x000D_
height: 35px;_x000D_
_x000D_
}
_x000D_
<button id="copy_btn">_x000D_
_x000D_
<img class="icon_copy" src="./assest/copy.svg" alt="Copy Text">_x000D_
</button>
_x000D_
An easy fix is to just create a new branch for that commit and checkout to it: git checkout -b <branch-name> <commit-hash>
.
In this way, all the changes you made will be saved in that branch. In case you need to clean up your master branch from leftover commits be sure to run git reset --hard master
.
With this, you will be rewriting your branches so be sure not to disturb anyone with these changes. Be sure to take a look at this article for a better illustration of detached HEAD state.
With the new development center it is now easier:
1) Leave app domains blank.
2) Click Add Platform
3) Site URL should equal the full path of your local host.
4) Save Changes
If you know the cell number, then i would recommend using getDateCellValue() method Here's an example for the same that worked for me - java.util.Date date = row.getCell().getDateCellValue(); System.out.println(date);
I found this solution useful in a NodeJS app. I use it just in desperate cases because it launches a timeout in order to wait for the full page load.
The second argument is the callback function which is going to be called once the response is ready.
phantom = require('phantom');
var fullLoad = function(anUrl, callbackDone) {
phantom.create(function (ph) {
ph.createPage(function (page) {
page.open(anUrl, function (status) {
if (status !== 'success') {
console.error("pahtom: error opening " + anUrl, status);
ph.exit();
} else {
// timeOut
global.setTimeout(function () {
page.evaluate(function () {
return document.documentElement.innerHTML;
}, function (result) {
ph.exit(); // EXTREMLY IMPORTANT
callbackDone(result); // callback
});
}, 5000);
}
});
});
});
}
var callback = function(htmlBody) {
// do smth with the htmlBody
}
fullLoad('your/url/', callback);
I was searching an answer for this same question and found ENTRYPOINT in Dockerfile solution for me.
Dockerfile
...
ENTRYPOINT /my-script.sh ; /my-script2.sh ; /bin/bash
Now the scripts are executed when I start the container and I get the bash prompt after the scripts has been executed.
In WPF the titlebar is part of the non-client area, which can't be modified through the WPF window class. You need to manipulate the Win32 handles (if I remember correctly).
This article could be helpful for you: Custom Window Chrome in WPF.
string keyName=@"HKEY_LOCAL_MACHINE\System\CurrentControlSet\services\pcmcia";
string valueName="Start";
if (Registry.GetValue(keyName, valueName, null) == null)
{
//code if key Not Exist
}
else
{
//code if key Exist
}
Two possibilities:
You can see which table it was (one of them, anyway) by doing a "SHOW ENGINE INNODB STATUS" after the drop fails.
If it turns out to be the latter case, I'd dump and restore the whole server if you can.
MySQL 5.1 and above will give you the name of the table with the FK in the error message.
if (capital.touched && capital != undefined && capital.length < 1 ) {
//capital does exists
}
Ideone supports Python 2.6 and Python 3
You should use bootstarp's variables to control your font-weight if you want a more customized value and/or you're following a scheme that needs to be repeated ; Variables are used throughout the entire project as a way to centralize and share commonly used values like colors, spacing, or font stacks;
you can find all the documentation at http://getbootstrap.com/css.
Reverse one of the strings. Take the FFT of both (treating them as simple sequences of integers). Multiply the results together point-wise. Transform back using inverse FFT. The result will have a single peak if the strings are rotations of each other -- the position of the peak will indicate by how much they are rotated with respect to each other.
let 'parent' be the class-name of parent and 'child' be the class-name of child
.parent .child{
//css definition for child inside parent components
}
you can use this format to define CSS format to 'child' component inside the 'parent'
Beautify does a good job. It provides a "Beautify on save" option, so that you may use ctrl+s to reformate html, less, css, etc
To backup a single database from the command line, use osql or sqlcmd.
"C:\Program Files\Microsoft SQL Server\90\Tools\Binn\osql.exe"
-E -Q "BACKUP DATABASE mydatabase TO DISK='C:\tmp\db.bak' WITH FORMAT"
You'll also want to read the documentation on BACKUP and RESTORE and general procedures.
This worked:
$("#theSelectId").prepend("<option value='' selected='selected'></option>");
Firebug Output:
<select id="theSelectId">
<option selected="selected" value=""/>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
You could also use .prependTo
if you wanted to reverse the order:
?$("<option>", { value: '', selected: true }).prependTo("#theSelectId");???????????
I wouldn't expect anyone to find a "huge" performance difference between the two.
I guess the answer depends on the whether the collection you are trying to access has a faster indexer access implementation or a faster IEnumerator access implementation. Since IEnumerator often uses the indexer and just holds a copy of the current index position, I would expect enumerator access to be at least as slow or slower than direct index access, but not by much.
Of course this answer doesn't account for any optimizations the compiler may implement.
{% for i in range(10) %}
{{ i }}
{% endfor %}
If you want the margin-left
to work on a span
element you'll need to make it display: inline-block
or display:block
as well.
I just had this happen to me: I was getting the error only on my device and the simulator was working fine. I ended up having to reset my device and the error went away.
For starters:
<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.
This would be the optimal solution:
<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
change PYTHONHOME to the parent folder of the bin file of python, like /usr,which is the parent folder of /usr/bin.
No need to use second ajax function, you can get it back on success inside a function, another issue here is you don't know when the first ajax call finished, then, even if you use SESSION you may not get it within second AJAX call.
SO, I recommend using one AJAX call and get the value with success.
example: in first ajax call
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data){
console.log(data);
alert(data);
//or if the data is JSON
var jdata = jQuery.parseJSON(data);
}
});
As suggested by some, by using DATE(timestamp)
you are applying manipulation to the column and therefore you cannot rely on the index ordering.
However, using BETWEEN
would only be reliable if you include the milliseconds. In the example timestamp BETWEEN '2012-05-05 00:00:00' AND '2012-05-05 23:59:59'
you exclude records with a timestamp between 2012-05-05 23:59:59.001
and 2012-05-05 23:59:59.999
. However, even this method has some problems, because of the datatypes precision. Occasionally 999 milliseconds is rounded up.
The best thing to do is:
SELECT * FROM table
WHERE date>='2012-05-05' AND date<'2012-05-06'
No need to use .each
. click
already binds to all div
occurrences.
$('div').click(function(e) {
..
});
Note: use hard binding such as .click
to make sure dynamically loaded elements don't get bound.
I did it in this way:
git --version
, it should give you the latest version.Power has more precedence than multiply, so:
2**2*3 = (2^2)*3
2*2*3 = 2*2*3
The value
attribute on submit
-type <input>
elements controls the text displayed.
<input type="submit" class="like" value="Like" />
There is plugin called Partial Diff which helps to compare text selections within a file, across different files, or to the clipboard.
There are two main ways that you can do this. One of them is the standard CakePHP way, and the other is using a custom join.
It's worth pointing out that this advice is for CakePHP 2.x, not 3.x.
You would create a relationship with your User model and Messages Model, and use the containable behavior:
class User extends AppModel {
public $actsAs = array('Containable');
public $hasMany = array('Message');
}
class Message extends AppModel {
public $actsAs = array('Containable');
public $belongsTo = array('User');
}
You need to change the messages.from
column to be messages.user_id
so that cake can automagically associate the records for you.
Then you can do this from the messages controller:
$this->Message->find('all', array(
'contain' => array('User')
'conditions' => array(
'Message.to' => 4
),
'order' => 'Message.datetime DESC'
));
I recommend using the first method, because it will save you a lot of time and work. The first method also does the groundwork of setting up a relationship which can be used for any number of other find calls and conditions besides the one you need now. However, cakePHP does support a syntax for defining your own joins. It would be done like this, from the MessagesController
:
$this->Message->find('all', array(
'joins' => array(
array(
'table' => 'users',
'alias' => 'UserJoin',
'type' => 'INNER',
'conditions' => array(
'UserJoin.id = Message.from'
)
)
),
'conditions' => array(
'Message.to' => 4
),
'fields' => array('UserJoin.*', 'Message.*'),
'order' => 'Message.datetime DESC'
));
Note, I've left the field name messages.from
the same as your current table in this example.
Here is how you can do the first example using two relationships to the same model:
class User extends AppModel {
public $actsAs = array('Containable');
public $hasMany = array(
'MessagesSent' => array(
'className' => 'Message',
'foreignKey' => 'from'
)
);
public $belongsTo = array(
'MessagesReceived' => array(
'className' => 'Message',
'foreignKey' => 'to'
)
);
}
class Message extends AppModel {
public $actsAs = array('Containable');
public $belongsTo = array(
'UserFrom' => array(
'className' => 'User',
'foreignKey' => 'from'
)
);
public $hasMany = array(
'UserTo' => array(
'className' => 'User',
'foreignKey' => 'to'
)
);
}
Now you can do your find call like this:
$this->Message->find('all', array(
'contain' => array('UserFrom')
'conditions' => array(
'Message.to' => 4
),
'order' => 'Message.datetime DESC'
));
One simply solution would be create a Dictionary with names and values. Then using Contains() you can find the right value.
Dictionary<string, string> months = new Dictionary<string, string>()
{
{ "january", "01"},
{ "february", "02"},
{ "march", "03"},
{ "april", "04"},
{ "may", "05"},
{ "june", "06"},
{ "july", "07"},
{ "august", "08"},
{ "september", "09"},
{ "october", "10"},
{ "november", "11"},
{ "december", "12"},
};
foreach (var month in months)
{
if (StringThatContainsMonth.ToLower().Contains(month.Key))
{
string thisMonth = month.Value;
}
}
The result of equals in your example is obviously false because you are comparing the map a with some values in it with an empty map b (probably a copy and paste error). I recommend to use proper variable names (so you can avoid these kinds of errors) and make use of generics, too.
Map<String, String> first = new HashMap<String, String>();
first.put("f"+"oo", "bar"+"bar");
first.put("fo"+"o", "bar"+"bar");
Map second = new HashMap();
second.put("f"+"oo", "bar"+"bar");
second.put("fo"+"o", "bar"+"bar");
System.out.println("equals: " + first.equals(second));
The concatenation of your strings doesn't have any effect because it will be done at compile time.
You can only use date in input type="date"
as in format YYYY-MM-DD
I have implemented helper as formatDate
in NODE.js express-handlebars, don't need to be worry ... just use format as described in first line.
e.g:
< input type="date" id="date" name="date" class="form-control" value="{{formatDate invoice.date 'YYYY-MM-DD'}}" />
$data = DB::table('borrowers')
->join('loans', 'borrowers.id', '=', 'loans.borrower_id')
->select('borrowers.*', 'loans.*')
->where('loan_officers', 'like', '%' . $officerId . '%')
->where('loans.maturity_date', '<', date("Y-m-d"))
->get();
since you capitalized the word, I assume you are referring to the interface javax.naming.Context
. A few classes implement this interface, and at its simplest description, it (generically) is a set of name/object pairs.
You could use display: table-row-group
for your div.
<table>
<div style="display: table-row-group">
<tr><td></td></tr>
</div>
<div style="display: table-row-group">
<tr><td></td></tr>
</div>
</table>
Thread.currentThread().isInterrupted() is superbly working. but this code is only pause the timer.
This code is stop and reset the thread timer. h1 is handler name. This code is add on inside your button click listener. w_h =minutes w_m =milli sec i=counter
i=0;
w_h = 0;
w_m = 0;
textView.setText(String.format("%02d", w_h) + ":" + String.format("%02d", w_m));
hl.removeCallbacksAndMessages(null);
Thread.currentThread().isInterrupted();
}
});
}`
$(document).ready(function(){
$('form').find("input[type=search]").each(function(ev)
{
$(this).attr("placeholder", "Search Whatever you want");
});
});
If you are happy to use a 3rd party library, you can do this with Pandas. The benefits include seamless access to specialized methods and row / column labeling:
import pandas as pd
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]
df = pd.DataFrame(list(zip(*[list1, list2, list3]))).add_prefix('Col')
df.to_csv('file.csv', index=False)
print(df)
Col0 Col1 Col2
0 1 4 7
1 2 5 8
2 3 6 9
class1 item = lst[index];
item.foo = bar;
PUT is meant as a a method for "uploading" stuff to a particular URI, or overwriting what is already in that URI.
POST, on the other hand, is a way of submitting data RELATED to a given URI.
Refer to the HTTP RFC
I to had a similar doubt what I got to know was getActivity()
returns the Activity
to which the fragment is associated.
The getActivity()
method is used generally in static fragment as the associated activity will not be static and non static member cannot be used in static member.
I had a moment, so, although you've already accepted an answer, I thought I'd contribute the following:
Number.prototype.between = function(a, b) {_x000D_
var min = Math.min.apply(Math, [a, b]),_x000D_
max = Math.max.apply(Math, [a, b]);_x000D_
return this > min && this < max;_x000D_
};_x000D_
_x000D_
var windowSize = 550;_x000D_
_x000D_
console.log(windowSize.between(500, 600));
_x000D_
Or, if you'd prefer to have the option to check a number is in the defined range including the end-points:
Number.prototype.between = function(a, b, inclusive) {_x000D_
var min = Math.min.apply(Math, [a, b]),_x000D_
max = Math.max.apply(Math, [a, b]);_x000D_
return inclusive ? this >= min && this <= max : this > min && this < max;_x000D_
};_x000D_
_x000D_
var windowSize = 500;_x000D_
_x000D_
console.log(windowSize.between(500, 603, true));
_x000D_
Edited to add a minor amendment to the above, given that – as noted in the comments –
…
Function.prototype.apply()
is slow! Besides calling it when you have a fixed amount of arguments is pointless…
it was worth removing the use of Function.prototype.apply()
, which yields the amended versions of the above methods, firstly without the 'inclusive' option:
Number.prototype.between = function(a, b) {_x000D_
var min = Math.min(a, b),_x000D_
max = Math.max(a, b);_x000D_
_x000D_
return this > min && this < max;_x000D_
};_x000D_
_x000D_
var windowSize = 550;_x000D_
_x000D_
console.log(windowSize.between(500, 600));
_x000D_
And with the 'inclusive' option:
Number.prototype.between = function(a, b, inclusive) {_x000D_
var min = Math.min(a, b),_x000D_
max = Math.max(a, b);_x000D_
_x000D_
return inclusive ? this >= min && this <= max : this > min && this < max;_x000D_
}_x000D_
_x000D_
var windowSize = 500;_x000D_
_x000D_
console.log(windowSize.between(500, 603, true));
_x000D_
References:
Use Mach-OView for viewing all the Symbols in dylib
Try this
.nav.navbar-nav.navbar-right li a span{
color: blue;
}
If it doesn't work try this
.nav.navbar-nav.navbar-right li a {
color: blue;
}
If you use Tomcat, add '-Dorg.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true' in VM properties.
https://tomcat.apache.org/tomcat-7.0-doc/config/systemprops.html#Security
I using "+" (plus) to insert div to html :
document.getElementById('idParent').innerHTML += '<div id="idChild"> content html </div>';
Hope this help.
To elaborate on Rahul Mahadik's answer, this works for MVC5 C#.NET:
AllowSameSiteAttribute.cs
public class AllowSameSiteAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var response = filterContext.RequestContext.HttpContext.Response;
if(response != null)
{
response.AddHeader("Set-Cookie", "HttpOnly;Secure;SameSite=Strict");
//Add more headers...
}
base.OnActionExecuting(filterContext);
}
}
HomeController.cs
[AllowSameSite] //For the whole controller
public class UserController : Controller
{
}
or
public class UserController : Controller
{
[AllowSameSite] //For the method
public ActionResult Index()
{
return View();
}
}
This blog post could be a duplicate of Phil's but it might help:
In some languages True is just and alias for the number. You can learn more why this is by reading more about boolean logic.
You can also use
CREATE PROCEDURE [Search](
@Filter nvarchar(max)
)
AS
BEGIN
SELECT name
FROM procedures
WHERE definition LIKE '%'+@Filter+'%'
END
and then run
exec [Search] 'text'
Its a common error which happens when we try to access a database which doesn't exist. So create the database using
CREATE DATABASE blog_development;
The error commonly occours when we have dropped the database using
DROP DATABASE blog_development;
and then try to access the database.
There are already a lot of answers but here is another approach if you're in the Rails world:
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].select &:present?
I had this error when i renamed the pc in the windows-properties. The pc-name must be updated in the listener.ora
-file
Here is a one line lambda that also works:
df["TrueFalse"] = df['col1'].apply(lambda x: 1 if any(i in x for i in searchfor) else 0)
Input:
searchfor = ['og', 'at']
df = pd.DataFrame([('cat', 1000.0), ('hat', 2000000.0), ('dog', 1000.0), ('fog', 330000.0),('pet', 330000.0)], columns=['col1', 'col2'])
col1 col2
0 cat 1000.0
1 hat 2000000.0
2 dog 1000.0
3 fog 330000.0
4 pet 330000.0
Apply Lambda:
df["TrueFalse"] = df['col1'].apply(lambda x: 1 if any(i in x for i in searchfor) else 0)
Output:
col1 col2 TrueFalse
0 cat 1000.0 1
1 hat 2000000.0 1
2 dog 1000.0 1
3 fog 330000.0 1
4 pet 330000.0 0
Actually, when we want this, we want to change the action depending on which submit button we press.
Here you do not need even assign name
or id
to the form. Just use the form
property of the clicked element:
<form action = "/default/page" >
<input type=submit onclick='this.form.action="/this/page";' value="Save">
<input type=submit onclick='this.form.action="/that/page";' value="Cancel">
</form>
If you have reason to avoid the use of the datetime
module, then these functions will work.
def is_leap_year(year):
""" if year is a leap year return True
else return False """
if year % 100 == 0:
return year % 400 == 0
return year % 4 == 0
def doy(Y,M,D):
""" given year, month, day return day of year
Astronomical Algorithms, Jean Meeus, 2d ed, 1998, chap 7 """
if is_leap_year(Y):
K = 1
else:
K = 2
N = int((275 * M) / 9.0) - K * int((M + 9) / 12.0) + D - 30
return N
def ymd(Y,N):
""" given year = Y and day of year = N, return year, month, day
Astronomical Algorithms, Jean Meeus, 2d ed, 1998, chap 7 """
if is_leap_year(Y):
K = 1
else:
K = 2
M = int((9 * (K + N)) / 275.0 + 0.98)
if N < 32:
M = 1
D = N - int((275 * M) / 9.0) + K * int((M + 9) / 12.0) + 30
return Y, M, D
You would use the WITH ADMIN OPTION
option in the GRANT
statement
GRANT CREATE SESSION TO <<username>> WITH ADMIN OPTION
As other answers have mentioned, the following calls will compute the hash:
MD5Context md5;
MD5Init(&md5);
MD5Update(&md5, data, datalen);
MD5Final(digest, &md5);
The purpose of splitting it up into that many functions is to let you stream large datasets.
For example, if you're hashing a 10GB file and it doesn't fit into ram, here's how you would go about doing it. You would read the file in smaller chunks and call MD5Update
on them.
MD5Context md5;
MD5Init(&md5);
fread(/* Read a block into data. */)
MD5Update(&md5, data, datalen);
fread(/* Read the next block into data. */)
MD5Update(&md5, data, datalen);
fread(/* Read the next block into data. */)
MD5Update(&md5, data, datalen);
...
// Now finish to get the final hash value.
MD5Final(digest, &md5);
You could try using a Polyfill. The following Polyfill was published in 2019 and did the trick for me. It assigns the Promise function to the window object.
used like: window.Promise
https://www.npmjs.com/package/promise-polyfill
If you want more information on Polyfills check out the following MDN web doc https://developer.mozilla.org/en-US/docs/Glossary/Polyfill
See this: Demo
$('#cat_icon,.panel_title').click(function () {
$('#categories,#cat_icon').stop().slideToggle('slow');
});
Update : To slide from left to right: Demo2
Note: Second one uses jquery-ui also
I've found an elegant one line solution using LINQ or Lambda expression, both work the same (LINQ is converted to Lambda when program is compiled). The solution works for any array type and for any number of arrays.
Using LINQ:
public static T[] ConcatArraysLinq<T>(params T[][] arrays)
{
return (from array in arrays
from arr in array
select arr).ToArray();
}
Using Lambda:
public static T[] ConcatArraysLambda<T>(params T[][] arrays)
{
return arrays.SelectMany(array => array.Select(arr => arr)).ToArray();
}
I've provided both for one's preference. Performance wise @Sergey Shteyn's or @deepee1's solutions are a bit faster, Lambda expression being the slowest. Time taken is dependant on type(s) of array elements, but unless there are millions of calls, there is no significant difference between the methods.
Sort each element then look for duplicates. There's a built-in function for sorting so you do not need to import anything
One good option.
import static some.Util.*;
public class Java {
public static void main(String[] args) {
String sql = $(
"Select * from java",
"join some on ",
"group by"
);
System.out.println(sql);
}
}
public class Util {
public static String $(String ...sql){
return String.join(System.getProperty("line.separator"),sql);
}
}
Why not downloading the python installer here ? It make the work for you when you check the path installation
double a=59.0/4;
int b=59/4;
if(a-b>=0.5){
b++;
}
printf("%d",b);
In my experience, printf()
hauls in more code than puts()
regardless of the format string.
If I don't need the formatting, I don't use printf
. However, fwrite
to stdout
works a lot faster than puts
.
static const char my_text[] = "Using fwrite.\n";
fwrite(my_text, 1, sizeof(my_text) - sizeof('\0'), stdout);
Note: per comments, '\0' is an integer constant. The correct expression should be sizeof(char)
as indicated by the comments.
Remove current REcaptcha key, then register new key and set your key settings with domains:
127.0.0.1
localhost
I had the same problem i solved it in that way: My ajax:
event.preventDefault();
$.ajax('file.php', {
method: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({tab}),
success: function(php_response){
if (php_response == 'item')
{
console.log('it works');
}
}
})
Ok. The problem is not with json but only php response. Before: my php response was:
echo 'item';
Now:
$variable = 'item';
echo json.encode($variable);
Now my success working. PS. Sorry if something is wrong but it is my first comment on this forum :)
list($width, $height) = getimagesize($filename)
Or,
$data = getimagesize($filename);
$width = $data[0];
$height = $data[1];
Use this code:
Intent intent=new Intent(context,SecondActivty.class);
startActivity(intent);
finish();
context: refer to current activity context,
please make sure that you have added activity in android manifest file.
Following code for adding activity in android manifest file
<Activity name=".SecondActivity">
</Activity>
The HTML4 spec for the <input>
element specifies the following script events are available:
onfocus, onblur, onselect, onchange, onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup
here's an example that bind's to all these events and shows what's going on http://jsfiddle.net/pxfunc/zJ7Lf/
I think you can filter out which events are truly relevent to your situation and detect what the text value was before and after the event to determine a change
Various forms depending on type of List, for Array List:
val myList = mutableListOf<Kolory>()
// or more specifically use the helper for a specific list type
val myList = arrayListOf<Kolory>()
For LinkedList:
val myList = linkedListOf<Kolory>()
// same as
val myList: MutableList<Kolory> = linkedListOf()
For other list types, will be assumed Mutable if you construct them directly:
val myList = ArrayList<Kolory>()
// or
val myList = LinkedList<Kolory>()
This holds true for anything implementing the List
interface (i.e. other collections libraries).
No need to repeat the type on the left side if the list is already Mutable. Or only if you want to treat them as read-only, for example:
val myList: List<Kolory> = ArrayList()
In my case, the problem was with the specific box I was trying to use ubuntu/xenial64, I just had to switch to centos/7 and all those errors disappeared.
Hope this helps someone.
I read this question looking for an answer, and didn't like any of them.
So I wrote a quick and dirty solution. Just put this somewhere on your sys.path, and it'll add any directory under folder
(from the current working directory), or under abspath
:
#using.py
import sys, os.path
def all_from(folder='', abspath=None):
"""add all dirs under `folder` to sys.path if any .py files are found.
Use an abspath if you'd rather do it that way.
Uses the current working directory as the location of using.py.
Keep in mind that os.walk goes *all the way* down the directory tree.
With that, try not to use this on something too close to '/'
"""
add = set(sys.path)
if abspath is None:
cwd = os.path.abspath(os.path.curdir)
abspath = os.path.join(cwd, folder)
for root, dirs, files in os.walk(abspath):
for f in files:
if f[-3:] in '.py':
add.add(root)
break
for i in add: sys.path.append(i)
>>> import using, sys, pprint
>>> using.all_from('py') #if in ~, /home/user/py/
>>> pprint.pprint(sys.path)
[
#that was easy
]
And I like it because I can have a folder for some random tools and not have them be a part of packages or anything, and still get access to some (or all) of them in a couple lines of code.
This should do the trick, to produce the data frame you asked for, using only base R:
df <- data.frame(cond=c(rep("x", times=length(x)),
rep("y", times=length(y))),
rating=c(x, y))
df
cond rating
1 x 1
2 x 2
3 x 3
4 y 100
5 y 200
6 y 300
However, from your initial description, I'd say that this is perhaps a more likely usecase:
df2 <- data.frame(x, y)
colnames(df2) <- c(x_name, y_name)
df2
cond rating
1 1 100
2 2 200
3 3 300
[edit: moved parentheses in example 1]
function function_one() {
function_two();
}
function function_two() {
//enter code here
}
What you are doing raises an exception (and rightfully so).
You can always do
try{
window.a.b.c
}catch(e){
console.log("YO",e)
}
But I wouldn't, instead think of your use case.
Why are you accessing data, 6 levels nested that you are unfamiliar of? What use case justifies this?
Usually, you'd like to actually validate what sort of object you're dealing with.
Also, on a side note you should not use statements like if(a.b)
because it will return false if a.b is 0 or even if it is "0". Instead check if a.b !== undefined
if exist yourfilename (
echo Yes
) else (
echo No
)
Replace yourfilename with the name of your file.
if exist yourfoldername\ (
echo Yes
) else (
echo No
)
Replace yourfoldername with the name of your folder.
A trailing backslash (\
) seems to be enough to distinguish between directories and ordinary files.
Here is my function for finding multiple occurrences. Unlike the other solutions here, it supports the optional start and end parameters for slicing, just like str.index
:
def all_substring_indexes(string, substring, start=0, end=None):
result = []
new_start = start
while True:
try:
index = string.index(substring, new_start, end)
except ValueError:
return result
else:
result.append(index)
new_start = index + len(substring)
When indexed view is not an option, and quick updates are not necessary, you can create a hack cache table:
select * into cachetablename from myviewname
alter table cachetablename add primary key (columns)
-- OR alter table cachetablename add rid bigint identity primary key
create index...
then sp_rename view/table or change any queries or other views that reference it to point to the cache table.
schedule daily/nightly/weekly/whatnot refresh like
begin transaction
truncate table cachetablename
insert into cachetablename select * from viewname
commit transaction
NB: this will eat space, also in your tx logs. Best used for small datasets that are slow to compute. Maybe refactor to eliminate "easy but large" columns first into an outer view.
Object oriented style:
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
Procedural style:
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');
I like this approach because it is simple and clean:
String getCompaniesIdAndName = " select "
+ " c.id as id, "
+ " c.name as name "
+ " from Company c ";
@Query(value = getCompaniesWithoutAccount)
Set<CompanyIdAndName> findAllIdAndName();
public static interface CompanyIdAndName extends DTO {
Integer getId();
String getName();
}
I tried the solutions mentioned above and none of them worked for me. I used JSON.parse and it worked:
$http.get('/api/getAdPolling')
.success(function (data) {
console.log('success: ' + data.length);
if (JSON.stringify(data) != "not found") {
$scope.adPoll = JSON.parse(data);
}
})
.error(function (data) {
console.log('Error: ' + data);
});
This isn't a single JSON object. You have an array of JSON objects. You need to loop over array first and then access each object. Maybe the following kickoff example is helpful:
var arrayOfObjects = [{
"id": 28,
"Title": "Sweden"
}, {
"id": 56,
"Title": "USA"
}, {
"id": 89,
"Title": "England"
}];
for (var i = 0; i < arrayOfObjects.length; i++) {
var object = arrayOfObjects[i];
for (var property in object) {
alert('item ' + i + ': ' + property + '=' + object[property]);
}
// If property names are known beforehand, you can also just do e.g.
// alert(object.id + ',' + object.Title);
}
If the array of JSON objects is actually passed in as a plain vanilla string, then you would indeed need eval()
here.
var string = '[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]';
var arrayOfObjects = eval(string);
// ...
To learn more about JSON, check MDN web docs: Working with JSON .
Another cause for this is if you have the same database restored under a different name. Delete the existing one and then restoring solved it for me.
There are several examples on DZone Snippets if you want to roll your own that works with a Collection. For example:
public static String join(AbstractCollection<String> s, String delimiter) {
if (s == null || s.isEmpty()) return "";
Iterator<String> iter = s.iterator();
StringBuilder builder = new StringBuilder(iter.next());
while( iter.hasNext() )
{
builder.append(delimiter).append(iter.next());
}
return builder.toString();
}
Single elements of a tuple a
can be accessed -in an indexed array-like fashion-
via a[0]
, a[1]
, ... depending on the number of elements in the tuple.
If your tuple is a=(3,"a")
a[0]
yields 3
,a[1]
yields "a"
def tup():
return (3, "hello")
tup()
returns a 2-tuple.
In order to "solve"
i = 5 + tup() # I want to add just the three
you select the 3 by
tup()[0| #first element
so in total
i = 5 + tup()[0]
Go with namedtuple that allows you to access tuple elements by name (and by index). Details at https://docs.python.org/3/library/collections.html#collections.namedtuple
>>> import collections
>>> MyTuple=collections.namedtuple("MyTuple", "mynumber, mystring")
>>> m = MyTuple(3, "hello")
>>> m[0]
3
>>> m.mynumber
3
>>> m[1]
'hello'
>>> m.mystring
'hello'
It is Debian convention to separate shared libraries into their runtime components (libmagic1: /usr/lib/libmagic.so.1 ? libmagic.so.1.0.0
) and their development components (libmagic-dev: /usr/lib/libmagic.so ? …
).
Because the library's soname is libmagic.so.1
, that's the string that gets embedded into the executable so that's the file that is loaded when the executable is run.
However, because the library is specified as -lmagic
to the linker, it looks for libmagic.so
, which is why it is needed for development.
See Diego E. Pettenò: Linkers and names for details on how this all works on Linux.
In short, you should apt-get install libmagic-dev
. This will not only give you libmagic.so
but also other files necessary for compiling like /usr/include/magic.h
.
type FunctionName = (n: inputType) => any;
class ClassName {
save(callback: FunctionName) : void {
callback(data);
}
}
This surely aligns with the functional programming paradigm.
To iterate through the keys of an object, use a for .. in
loop:
for (var key in json_obj) {
if (json_obj.hasOwnProperty(key)) {
// do something with `key'
}
}
To test all elements for empty children, you can use a recursive approach: iterate through all elements and recursively test their children too.
Removing a property of an object can be done by using the delete
keyword:
var someObj = {
"one": 123,
"two": 345
};
var key = "one";
delete someObj[key];
console.log(someObj); // prints { "two": 345 }
Documentation:
I would use
like 'Express Edition%'
Example:
DECLARE @edition varchar(50);
set @edition = cast((select SERVERPROPERTY ('edition')) as varchar)
DECLARE @isExpress bit
if @edition like 'Express Edition%'
set @isExpress = 1;
else
set @isExpress = 0;
print @isExpress
You can use virtualenv --clear
. which won't install any packages, then install the ones you want.
Deleting some of the JDT indexes (in .metadata.plugins\org.eclipse.jdt.core), particularly the big files, often fix or ease the problem for me.
Here is a function to launch a background process in PHP. Finally created one that actually works on Windows too, after a lot of reading and testing different approaches and parameters.
function LaunchBackgroundProcess($command){
// Run command Asynchroniously (in a separate thread)
if(PHP_OS=='WINNT' || PHP_OS=='WIN32' || PHP_OS=='Windows'){
// Windows
$command = 'start "" '. $command;
} else {
// Linux/UNIX
$command = $command .' /dev/null &';
}
$handle = popen($command, 'r');
if($handle!==false){
pclose($handle);
return true;
} else {
return false;
}
}
Note 1: On windows, do not use /B
parameter as suggested elsewhere. It forces process to run the same console window as start
command itself, resulting in the process being processed synchronously. To run the process in a separate thread (asynchronously), do not use /B
.
Note 2: The empty double quotes after start ""
are required if the command is a quoted path. start
command interprets the first quoted parameter as window title.
You can extend the abstract class with an anonymous class in your test. For example (using Junit 4):
private AbstractClassName classToTest;
@Before
public void preTestSetup()
{
classToTest = new AbstractClassName() { };
}
// Test the AbstractClassName methods.
The best and easy solution for solving this issue is pass your data from this function in controller.
$scope.trustSrcurl = function(data)
{
return $sce.trustAsResourceUrl(data);
}
In html page
<iframe class="youtube-player" type="text/html" width="640" height="385" ng-src="{{trustSrcurl(video.src)}}" allowfullscreen frameborder="0"></iframe>
A bit involved. Easiest would be to refer to this SQL Fiddle I created for you that produces the exact result. There are ways you can improve it for performance or other considerations, but this should hopefully at least be clearer than some alternatives.
The gist is, you get a canonical ranking of your data first, then use that to segment the data into groups, then find an end date for each group, then eliminate any intermediate rows. ROW_NUMBER() and CROSS APPLY help a lot in doing it readably.
EDIT 2019:
The SQL Fiddle does in fact seem to be broken, for some reason, but it appears to be a problem on the SQL Fiddle site. Here's a complete version, tested just now on SQL Server 2016:
CREATE TABLE Source
(
EmployeeID int,
DateStarted date,
DepartmentID int
)
INSERT INTO Source
VALUES
(10001,'2013-01-01',001),
(10001,'2013-09-09',001),
(10001,'2013-12-01',002),
(10001,'2014-05-01',002),
(10001,'2014-10-01',001),
(10001,'2014-12-01',001)
SELECT *,
ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS EntryRank,
newid() as GroupKey,
CAST(NULL AS date) AS EndDate
INTO #RankedData
FROM Source
;
UPDATE #RankedData
SET GroupKey = beginDate.GroupKey
FROM #RankedData sup
CROSS APPLY
(
SELECT TOP 1 GroupKey
FROM #RankedData sub
WHERE sub.EmployeeID = sup.EmployeeID AND
sub.DepartmentID = sup.DepartmentID AND
NOT EXISTS
(
SELECT *
FROM #RankedData bot
WHERE bot.EmployeeID = sup.EmployeeID AND
bot.EntryRank BETWEEN sub.EntryRank AND sup.EntryRank AND
bot.DepartmentID <> sup.DepartmentID
)
ORDER BY DateStarted ASC
) beginDate (GroupKey);
UPDATE #RankedData
SET EndDate = nextGroup.DateStarted
FROM #RankedData sup
CROSS APPLY
(
SELECT TOP 1 DateStarted
FROM #RankedData sub
WHERE sub.EmployeeID = sup.EmployeeID AND
sub.DepartmentID <> sup.DepartmentID AND
sub.EntryRank > sup.EntryRank
ORDER BY EntryRank ASC
) nextGroup (DateStarted);
SELECT * FROM
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY GroupKey ORDER BY EntryRank ASC) AS GroupRank FROM #RankedData
) FinalRanking
WHERE GroupRank = 1
ORDER BY EntryRank;
DROP TABLE #RankedData
DROP TABLE Source
If you want to check if a string contains substring or not using regex, the closest you can do is by using find() -
private static final validPattern = "\\bstores\\b.*\\bstore\\b.*\\bproduct\\b"
Pattern pattern = Pattern.compile(validPattern);
Matcher matcher = pattern.matcher(inputString);
System.out.print(matcher.find()); // should print true or false.
Note the difference between matches() and find(), matches() return true if the whole string matches the given pattern. find() tries to find a substring that matches the pattern in a given input string. Also by using find() you don't have to add extra matching like - (?s).* at the beginning and .* at the end of your regex pattern.
The command is date
To customise the output there are a myriad of options available, see date --help
for a list.
For example, date '+%A %W %Y %X'
gives Tuesday 34 2013 08:04:22
which is the name of the day of the week, the week number, the year and the time.
I have been trying to do the same myself. What I found was that the "Export Ant Buildfile" gets kicked off in the org.eclipse.ant.internal.ui.datatransfer.AntBuildfileExportPage.java file. This resides in the org.eclipse.ant.ui plugin.
To view the source, use the Plug-in Development perspective and open the Plug-ins view. Then right-click on the org.eclipse.ant.ui plugin and select import as > source project.
My plan is to create a Java program to programmatically kick off the ant buildfile generation and call this in an Ant file every time I build by adding the ant file to the builders of my projects (Right-click preferences on a projet, under the builders tab).
Like this?
In LINQ:
var sortedList = originalList.OrderBy(foo => !foo.AVC)
.ToList();
Or in-place:
originalList.Sort((foo1, foo2) => foo2.AVC.CompareTo(foo1.AVC));
As Jon Skeet says, the trick here is knowing that false
is considered to be 'smaller' than true.
If you find that you are doing these ordering operations in lots of different places in your code, you might want to get your type Foo
to implement the IComparable<Foo>
and IComparable
interfaces.
Run the given command
git add . && git commit -m "Changes Committed"
However, even if it seems a single command, It's two separate command runs one by one. Here we just used &&
to combine them. It's not much different than running
git add .
and git commit -m "Changes Committed"
separately. You can run multiple commands together but sequence matters here. How if you want to push the changes to remote server along with staging and commit you can do it as given,
git add . && git commit -m "Changes Committed" && git push origin master
Instead, if you change the sequence and put the push
to first, It will be executed first and does not give desired push after staging and commit just because it already ran first.
&&
runs the second command on the line when the first command comes back successfully, or with an error level of 0. The opposite of &&
is ||
, which runs the second command when the first command is unsuccessful, or with an error level of 1.
Alternatively, you can create alise as git config --global alias.addcommit '!git add -a && git commit -m'
and use it as git addcommit -m "Added and commited new files"
The problem with camel case is that there are often different interpretations of words - for example, checkinService vs checkInService. Going along with Aaron's answer, it is difficult with auto-completion if you have many similarly named repos to have to constantly check if the person who created the repo you care about used a certain breakdown of the upper and lower cases. avoid upper case.
His point about dashes is also well-advised.
StringUtils is in org.apache.commons.lang.* not in java.lang.*. Most importantly learn to read javadoc file. All java programmers after learning basic java learn to read javadoc, execute tests from public projects, use those jars in their projects.
If you are working on eclipse or netbeans you can make a directory (folder) called lib in your project (from within the IDE) and copy the downloaded jar from hard disk and paste it in that directory from eclipse or netbeans. Next you have to add it to your project.
E.g in case of eclipse from Project->Properties select Java Build Path -> Add Jars, point to the jar you copied earlier. In your case it might be commons-lang-version.jar.
After this step whenever you add above import in a java file, those libraries will be available on your project (in case of eclipse or netbeans).
From where do you get the jar for commons-lang? Root directory of any apache commons is http://commons.apache.org/ And for commons-lang it is http://commons.apache.org/lang/
Some of these libraries contain User Guide and other help to get you started, but javadoc is the ultimate guide for any java programmer.
It is right time you asked about this library, because you should never re-invent the wheel. Use apache commons and other well tested libraries whenever possible. By using those libraries you omit some common human errors and even test those libraries (using is testing). Sometimes in future when using this library, you may even write some modifications or addition to this library. If you contribute back, the world benefits.
Most common use of StringUtils is in web projects (when you want to check for blank or null strings, checking if a string is number, splitting strings with some token). StringUtils helps to get rid of those nasty NumberFormat and Null exceptions. But StringUtils can be used anywhere String is used.
Here, the paragraph is printed only 'isValid' is true / it contains any value
<p *ngIf="isValid ? true : false">Paragraph</p>
<?
# ------- The graph values in the form of associative array
$values=array(
"Jan" => 110,
"Feb" => 130,
"Mar" => 215,
"Apr" => 81,
"May" => 310,
"Jun" => 110,
"Jul" => 190,
"Aug" => 175,
"Sep" => 390,
"Oct" => 286,
"Nov" => 150,
"Dec" => 196
);
$img_width=450;
$img_height=300;
$margins=20;
# ---- Find the size of graph by substracting the size of borders
$graph_width=$img_width - $margins * 2;
$graph_height=$img_height - $margins * 2;
$img=imagecreate($img_width,$img_height);
$bar_width=20;
$total_bars=count($values);
$gap= ($graph_width- $total_bars * $bar_width ) / ($total_bars +1);
# ------- Define Colors ----------------
$bar_color=imagecolorallocate($img,0,64,128);
$background_color=imagecolorallocate($img,240,240,255);
$border_color=imagecolorallocate($img,200,200,200);
$line_color=imagecolorallocate($img,220,220,220);
# ------ Create the border around the graph ------
imagefilledrectangle($img,1,1,$img_width-2,$img_height-2,$border_color);
imagefilledrectangle($img,$margins,$margins,$img_width-1-$margins,$img_height-1-$margins,$background_color);
# ------- Max value is required to adjust the scale -------
$max_value=max($values);
$ratio= $graph_height/$max_value;
# -------- Create scale and draw horizontal lines --------
$horizontal_lines=20;
$horizontal_gap=$graph_height/$horizontal_lines;
for($i=1;$i<=$horizontal_lines;$i++){
$y=$img_height - $margins - $horizontal_gap * $i ;
imageline($img,$margins,$y,$img_width-$margins,$y,$line_color);
$v=intval($horizontal_gap * $i /$ratio);
imagestring($img,0,5,$y-5,$v,$bar_color);
}
# ----------- Draw the bars here ------
for($i=0;$i< $total_bars; $i++){
# ------ Extract key and value pair from the current pointer position
list($key,$value)=each($values);
$x1= $margins + $gap + $i * ($gap+$bar_width) ;
$x2= $x1 + $bar_width;
$y1=$margins +$graph_height- intval($value * $ratio) ;
$y2=$img_height-$margins;
imagestring($img,0,$x1+3,$y1-10,$value,$bar_color);imagestring($img,0,$x1+3,$img_height-15,$key,$bar_color);
imagefilledrectangle($img,$x1,$y1,$x2,$y2,$bar_color);
}
header("Content-type:image/png");
imagepng($img);
$_REQUEST['asdfad']=234234;
?>
HTTP
is stateless. TCP
is stateful.
There is no so-called HTTP connection
, but only HTTP request
and HTTP response
. We don't need anything to be maintained to make another HTTP request
.
A connection header that is "keep-alive" means the TCP
will be reused by the subsequent HTTP
requests and responses, instead of disconnecting and re-establishing TCP
connection all the time.
Just adding another solution that works for me.. You can simply append it in the marker options:
var marker = new google.maps.Marker({
map: map,
position: position,
// Custom Attributes / Data / Key-Values
store_id: id,
store_address: address,
store_type: type
});
And then retrieve them with:
marker.get('store_id');
marker.get('store_address');
marker.get('store_type');
What worked for me was going to the article someone else had already mentioned, but keying on this piece:
application.config.backup is not created by automatic backup. The backup files are in %systemdrive%\inetpub\history directory. Automatic backup is also a Vista SP1 and above feature. More information can be found in this blog post, http://blogs.iis.net/bills/archive/2008/03/24/how-to-backup-restore-iis7-configuration.aspx
I was able to find backups of my settings from when I had first installed IIS, and just copy and replace the files in the inetsrv\config directory.
You can use the setupFiles
feature of the Jest configuration. As the documentation said that,
A list of paths to modules that run some code to configure or set up the testing environment. Each setupFile will be run once per test file. Since every test runs in its own environment, these scripts will be executed in the testing environment immediately before executing the test code itself.
npm install dotenv
dotenv that uses to access environment variable.
Create your .env
file to the root directory of your application and add this line into it:
#.env
APP_PORT=8080
Create your custom module file as its name being someModuleForTest.js and add this line into it:
// someModuleForTest.js
require("dotenv").config()
Update your jest.config.js
file like this:
module.exports = {
setupFiles: ["./someModuleForTest"]
}
You can access an environment variable within all test blocks.
test("Some test name", () => {
expect(process.env.APP_PORT).toBe("8080")
})
That is not changing due to the default theme set to the screen.
So just change them for the widget you are drawing by wrapping your TextField with new ThemeData()
child: new Theme(
data: new ThemeData(
primaryColor: Colors.redAccent,
primaryColorDark: Colors.red,
),
child: new TextField(
decoration: new InputDecoration(
border: new OutlineInputBorder(
borderSide: new BorderSide(color: Colors.teal)),
hintText: 'Tell us about yourself',
helperText: 'Keep it short, this is just a demo.',
labelText: 'Life story',
prefixIcon: const Icon(
Icons.person,
color: Colors.green,
),
prefixText: ' ',
suffixText: 'USD',
suffixStyle: const TextStyle(color: Colors.green)),
),
));
Short answer: You can't. rm
removes files blindly, with no concept of 'trash'.
Some Unix and Linux systems try to limit its destructive ability by aliasing it to rm -i
by default, but not all do.
Long answer: Depending on your filesystem, disk activity, and how long ago the deletion occured, you may be able to recover some or all of what you deleted. If you're using an EXT3 or EXT4 formatted drive, you can check out extundelete
.
In the future, use rm
with caution. Either create a del
alias that provides interactivity, or use a file manager.
You have the following solution from https://www.mkyong.com/java/java-how-to-compare-two-sets/
public static boolean equals(Set<?> set1, Set<?> set2){
if(set1 == null || set2 ==null){
return false;
}
if(set1.size() != set2.size()){
return false;
}
return set1.containsAll(set2);
}
Or if you prefer to use a single return statement:
public static boolean equals(Set<?> set1, Set<?> set2){
return set1 != null
&& set2 != null
&& set1.size() == set2.size()
&& set1.containsAll(set2);
}
How about a NuGet Windows Identity Foundation. Just add it you you project and away you go! Its one of the MS owned NuGets so should be maintained accordingly.
EDIT: In Windows 8 Windows Identity Foundation is installed (enabled) by turning a windows feature on in Control Panel > All Control Panel Items > Programs and Features > Turn Windows feature on or off the feature is Windows Identity Foundation 3.5. Installers linked in the answer above will not work on Windows 8
Java Programmer's FAQ Part B Sect 6 suggests:
public static void bytefill(byte[] array, byte value) {
int len = array.length;
if (len > 0)
array[0] = value;
for (int i = 1; i < len; i += i)
System.arraycopy( array, 0, array, i,
((len - i) < i) ? (len - i) : i);
}
This essentially makes log2(array.length) calls to System.arraycopy which hopefully utilizes an optimized memcpy implementation.
However, is this technique still required on modern Java JITs such as the Oracle/Android JIT?
This will open a second cmd.exe window. If you want it to go away, replace the /K with /C.
Obviously, replace new_file_loc with whatever your new file location will be.
@echo off
for /F %%i in ('dir /B /O:-D *.txt') do (
call :open "%%i"
exit /B 0
)
:open
start "window title" "cmd /K copy %~1 new_file_loc"
exit /B 0
string zipfile = @"E:\Folderx\NPPES.zip";
string folder = @"E:\TargetFolderx";
ExtractFile(zipfile,folder);
public void ExtractFile(string source, string destination)
{
// If the directory doesn't exist, create it.
if (!Directory.Exists(destination))
Directory.CreateDirectory(destination);
//string zPath = ConfigurationManager.AppSettings["FileExtactorEXE"];
// string zPath = Properties.Settings.Default.FileExtactorEXE; ;
string zPath=@"C:\Program Files\7-Zip\7zG.exe";
try
{
ProcessStartInfo pro = new ProcessStartInfo();
pro.WindowStyle = ProcessWindowStyle.Hidden;
pro.FileName = zPath;
pro.Arguments = "x \"" + source + "\" -o" + destination;
Process x = Process.Start(pro);
x.WaitForExit();
}
catch (System.Exception Ex) { }
}
Just Install 7 zip from source and pass the parameter to the method.
Thanks. Please like the answer.
I disagree that .form-group should be within .col-*-n elements. In my experience, all the appropriate padding happens automatically when you use .form-group like .row within a form.
<div class="form-group">
<div class="col-sm-12">
<label for="user_login">Username</label>
<input class="form-control" id="user_login" name="user[login]" required="true" size="30" type="text" />
</div>
</div>
Check out this demo.
Altering the demo slightly by adding .form-horizontal to the form tag changes some of that padding.
<form action="#" method="post" class="form-horizontal">
Check out this demo.
When in doubt, inspect in Chrome or use Firebug in Firefox to figure out things like padding and margins. Using .row within the form fails in edsioufi's fiddle because .row uses negative left and right margins thereby drawing the horizontal bounds of the divs classed .row beyond the bounds of the containing fieldsets.
You can use np.where
to match the boolean conditions corresponding to Nan
values of the array and map
each outcome to generate a list of tuples
.
>>>list(map(tuple, np.where(np.isnan(x))))
[(1, 2), (2, 0)]
Another way is here
hash = {one: 1, two: 2}
hash.member?(:one)
#=> true
hash.member?(:five)
#=> false
First off, BigDecimal.multiply()
returns a BigDecimal
and you're trying to store that in an int
.
Second, it takes another BigDecimal
as the argument, not an int
.
If you just use the BigDecimal
for all variables involved in these calculations, it should work fine.
Here you go:
^[^<>]*$
This will test for string that has no <
and no >
If you want to test for a string that may have <
and >
, but must also have something other you should use just
[^<>] (or ^.*[^<>].*$)
Where [<>]
means any of <
or >
and [^<>]
means any that is not of <
or >
.
And of course the mandatory link.
I'd like to give a small addition to the existing answers. You get the same "Unclosed Character Literal error", if you give value to a char with incorrect unicode form. Like when you write:
char HI = '\3072';
You have to use the correct form which is:
char HI = '\u3072';
One of the reasons of your problem could be the password policy you are using.
And if there is no such policy of yours then check your settings for the password properties in the DEFAULT
profile with the following query:
SELECT resource_name, limit
FROM dba_profiles
WHERE profile = 'DEFAULT'
AND resource_type = 'PASSWORD';
And If required, you just need to change the PASSWORD_LIFE_TIME
to unlimited
with the following query:
ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED;
And this Link might be helpful for your problem.
Since Java 8, the best answer is to use Consumer<T>
:
https://docs.oracle.com/javase/8/docs/api/java/util/function/Consumer.html
It's one of the functional interfaces, which means you can call it as a lambda expression:
void doSomething(Consumer<String> something) {
something.accept("hello!");
}
...
doSomething( (something) -> System.out.println(something) )
...
I'm using Xcode 6 GM. I encountered the same issue. What I did was to go to Build Settings -> Build Options (you can search "compiler"), and then changed the option of the "Compiler for C/C++/Objective-C" to Default Compiler.
Alternatively you can grant the user DROP_ANY_TABLE
privilege if need be and the procedure will run as is without the need for any alteration. Dangerous maybe but depends what you're doing :)
I have found PercentEscaper class from google-http-java-client library, that can be used to implement encodeURIComponent quite easily.
PercentEscaper from google-http-java-client javadoc google-http-java-client home
You can use <<
to append to a string in-place.
s = "foo"
old_id = s.object_id
s << "bar"
s #=> "foobar"
s.object_id == old_id #=> true
Use:
dateTimePicker.Value.ToString("yyyy/MM/dd")
Refer to the following link:
http://www.vbdotnetforums.com/schedule-time/15001-datetimepicker-format.html
This works for mi fine on mac
kill -9 `ps -ef | awk '/nohup/{ print \$2 }'`
function bookmark(title, url) {
if (window.sidebar) {
// Firefox
window.sidebar.addPanel(title, url, '');
}
else if (window.opera && window.print)
{
// Opera
var elem = document.createElement('a');
elem.setAttribute('href', url);
elem.setAttribute('title', title);
elem.setAttribute('rel', 'sidebar');
elem.click(); //this.title=document.title;
}
else if (document.all)
{
// ie
window.external.AddFavorite(url, title);
}
}
I used this & works great in IE, FF, Netscape. Chrome, Opera and safari do not support it!
Change:
<!-- ANT4X -->
<dependency>
<groupId>net.sourceforge</groupId>
<artifactId>ant4x</artifactId>
<version>${net.sourceforge.ant4x-version}</version>
<scope>provided</scope>
</dependency>
To:
<!-- ANT4X -->
<dependency>
<groupId>net.sourceforge.ant4x</groupId>
<artifactId>ant4x</artifactId>
<version>${net.sourceforge.ant4x-version}</version>
<scope>provided</scope>
</dependency>
The groupId
of net.sourceforge
was incorrect. The correct value is net.sourceforge.ant4x
.
2008 Answer The "Official" Java API for this is now JAXB - Java API for XML Binding. See Tutorial by Oracle. The reference implementation lives at http://jaxb.java.net/
2018 Update Note that the Java EE and CORBA Modules are deprecated in SE in JDK9 and to be removed from SE in JDK11. Therefore, to use JAXB it will either need to be in your existing enterprise class environment bundled by your e.g. app server, or you will need to bring it in manually.
Check your code man....
In the main method you are trying to remove the 4th element which is not there and hence the error. In the remove() method you are trying to remove the 3rd element which is there and hence no error.
Something like this should work:
sh -c 'cd /tmp && exec pwd'
meshgrid helps in creating a rectangular grid from two 1-D arrays of all pairs of points from the two arrays.
x = np.array([0, 1, 2, 3, 4])
y = np.array([0, 1, 2, 3, 4])
Now, if you have defined a function f(x,y) and you wanna apply this function to all the possible combination of points from the arrays 'x' and 'y', then you can do this:
f(*np.meshgrid(x, y))
Say, if your function just produces the product of two elements, then this is how a cartesian product can be achieved, efficiently for large arrays.
Referred from here
Word of warning: if you put config files in your WEB-INF/classes
folder, and your IDE, say Eclipse, does a clean/rebuild, it will nuke your conf files unless they were in the Java source directory. BalusC's great answer alludes to that in option 1 but I wanted to add emphasis.
I learned the hard way that if you "copy" a web project in Eclipse, it does a clean/rebuild from any source folders. In my case I had added a "linked source dir" from our POJO java library, it would compile to the WEB-INF/classes
folder. Doing a clean/rebuild in that project (not the web app project) caused the same problem.
I thought about putting my confs in the POJO src folder, but these confs are all for 3rd party libs (like Quartz or URLRewrite) that are in the WEB-INF/lib
folder, so that didn't make sense. I plan to test putting it in the web projects "src" folder when i get around to it, but that folder is currently empty and having conf files in it seems inelegant.
So I vote for putting conf files in WEB-INF/commonConfFolder/filename.properties
, next to the classes folder, which is Balus option 2.
Also remember one thing. Very important
You have to specify the command something like this to be more precise
grep -l "pattern" *
Here is another direct-access implementation:
head="$(cat ".git/HEAD")"
while [ "$head" != "${head#ref: }" ]; do
head="$(cat ".git/${head#ref: }")"
done
This also works over http which is useful for local package archives (I know: for public web sites it's not recommended to make the .git directory accessable):
head="$(curl -s "$baseurl/.git/HEAD")"
while [ "$head" != "${head#ref: }" ]; do
head="$(curl -s "$baseurl/.git/${head#ref: }")"
done
In C++11 you can:
#include <tuple>
std::tuple<int, int> divide(int dividend, int divisor) {
return std::make_tuple(dividend / divisor, dividend % divisor);
}
#include <iostream>
int main() {
using namespace std;
int quotient, remainder;
tie(quotient, remainder) = divide(14, 3);
cout << quotient << ',' << remainder << endl;
}
In C++17:
#include <tuple>
std::tuple<int, int> divide(int dividend, int divisor) {
return {dividend / divisor, dividend % divisor};
}
#include <iostream>
int main() {
using namespace std;
auto [quotient, remainder] = divide(14, 3);
cout << quotient << ',' << remainder << endl;
}
or with structs:
auto divide(int dividend, int divisor) {
struct result {int quotient; int remainder;};
return result {dividend / divisor, dividend % divisor};
}
#include <iostream>
int main() {
using namespace std;
auto result = divide(14, 3);
cout << result.quotient << ',' << result.remainder << endl;
// or
auto [quotient, remainder] = divide(14, 3);
cout << quotient << ',' << remainder << endl;
}
If you are using ES6 with NPM, you can try node module "fetch-jsonp". Fetch API Provides support for making a JsonP call as a regular XHR call.
Prerequisite:
you should be using isomorphic-fetch
node module in your stack.
You can just do that too, it seems to work well too.
sc create "Servicename" binPath= "Path\To\your\App.exe" DisplayName= "My Custom Service"
You can open the registry and add a string named Description in your service's registry key to add a little more descriptive information about it. It will be shown in services.msc.
Using the minus
operator was working but also it was taking more time to execute which was not acceptable.
I have a similar kind of requirement for data migration and I used the NOT IN
operator for that.
The modified query is :
select *
from A
where (emp_id,emp_name) not in
(select emp_id,emp_name from B)
union all
select * from B
where (emp_id,emp_name) not in
(select emp_id,emp_name from A);
This query executed fast. Also you can add any number of columns in the select query. Only catch is that both tables should have the exact same table structure for this to be executed.
In Notepad++ v6.6 this setting is moved to the Backup tab of the Preferences menu.
The only difference i've noted is that things set in a relative layout via drag and drop automatically have their dimensions relative to other elements inferred, so when you run the app what you see is what you get. However in the constraint layout even if you drag and drop an element in the design view, when you run the app things may be shifted around. This can easily be fixed by manually setting the constraints or, a more risky move being to right click the element in the component tree, selecting the constraint layout sub menu, then clicking 'infer constraints'. Hope this helps
<?php
set_time_limit(0);
//This is the file where we save the information
$fp = fopen (dirname(__FILE__) . '/localfile.tmp', 'w+');
//Here is the file we are downloading, replace spaces with %20
$ch = curl_init(str_replace(" ","%20",$url));
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
// write curl response to file
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// get curl response
curl_exec($ch);
curl_close($ch);
fclose($fp);
?>
var currentDate = new Date(),
currentDay = currentDate.getDate() < 10
? '0' + currentDate.getDate()
: currentDate.getDate(),
currentMonth = currentDate.getMonth() < 9
? '0' + (currentDate.getMonth() + 1)
: (currentDate.getMonth() + 1);
document.getElementById("date").innerHTML = currentDay + '/' + currentMonth + '/' + currentDate.getFullYear();
You can read more about Date object
In addition to the above posts, i'd like to point out that "man ls" will give you a nice manual about the "ls" ( List " command.
Also, using ls -la myFile will list & show all the facts about that file.
I was tearing my hair out because for some items, the renamed item would get renamed again (repeatedly, unless max file name length was reached). This was happening both for Get-ChildItem and piping the output of dir. I guess that the renamed files got picked up because of a change in the alphabetical ordering. I solved this problem in the following way:
Get-ChildItem -Path . -OutVariable dirs
foreach ($i in $dirs) { Rename-Item $i.name ("<MY_PREFIX>"+$i.name) }
This "locks" the results returned by Get-ChildItem in the variable $dirs and you can iterate over it without fear that ordering will change or other funny business will happen.
Dave.Gugg's tip for using -Exclude should also solve this problem, but this is a different approach; perhaps if the files being renamed already contain the pattern used in the prefix.
(Disclaimer: I'm very much a PowerShell n00b.)
Try shFlags -- Advanced command-line flag library for Unix shell scripts.
http://code.google.com/p/shflags/
It is very good and very flexible.
FLAG TYPES: This is a list of the DEFINE_*'s that you can do. All flags take a name, default value, help-string, and optional 'short' name (one-letter name). Some flags have other arguments, which are described with the flag.
DEFINE_string: takes any input, and intreprets it as a string.
DEFINE_boolean: typically does not take any argument: say --myflag to set FLAGS_myflag to true, or --nomyflag to set FLAGS_myflag to false. Alternately, you can say --myflag=true or --myflag=t or --myflag=0 or --myflag=false or --myflag=f or --myflag=1 Passing an option has the same affect as passing the option once.
DEFINE_float: takes an input and intreprets it as a floating point number. As shell does not support floats per-se, the input is merely validated as being a valid floating point value.
DEFINE_integer: takes an input and intreprets it as an integer.
SPECIAL FLAGS: There are a few flags that have special meaning: --help (or -?) prints a list of all the flags in a human-readable fashion --flagfile=foo read flags from foo. (not implemented yet) -- as in getopt(), terminates flag-processing
EXAMPLE USAGE:
-- begin hello.sh --
! /bin/sh
. ./shflags
DEFINE_string name 'world' "somebody's name" n
FLAGS "$@" || exit $?
eval set -- "${FLAGS_ARGV}"
echo "Hello, ${FLAGS_name}."
-- end hello.sh --
$ ./hello.sh -n Kate
Hello, Kate.
Note: I took this text from shflags documentation
Looks like you're trying to execute a windows file (.exe) Surely you ought to be using powershell. Anyway on a Linux bash shell a simple one-liner will suffice.
[/home/$] for filename in /Data/*.txt; do for i in {0..3}; do ./MyProgam.exe Data/filenameLogs/$filename_log$i.txt; done done
Or in a bash
#!/bin/bash
for filename in /Data/*.txt;
do
for i in {0..3};
do ./MyProgam.exe Data/filename.txt Logs/$filename_log$i.txt;
done
done
Git doesn't think in terms of file versions. A version in git is a snapshot of the entire tree.
Given this, what you really want is a tree that has the latest content of most files, but with the contents of one file the same as it was 5 commits ago. This will take the form of a new commit on top of the old ones, and the latest version of the tree will have what you want.
I don't know if there's a one-liner that will revert a single file to the contents of 5 commits ago, but the lo-fi solution should work: checkout master~5
, copy the file somewhere else, checkout master
, copy the file back, then commit.
Looking into this, it seems like the LibMan approach works best for my needs with adding Bootstrap. I like it because it is now built into Visual Studio 2017(15.8 or later) and has its own dialog boxes.
Update 6/11/2020: bootstrap 4.1.3 is now added by default with VS-2019.5 (Thanks to Harald S. Hanssen for noticing.)
The default method VS adds to projects uses Bower but it looks like it is on the way out. In the header of Microsofts bower page they write:
Following a couple links lead to Use LibMan with ASP.NET Core in Visual Studio where it shows how libs can be added using a built-in Dialog:
In Solution Explorer, right-click the project folder in which the files should be added. Choose Add > Client-Side Library. The Add Client-Side Library dialog appears: [source: Scott Addie 2018]
Then for bootstrap just (1) select the unpkg, (2) type in "bootstrap@.." (3) Install. After this, you would just want to verify all the includes in the _Layout.cshtml or other places are correct. They should be something like href="~/lib/bootstrap/dist/js/bootstrap...")
Another solution, using Set
. May not be the ideal solution, but it works
Set<String> set = new HashSet<>(persons.size());
persons.stream().filter(p -> set.add(p.getName())).collect(Collectors.toList());
Or if you can modify the original list, you can use removeIf method
persons.removeIf(p -> !set.add(p.getName()));
The solution above not working for the latest version on PostgreSQL. I found this way to convert epoch time being stored in number and int column type is on PostgreSQL 13:
SELECT TIMESTAMP 'epoch' + (<table>.field::int) * INTERVAL '1 second' as started_on from <table>;
For more detail explanation, you can see here https://www.yodiw.com/convert-epoch-time-to-timestamp-in-postgresql/#more-214
Given that you're only converting to int
s to then perform a comparison, I'd just switch the table definition around to using varchar
also:
Create table #myTempTable
(
num varchar(12)
)
insert into #myTempTable (num) values (1),(2),(3),(4),(5)
and remove all of the attempted CONVERT
s from the rest of the query.
SELECT a.name, a.value AS value, COUNT(*) AS pocet
FROM
(SELECT item.name, value.value
FROM mdl_feedback AS feedback
INNER JOIN mdl_feedback_item AS item
ON feedback.id = item.feedback
INNER JOIN mdl_feedback_value AS value
ON item.id = value.item
WHERE item.typ = 'multichoicerated' AND item.feedback IN (43)
) AS a
INNER JOIN #myTempTable
on a.value = #myTempTable.num
GROUP BY a.name, a.value ORDER BY a.name
You are looking for the android:layout_weight
attribute. It will allow you to use percentages to define your layout.
In the following example, the left button uses 70% of the space, and the right button 30%.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:text="left"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".70" />
<Button
android:text="right"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".30" />
</LinearLayout>
It works the same with any kind of View, you can replace the buttons with some EditText to fit your needs.
Be sure to set the layout_width
to 0dp
or your views may not be scaled properly.
Note that the weight sum doesn't have to equal 1, I just find it easier to read like this. You can set the first weight to 7 and the second to 3 and it will give the same result.
In res/drawable
folder,
1. Create a new Drawable Resources
.
2. Input file name.
A new file will be created inside the res/drawable
folder.
Replace this code inside the newly created file and replace ic_action_back
with your drawable file name.
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/ic_action_back"
android:tint="@color/color_primary_text" />
Now, you can use it with Resource ID, R.id.filename
.
It should be just DateTime.ToString( "MMMM" )
You don't need all the extra M
s.
Unfortunately, the MinGW-w64 installer you used sometimes has this issue. I myself am not sure about why this happens (I think it has something to do with Sourceforge URL redirection or whatever that the installer currently can't handle properly enough).
Anyways, if you're already planning on using MSYS2, there's no need for that installer.
Download MSYS2 from this page (choose 32 or 64-bit according to what version of Windows you are going to use it on, not what kind of executables you want to build, both versions can build both 32 and 64-bit binaries).
After the install completes, click on the newly created "MSYS2 Shell" option under either MSYS2 64-bit
or MSYS2 32-bit
in the Start menu. Update MSYS2 according to the wiki (although I just do a pacman -Syu
, ignore all errors and close the window and open a new one, this is not recommended and you should do what the wiki page says).
Install a toolchain
a) for 32-bit:
pacman -S mingw-w64-i686-gcc
b) for 64-bit:
pacman -S mingw-w64-x86_64-gcc
install any libraries/tools you may need. You can search the repositories by doing
pacman -Ss name_of_something_i_want_to_install
e.g.
pacman -Ss gsl
and install using
pacman -S package_name_of_something_i_want_to_install
e.g.
pacman -S mingw-w64-x86_64-gsl
and from then on the GSL library is automatically found by your MinGW-w64 64-bit compiler!
Open a MinGW-w64 shell:
a) To build 32-bit things, open the "MinGW-w64 32-bit Shell"
b) To build 64-bit things, open the "MinGW-w64 64-bit Shell"
Verify that the compiler is working by doing
gcc -v
If you want to use the toolchains (with installed libraries) outside of the MSYS2 environment, all you need to do is add <MSYS2 root>/mingw32/bin
or <MSYS2 root>/mingw64/bin
to your PATH
.
Mac Users, let me save you the time:
The simplest is to do a PivotChart. Select your array of dates (with a header) and create a new Pivot Chart (Insert / PivotChart / Ok) Then on the field list window, drag and drop the date column in the Axis list first and then in the value list first.
Step 1:
Step 2:
HTML:
<a href="#" class="yourlink">Click Here</a>
JS:
$('a.yourlink').click(function(e) {
e.preventDefault();
window.open('http://yoururl1.com');
window.open('http://yoururl2.com');
});
window.open
also can take additional parameters. See them here: http://www.javascript-coder.com/window-popup/javascript-window-open.phtml
You should also know that window.open is sometimes blocked by popup blockers and/or ad-filters.
Addition from Paul below: This approach also places a dependency on JavaScript being enabled. Not typically a good idea, but sometimes necessary.
Here is an answer for your question:
Move your code to below method because navigation bar title updated after view loaded. I tried adding above code in viewDidLoad doesn't work, it works fine in viewDidAppear method.
-(void)viewDidAppear:(BOOL)animated{}
By default wordpress uses MD5. You can upgrade it to blowfish or extended DES.
http://frameworkgeek.com/support/what-hash-does-wordpress-use/
FYI, in case you need to add attributes to your dictionary (things that are attached to the dictionary, but are not one of the keys), then you'll need the second form. In that case, you can initialize your dictionary with keys having arbitrary characters, one at a time, like so:
class mydict(dict): pass
a = mydict()
a["b=c"] = 'value'
a.test = False
Within the range 0 = c < 128, yes the '
is the only difference for CPython 2.6.
>>> set(unichr(c).encode('unicode_escape') for c in range(128)) - set(chr(c).encode('string_escape') for c in range(128))
set(["'"])
Outside of this range the two types are not exchangeable.
>>> '\x80'.encode('string_escape')
'\\x80'
>>> '\x80'.encode('unicode_escape')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can’t decode byte 0x80 in position 0: ordinal not in range(128)
>>> u'1'.encode('unicode_escape')
'1'
>>> u'1'.encode('string_escape')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: escape_encode() argument 1 must be str, not unicode
On Python 3.x, the string_escape
encoding no longer exists, since str
can only store Unicode.
Everything looks fine at first blush, but some poking around on here found an answer that could be helpful: https://stackoverflow.com/a/16905808/7944
Even the original answer writer doesn't sound super confident, but it's worth following up on. Also, you didn't say anything about your directory structure and so I'm assuming it's boring default stuff, but can't know for sure.
PrincipalContext for browsing the AD is ridiculously slow (only use it for .ValidateCredentials, see below), use DirectoryEntry instead and .PropertiesToLoad() so you only pay for what you need.
Filters and syntax here: https://social.technet.microsoft.com/wiki/contents/articles/5392.active-directory-ldap-syntax-filters.aspx
Attributes here: https://docs.microsoft.com/en-us/windows/win32/adschema/attributes-all
using (var root = new DirectoryEntry($"LDAP://{Domain}"))
{
using (var searcher = new DirectorySearcher(root))
{
// looking for a specific user
searcher.Filter = $"(&(objectCategory=person)(objectClass=user)(sAMAccountName={username}))";
// I only care about what groups the user is a memberOf
searcher.PropertiesToLoad.Add("memberOf");
// FYI, non-null results means the user was found
var results = searcher.FindOne();
var properties = results?.Properties;
if (properties?.Contains("memberOf") == true)
{
// ... iterate over all the groups the user is a member of
}
}
}
Clean, simple, fast. No magic, no half-documented calls to .RefreshCache to grab the tokenGroups or to .Bind or .NativeObject in a try/catch to validate credentials.
For authenticating the user:
using (var context = new PrincipalContext(ContextType.Domain))
{
return context.ValidateCredentials(username, password);
}
From MSDN:
Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This is the code to use if you are have called Application.Run (WinForms applications), this method stops all running message loops on all threads and closes all windows of the application.
Terminates this process and gives the underlying operating system the specified exit code. This is the code to call when you are using console application.
This article, Application.Exit vs. Environment.Exit, points towards a good tip:
You can determine if System.Windows.Forms.Application.Run
has been called by checking the System.Windows.Forms.Application.MessageLoop
property. If true, then Run has been called and you can assume that a WinForms application is executing as follows.
if (System.Windows.Forms.Application.MessageLoop)
{
// WinForms app
System.Windows.Forms.Application.Exit();
}
else
{
// Console app
System.Environment.Exit(1);
}
Reference: Why would Application.Exit fail to work?
You can say that pass means NOP (No Operation) operation. You will get a clear picture after this example :-
C Program
#include<stdio.h>
void main()
{
int age = 12;
if( age < 18 )
{
printf("You are not adult, so you can't do that task ");
}
else if( age >= 18 && age < 60)
{
// I will add more code later inside it
}
else
{
printf("You are too old to do anything , sorry ");
}
}
Now how you will write that in Python :-
age = 12
if age < 18:
print "You are not adult, so you can't do that task"
elif age >= 18 and age < 60:
else:
print "You are too old to do anything , sorry "
But your code will give error because it required an indented block after elif . Here is the role of pass keyword.
age = 12
if age < 18:
print "You are not adult, so you can't do that task"
elif age >= 18 and age < 60:
pass
else:
print "You are too old to do anything , sorry "
Now I think its clear to you.
One issue with Bryan Rieger's useful answer is that on high-density displays, Apple devices report screen.width in dips, while Android devices report it in physical pixels. (See http://www.quirksmode.org/blog/archives/2012/07/more_about_devi.html .) I suggest using if (window.matchMedia('(max-device-width: 960px)').matches) {}
on browsers supporting matchMedia.
input -webkit-appearance: none;
alone does not work.
Try adding -webkit-border-radius:0px;
in addition.
Solution that worked for me:
This error popped up several times on several different projects.
What I finally figured out is that when I would build, there was already a copy of the system.web.mvc binary assembly in my bin folder.
To fix this, right-click on the assembly in the list of references and select "properties". Check to see if this is the latest version by looking at the "Version" property. If it is, switch "Copy Local" to true.
This will make sure that the version referenced in your project is the version that will end up in your binaries folder.
If you still get the error, try running nuGet to get the latest version, then try the aforementioned again.
Good luck - this error is a pain!
I was looking for an answer to this myself. S3 appears to only support redirects, you can't just rewrite the URL and silently return a different resource. I'm considering using my build script to simply make copies of my index.html in all of the required path locations. Maybe that will work for you too.
I did the same thing that @Diode, the first answer, but i made the condition with a range of dates, i hope this example going to be useful for someone
e.g (the same code to example with array of dates)
var dateFrom = "02/06/2013";_x000D_
var dateTo = "02/09/2013";_x000D_
_x000D_
var d1 = dateFrom.split("/");_x000D_
var d2 = dateTo.split("/");_x000D_
_x000D_
var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]); // -1 because months are from 0 to 11_x000D_
var to = new Date(d2[2], parseInt(d2[1])-1, d2[0]); _x000D_
_x000D_
_x000D_
_x000D_
var dates= ["02/06/2013", "02/07/2013", "02/08/2013", "02/09/2013", "02/07/2013", "02/10/2013", "02/011/2013"];_x000D_
_x000D_
dates.forEach(element => {_x000D_
let parts = element.split("/");_x000D_
let date= new Date(parts[2], parseInt(parts[1]) - 1, parts[0]);_x000D_
if (date >= from && date < to) {_x000D_
console.log('dates in range', date);_x000D_
}_x000D_
})
_x000D_
Try this:
<button (click)="click()">Click me</button>
<input class="txt" type="password" [(ngModel)]="input_pw" [ngClass]="{'hidden': isHidden}" />
component.ts:
isHidden: boolean = false;
click(){
this.isHidden = !this.isHidden;
}
Just FYI, if you are using Java 11+, there is an exception to this rule: if you run your java file directly (without compilation). In this mode, there is no restriction on a single public class per file. However, the class with the main
method must be the first one in the file.
Based on @ionden's answer, the call to the delegate could be simplified using null propagation since C# 6.0.
Your code would simply be:
class MyClass {
public event EventHandler MyEvent;
public void Method() {
MyEvent?.Invoke(this, EventArgs.Empty);
}
}
Use it like this:
MyClass myObject = new MyClass();
myObject.MyEvent += new EventHandler(myObject_MyEvent);
myObject.Method();
ALTER function dbo.FN_ReturnNumberRows(@Start int, @End int) returns @Numbers table (Number int) as
begin
insert into @Numbers
select n = ROW_NUMBER() OVER (ORDER BY n)+@Start-1 from (
select top (@End-@Start+1) 1 as n from information_schema.columns as A
cross join information_schema.columns as B
cross join information_schema.columns as C
cross join information_schema.columns as D
cross join information_schema.columns as E) X
return
end
GO
select * from dbo.FN_ReturnNumberRows(10,9999)
You May use first split and rejoin it using white space. it will work sure.
String[] Larray = L.split("[\\n]+");
L = "";
for(int i = 0; i<Larray.lengh; i++){
L = L+" "+Larray[i];
}
To get the result with two decimals, you can do like this :
var discount = Math.round((100 - (price / listprice) * 100) * 100) / 100;
The value to be rounded is multiplied by 100 to keep the first two digits, then we divide by 100 to get the actual result.
import urllib, urllib2, cookielib
username = 'myuser'
password = 'mypassword'
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()
resp.read()
is the straight html of the page you want to open, and you can use opener
to view any page using your session cookie.
Am I doing something wrong here?
Yes, you are. One servlet container is already running on port 8080 and you are trying to run another one on port 8080 again.
Either restart the server (If there is button for that in STS) or stop and start it
You need to do 2 things :
1) Call setPreventCornerOverlap(false)
on your CardView.
2) Put rounded Imageview inside CardView
About rounding your imageview, I had the same problem so I made a library that you can set different radii on each corner. Finally I got the result what I wanted like below.
So, I've found a solution for what I'm looking for, which is:
print open('f2').read().decode('string-escape').decode("utf-8")
There are some unusual codecs that are useful here. This particular reading allows one to take UTF-8 representations from within Python, copy them into an ASCII file, and have them be read in to Unicode. Under the "string-escape" decode, the slashes won't be doubled.
This allows for the sort of round trip that I was imagining.