You can use built-in sorted
function.
print sorted(['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue'])
By using Collections.sort()
, we can sort a list.
public class EmployeeList {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<String> empNames= new ArrayList<String>();
empNames.add("sudheer");
empNames.add("kumar");
empNames.add("surendra");
empNames.add("kb");
if(!empNames.isEmpty()){
for(String emp:empNames){
System.out.println(emp);
}
Collections.sort(empNames);
System.out.println(empNames);
}
}
}
output:
sudheer
kumar
surendra
kb
[kb, kumar, sudheer, surendra]
The simple way to solve the problem is to use ComparisonChain from Guava http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ComparisonChain.html
private static Comparator<String> stringAlphabeticalComparator = new Comparator<String>() {
public int compare(String str1, String str2) {
return ComparisonChain.start().
compare(str1,str2, String.CASE_INSENSITIVE_ORDER).
compare(str1,str2).
result();
}
};
Collections.sort(list, stringAlphabeticalComparator);
The first comparator from the chain will sort strings according to the case insensitive order, and the second comparator will sort strings according to the case insensitive order. As excepted strings appear in the result according to the alphabetical order:
"AA","Aa","aa","Development","development"
I guess this will be much more good if it has some numeric in the string. Hope it will help.
PS:I'm not sure about performance or complicated string values but it worked good something like this:
lorem ipsum
lorem ipsum 1
lorem ipsum 2
lorem ipsum 3
...
lorem ipsum 20
lorem ipsum 21
public class SemiNumericComparer : IComparer<string>
{
public int Compare(string s1, string s2)
{
int s1r, s2r;
var s1n = IsNumeric(s1, out s1r);
var s2n = IsNumeric(s2, out s2r);
if (s1n && s2n) return s1r - s2r;
else if (s1n) return -1;
else if (s2n) return 1;
var num1 = Regex.Match(s1, @"\d+$");
var num2 = Regex.Match(s2, @"\d+$");
var onlyString1 = s1.Remove(num1.Index, num1.Length);
var onlyString2 = s2.Remove(num2.Index, num2.Length);
if (onlyString1 == onlyString2)
{
if (num1.Success && num2.Success) return Convert.ToInt32(num1.Value) - Convert.ToInt32(num2.Value);
else if (num1.Success) return 1;
else if (num2.Success) return -1;
}
return string.Compare(s1, s2, true);
}
public bool IsNumeric(string value, out int result)
{
return int.TryParse(value, out result);
}
}
public List<DealInfo> getDealInfos(List<String> dealIds) {
String queryStr = "SELECT NEW com.admin.entity.DealInfo(deal.url, deal.url, deal.url, deal.url, deal.price, deal.value) " + "FROM Deal AS deal where deal.id in :inclList";
TypedQuery<DealInfo> query = em.createQuery(queryStr, DealInfo.class);
query.setParameter("inclList", dealIds);
return query.getResultList();
}
Works for me with JPA 2, Jboss 7.0.2
You'll want something like this, taken from http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
function alertSize() {
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
window.alert( 'Width = ' + myWidth );
window.alert( 'Height = ' + myHeight );
}
So that's innerHeight
for modern browsers, documentElement.clientHeight
for IE, body.clientHeight
for deprecated/quirks.
return RedirectToAction("ActionName", "ControllerName");
One option is to type [command] + [shift] + [p] (or the equivalent) and then type 'indentation'. The top result should be 'Indendtation: Reindent Lines'. Press [enter] and it will format the document.
Another option is to install the Emmet plugin (http://emmet.io/), which will provide not only better formatting, but also a myriad of other incredible features. To get the output you're looking for using Sublime Text 3 with the Emmet plugin requires just the following:
p [tab][enter] Hello world!
When you type p [tab] Emmet expands it to:
<p></p>
Pressing [enter] then further expands it to:
<p>
</p>
With the cursor indented and on the line between the tags. Meaning that typing text results in:
<p>
Hello, world!
</p>
The conversion is simple:
std::string str; LPCSTR lpcstr = str.c_str();
For those who stumble upon this question, here's how to achieve this layout with a Grid
:
<Grid>
<TextBlock Text="Server:"/>
<TextBlock Text="http://127.0.0.1" HorizontalAlignment="Right"/>
</Grid>
creates
Server: http://127.0.0.1
128M == 134217728
, the number you are seeing.
The memory limit is working fine. When it says it tried to allocate 32 bytes, that the amount requested by the last operation before failing.
Are you building any huge arrays or reading large text files? If so, remember to free any memory you don't need anymore, or break the task down into smaller steps.
If you have few modal shown simultaneously you can specify target modal for in-modal button with attributes data-toggle
and data-target
:
<div class="modal fade in" id="sendMessageModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header text-center">
<h4 class="modal-title">Modal Title</h4>
<small>Modal Subtitle</small>
</div>
<div class="modal-body">
<p>Modal content text</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-left" data-toggle="modal" data-target="#sendMessageModal">Close</button>
<button type="button" class="btn btn-danger" data-toggle="modal" data-target="#sendMessageModal">Send</button>
</div>
</div>
</div>
</div>
Somewhere outside the modal code you can have another toggle button:
<a href="index.html#" class="btn btn-default btn-xs" data-toggle="modal" data-target="#sendMessageModal">Resend Message</a>
User can't click in-modal toggle button while these button hidden and it correct works with option "modal"
for attribute data-toggle
. This scheme works automagicaly!
Following the documentation of fopen
:
``a'' Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then cur- rent end of file, irrespective of any intervening fseek(3) or similar.
So if you pFile2=fopen("myfile2.txt", "a");
the stream is positioned at the end to append automatically. just do:
FILE *pFile;
FILE *pFile2;
char buffer[256];
pFile=fopen("myfile.txt", "r");
pFile2=fopen("myfile2.txt", "a");
if(pFile==NULL) {
perror("Error opening file.");
}
else {
while(fgets(buffer, sizeof(buffer), pFile)) {
fprintf(pFile2, "%s", buffer);
}
}
fclose(pFile);
fclose(pFile2);
Let's say we need to use the class Classname
that is contained in the jar file org.example.jar
And your source is in the file mysource.java
Like this:
import org.example.Classname;
public class mysource {
public static void main(String[] argv) {
......
}
}
First, as you see, in your code you have to import the classes. To do that you need import org.example.Classname;
Second, when you compile the source, you have to reference the jar file.
Please note the difference in using :
and ;
while compiling
If you are under a unix like operating system:
javac -cp '.:org.example.jar' mysource.java
If you are under windows:
javac -cp .;org.example.jar mysource.java
After this, you obtain the bytecode file mysource.class
Now you can run this :
If you are under a unix like operating system:
java -cp '.:org.example.jar' mysource
If you are under windows:
java -cp .;org.example.jar mysource
For multiple integer in a single line, map
might be better.
arr = map(int, raw_input().split())
If the number is already known, (like 2 integers), you can use
num1, num2 = map(int, raw_input().split())
For all those looking for programming parlance, here is how it works. Internal implementation of advanced hashtables has many intricacies and optimisations for storage allocation/deallocation and search, but top-level idea will be very much the same.
(void) addValue : (object) value
{
int bucket = calculate_bucket_from_val(value);
if (bucket)
{
//do nothing, just overwrite
}
else //create bucket
{
create_extra_space_for_bucket();
}
put_value_into_bucket(bucket,value);
}
(bool) exists : (object) value
{
int bucket = calculate_bucket_from_val(value);
return bucket;
}
where calculate_bucket_from_val()
is the hashing function where all the uniqueness magic must happen.
The rule of thumb is: For a given value to be inserted, bucket must be UNIQUE & DERIVABLE FROM THE VALUE that it is supposed to STORE.
Bucket is any space where the values are stored - for here I have kept it int as an array index, but it maybe a memory location as well.
Surprised a multiline re.sub has not been suggested (Oh, because you've already split your string... But why?):
>>> import re
>>> a = "Foo\n \nBar\nBaz\n\n Garply\n \n"
>>> print a
Foo
Bar
Baz
Garply
>>> print(re.sub(r'\n\s*\n','\n',a,re.MULTILINE))
Foo
Bar
Baz
Garply
>>>
print(link_addres.contents[0])
It will print the context of the anchor tags
example:
statement_title = statement.find('h2',class_='briefing-statement__title')
statement_title_text = statement_title.a.contents[0]
package Jclasspackage
public class Jclass {
public String uname ;
/**
* @return the uname
*/
public String getUname() {
return uname;
}
/**
* @param uname the uname to set
*/
public void setUname(String uname) {
this.uname = uname;
}
public Jclass() {
this.uname = null;
}
public static void main(String[] args) {
}
}
<%@ page language="java"
import="java.util.*,java.io.*"
pageEncoding="ISO-8859-1"%>
<jsp:directive.page import="Jclasspackage.Jclass.java" />
<% Jclass jc = new Jclass();
String username = (String)request.getAttribute("un")
jc.setUname(username);
%>
In this way you can access the username in the java file using "this.username" in the class
Basically, what you want is:
google.com -> google.com -> google
www.google.com -> google.com -> google
google.co.uk -> google.co.uk -> google
www.google.co.uk -> google.co.uk -> google
www.google.org -> google.org -> google
www.google.org.uk -> google.org.uk -> google
Optional:
www.google.com -> google.com -> www.google
images.google.com -> google.com -> images.google
mail.yahoo.co.uk -> yahoo.co.uk -> mail.yahoo
mail.yahoo.com -> yahoo.com -> mail.yahoo
www.mail.yahoo.com -> yahoo.com -> mail.yahoo
You don't need to construct an ever-changing regex as 99% of domains will be matched properly if you simply look at the 2nd last part of the name:
(co|com|gov|net|org)
If it is one of these, then you need to match 3 dots, else 2. Simple. Now, my regex wizardry is no match for that of some other SO'ers, so the best way I've found to achieve this is with some code, assuming you've already stripped off the path:
my @d=split /\./,$domain; # split the domain part into an array
$c=@d; # count how many parts
$dest=$d[$c-2].'.'.$d[$c-1]; # use the last 2 parts
if ($d[$c-2]=~m/(co|com|gov|net|org)/) { # is the second-last part one of these?
$dest=$d[$c-3].'.'.$dest; # if so, add a third part
};
print $dest; # show it
To just get the name, as per your question:
my @d=split /\./,$domain; # split the domain part into an array
$c=@d; # count how many parts
if ($d[$c-2]=~m/(co|com|gov|net|org)/) { # is the second-last part one of these?
$dest=$d[$c-3]; # if so, give the third last
$dest=$d[$c-4].'.'.$dest if ($c>3); # optional bit
} else {
$dest=$d[$c-2]; # else the second last
$dest=$d[$c-3].'.'.$dest if ($c>2); # optional bit
};
print $dest; # show it
I like this approach because it's maintenance-free. Unless you want to validate that it's actually a legitimate domain, but that's kind of pointless because you're most likely only using this to process log files and an invalid domain wouldn't find its way in there in the first place.
If you'd like to match "unofficial" subdomains such as bozo.za.net, or bozo.au.uk, bozo.msf.ru just add (za|au|msf) to the regex.
I'd love to see someone do all of this using just a regex, I'm sure it's possible.
var results = from p in persons
group p by p.PersonID into g
select new { PersonID = g.Key, Cars = g.Select(m => m.car) };
I'm not familiar with postgresql, but in SQL Server or Oracle, using a subquery would work like below (in Oracle, the SELECT 0
would be SELECT 0 FROM DUAL
)
SELECT SUM(sub.value)
FROM
(
SELECT SUM(columnA) as value FROM my_table
WHERE columnB = 1
UNION
SELECT 0 as value
) sub
Maybe this would work for postgresql too?
I did this task in javascript like below
function GetCenterFromDegrees(data){
// var data = [{lat:22.281610498720003,lng:70.77577162868579},{lat:22.28065743343672,lng:70.77624369747241},{lat:22.280860953131217,lng:70.77672113067706},{lat:22.281863655593973,lng:70.7762061465462}];
var num_coords = data.length;
var X = 0.0;
var Y = 0.0;
var Z = 0.0;
for(i=0; i<num_coords; i++){
var lat = data[i].lat * Math.PI / 180;
var lon = data[i].lng * Math.PI / 180;
var a = Math.cos(lat) * Math.cos(lon);
var b = Math.cos(lat) * Math.sin(lon);
var c = Math.sin(lat);
X += a;
Y += b;
Z += c;
}
X /= num_coords;
Y /= num_coords;
Z /= num_coords;
lon = Math.atan2(Y, X);
var hyp = Math.sqrt(X * X + Y * Y);
lat = Math.atan2(Z, hyp);
var finalLat = lat * 180 / Math.PI;
var finalLng = lon * 180 / Math.PI;
var finalArray = Array();
finalArray.push(finalLat);
finalArray.push(finalLng);
return finalArray;
}
You just need to use the callbacks, from the documentation: https://github.com/fronteed/iCheck#callbacks
$('input').on('ifChecked', function(event){
alert(event.type + ' callback');
});
I like to use -v
for verbose mode.
It'll give you the commit id, comments and all affected files.
svn log -v --limit 4
Example of output:
I added some migrations and deleted a test xml file ------------------------------------------------------------------------ r58687 | mr_x | 2012-04-02 15:31:31 +0200 (Mon, 02 Apr 2012) | 1 line Changed paths: A /trunk/java/App/src/database/support A /trunk/java/App/src/database/support/MIGRATE A /trunk/java/App/src/database/support/MIGRATE/remove_device.sql D /trunk/java/App/src/code/test.xml
As the name suggests, Layout weight specifies what amount or percentage of space a particular field or widget should occupy the screen space.
If we specify weight in horizontal orientation, then we must specify layout_width = 0px
.
Similarly, If we specify weight in vertical orientation, then we must specify layout_height = 0px
.
Like @Gabi Purcaru mentions above, the proper way to rename and move the file is to use move_uploaded_file()
. It performs some safety checks to prevent security vulnerabilities and other exploits. You'll need to sanitize the value of $_FILES['file']['name']
if you want to use it or an extension derived from it. Use pathinfo
($_FILES['file']['name'], PATHINFO_EXTENSION)
to safely get the extension.
After reading the other answers (First by @duncan-finney and then by @Marrs) I set out to find the change log that explains the idiomatic react-router 2.x way of solving this. The documentation on using location (which you need for queries) in components is actually contradicted by the actual code. So if you follow their advice, you get big angry warnings like this:
Warning: [react-router] `context.location` is deprecated, please use a route component's `props.location` instead.
It turns out that you cannot have a context property called location that uses the location type. But you can use a context property called loc that uses the location type. So the solution is a small modification on their source as follows:
const RouteComponent = React.createClass({
childContextTypes: {
loc: PropTypes.location
},
getChildContext() {
return { location: this.props.location }
}
});
const ChildComponent = React.createClass({
contextTypes: {
loc: PropTypes.location
},
render() {
console.log(this.context.loc);
return(<div>this.context.loc.query</div>);
}
});
You could also pass down only the parts of the location object you want in your children get the same benefit. It didn't change the warning to change to the object type. Hope that helps.
By default there are no constraints on the foreign key, foreign key can be null and duplicate.
while creating a table / altering the table, if you add any constrain of uniqueness or not null then only it will not allow the null/ duplicate values.
If you would like to insert multiple values lets say from multiple inputs that have different post values but the same table to insert into then simply use:
mysql_query("INSERT INTO `table` (a,b,c,d,e,f,g) VALUES
('$a','$b','$c','$d','$e','$f','$g'),
('$a','$b','$c','$d','$e','$f','$g'),
('$a','$b','$c','$d','$e','$f','$g')")
or die (mysql_error()); // Inserts 3 times in 3 different rows
FYI : How to download data in CSV from Kibana:
In Kibana--> 1. Go to 'Discover' in left side
Select Index Field (based on your dashboard data) (*** In case if you are not sure which index to select-->go to management tab-->Saved Objects-->Dashboard-->select dashboard name-->scroll down to JSON-->you will see the Index name )
left side you see all the variables available in the data-->click over the variable name that you want to have in csv-->click add-->this variable will be added on the right side of the columns avaliable
Top right section of the kibana-->there is the time filter-->click -->select the duration for which you want the csv
Top upper right -->Reporting-->save this time/variable selection with a new report-->click generate CSV
Go to 'Management' in left side--> 'Reporting'-->download your csv
Edit 18 Nov 2016
This code also work (for those who prefer another solution , without using ActiveX)
var isIE11 = !!window.MSInputMethodContext && !!document.documentMode;
// true on IE11
// false on Edge and other IEs/browsers.
Original Answer
In order to check Ie11 , you can use this : ( tested)
(or run this)
!(window.ActiveXObject) && "ActiveXObject" in window
I have all VMS of IE :
Notice : this wont work for IE11 :
as you can see here , it returns true :
So what can we do :
Apparently , they added the machine bit space :
ie11 :
"Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; rv:11.0) like Gecko"
ie12 :
"Mozilla/5.0 (Windows NT 6.3; Win64; x64; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; rv:11.0) like Gecko"
so we can do:
/x64|x32/ig.test(window.navigator.userAgent)
this will return true only for ie11.
You can do this in many way.
- Using
display: flex
#block_container {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
}
_x000D_
<div id="block_container">_x000D_
<div id="bloc1">Copyright © All Rights Reserved.</div>_x000D_
<div id="bloc2"><img src="..."></div>_x000D_
</div>
_x000D_
- Using
display: inline-block
#block_container {_x000D_
text-align: center;_x000D_
}_x000D_
#block_container > div {_x000D_
display: inline-block;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<div id="block_container">_x000D_
<div id="bloc1">Copyright © All Rights Reserved.</div>_x000D_
<div id="bloc2"><img src="..."></div>_x000D_
</div>
_x000D_
- using
table
<div>_x000D_
<table align="center">_x000D_
<tr>_x000D_
<td>_x000D_
<div id="bloc1">Copyright © All Rights Reserved.</div>_x000D_
</td>_x000D_
<td>_x000D_
<div id="bloc2"><img src="..."></div>_x000D_
</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>
_x000D_
Just an idea that first came to my mind (sorry if stupid). Three components of colors can be assumed 3D coordinates of points and then you could calculate distance between points.
F.E.
Point1 has R1 G1 B1
Point2 has R2 G2 B2
Distance between colors is
d=sqrt((r2-r1)^2+(g2-g1)^2+(b2-b1)^2)
Percentage is
p=d/sqrt((255)^2+(255)^2+(255)^2)
You could also use countplot
from seaborn
. This package builds on pandas
to create a high level plotting interface. It gives you good styling and correct axis labels for free.
import pandas as pd
import seaborn as sns
sns.set()
df = pd.DataFrame({'colour': ['red', 'blue', 'green', 'red', 'red', 'yellow', 'blue'],
'direction': ['up', 'up', 'down', 'left', 'right', 'down', 'down']})
sns.countplot(df['colour'], color='gray')
It also supports coloring the bars in the right color with a little trick
sns.countplot(df['colour'],
palette={color: color for color in df['colour'].unique()})
Put the command
yum install php-gd
and restart the server (httpd, nginx, etc)
service httpd restart
jQuery .height
will return you the height of the element. It doesn't need CSS definition as it determines the computed height.
You can use .height()
, .innerHeight()
or outerHeight()
based on what you need.
.height()
- returns the height of element excludes padding, border and margin.
.innerHeight()
- returns the height of element includes padding but excludes border and margin.
.outerHeight()
- returns the height of the div including border but excludes margin.
.outerHeight(true)
- returns the height of the div including margin.
Check below code snippet for live demo. :)
$(function() {_x000D_
var $heightTest = $('#heightTest');_x000D_
$heightTest.html('Div style set as "height: 180px; padding: 10px; margin: 10px; border: 2px solid blue;"')_x000D_
.append('<p>Height (.height() returns) : ' + $heightTest.height() + ' [Just Height]</p>')_x000D_
.append('<p>Inner Height (.innerHeight() returns): ' + $heightTest.innerHeight() + ' [Height + Padding (without border)]</p>')_x000D_
.append('<p>Outer Height (.outerHeight() returns): ' + $heightTest.outerHeight() + ' [Height + Padding + Border]</p>')_x000D_
.append('<p>Outer Height (.outerHeight(true) returns): ' + $heightTest.outerHeight(true) + ' [Height + Padding + Border + Margin]</p>')_x000D_
});
_x000D_
div { font-size: 0.9em; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="heightTest" style="height: 150px; padding: 10px; margin: 10px; border: 2px solid blue; overflow: hidden; ">_x000D_
</div>
_x000D_
Your arguments are incorrect, error doesn't return an object containing status and message, it passed them as separate parameters in the order described below.
Taken from the angular docs:
So you'd need to change your code to:
$http.get(dataUrl)
.success(function (data){
$scope.data.products = data;
})
.error(function (error, status){
$scope.data.error = { message: error, status: status};
console.log($scope.data.error.status);
});
Obviously, you don't have to create an object representing the error, you could just create separate scope properties but the same principle applies.
If you don't need a custom ThreadPool but you rather want to limit the number of concurrent tasks, you can use:
List<Path> paths = List.of("/path/file1.csv", "/path/file2.csv", "/path/file3.csv").stream().map(e -> Paths.get(e)).collect(toList());
List<List<Path>> partitions = Lists.partition(paths, 4); // Guava method
partitions.forEach(group -> group.parallelStream().forEach(csvFilePath -> {
// do your processing
}));
(Duplicate question asking for this is locked, so please bear me here)
The accepted answer works, but I don't like much the idea to paste secure tokens into the package.json
I have found it elsewhere, just run this one-time command as documented in the git-config manpage.
git config --global url."https://${GITHUB_TOKEN}@github.com/".insteadOf [email protected]:
GITHUB_TOKEN
may be setup as environmnet variable or pasted directly
and then I install private github repos like: npm install user/repo --save
works also in Heroku, just setup the above git config ...
command as heroku-prebuild
script in package.json
and setup GITHUB_TOKEN
as Heroku config variable.
This can be done from the command line. This will create a column for your image with a NOT NULL
property.
CREATE TABLE `test`.`pic` (
`idpic` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`caption` VARCHAR(45) NOT NULL,
`img` LONGBLOB NOT NULL,
PRIMARY KEY(`idpic`)
)
TYPE = InnoDB;
From here
Use time.mktime() to convert the time tuple (in localtime) into seconds since the Epoch, then use datetime.fromtimestamp() to get the datetime object.
from datetime import datetime
from time import mktime
dt = datetime.fromtimestamp(mktime(struct))
I know this is an old question but wanted to give an additional option.
The jQuery Globalize gives the ability to parse a culture specific format to a float.
https://github.com/jquery/globalize
Given a string "$13,042.00", and Globalize set to en-US:
Globalize.culture("en-US");
You can parse the float value out like so:
var result = Globalize.parseFloat(Globalize.format("$13,042.00", "c"));
This will give you:
13042.00
And allows you to work with other cultures.
If I find that the private method is huge or complex or important enough to require its own tests, I just put it in another class and make it public there (Method Object). Then I can easily test the previously private but now public method that now lives on its own class.
For simple dockerized projects, I could not really see any existing answer fit.
So I wrote a very barebones solution without the need of external libraries or triggers, which runs on its own. No external os-cron needed, should work in every environment.
It works by adding a middleware: middleware.py
import threading
def should_run(name, seconds_interval):
from application.models import CronJob
from django.utils.timezone import now
try:
c = CronJob.objects.get(name=name)
except CronJob.DoesNotExist:
CronJob(name=name, last_ran=now()).save()
return True
if (now() - c.last_ran).total_seconds() >= seconds_interval:
c.last_ran = now()
c.save()
return True
return False
class CronTask:
def __init__(self, name, seconds_interval, function):
self.name = name
self.seconds_interval = seconds_interval
self.function = function
def cron_worker(*_):
if not should_run("main", 60):
return
# customize this part:
from application.models import Event
tasks = [
CronTask("events", 60 * 30, Event.clean_stale_objects),
# ...
]
for task in tasks:
if should_run(task.name, task.seconds_interval):
task.function()
def cron_middleware(get_response):
def middleware(request):
response = get_response(request)
threading.Thread(target=cron_worker).start()
return response
return middleware
models/cron.py
:
from django.db import models
class CronJob(models.Model):
name = models.CharField(max_length=10, primary_key=True)
last_ran = models.DateTimeField()
settings.py
:
MIDDLEWARE = [
...
'application.middleware.cron_middleware',
...
]
Be aware that Total Server Memory is NOT how much memory SQL Server is currently using.
refer to this Microsoft article: http://msdn.microsoft.com/en-us/library/ms190924.aspx
How to do it without using cURL with straight-up PHP: http://netevil.org/blog/2006/nov/http-post-from-php-without-curl
Try putting it inside a form tag and closing the input tag:
<form>
<input type = "text" class = "txtPost" placeholder = "Post a question?" required />
<button class = "btnPost btnBlue">Post</button>
</form>
FYI
PyQt is now available on all platforms via conda!
Useconda install pyqt
to get these #Python bindings for the Qt framework. @ 1:02 PM - 1 May 2014
The easiest way to pass additional data is to add the data to the existing ViewData for the view as @Joel Martinez notes. However, if you don't want to pollute your ViewData, RenderPartial has a method that takes three arguments as well as the two-argument version you show. The third argument is a ViewDataDictionary. You can construct a separate ViewDataDictionary just for your partial containing just the extra data that you want to pass in.
You can also use numpy.subtract
It has the advantage over the difference operator, -
, that you do not have to transform the sequences (list or tuples) into a numpy arrays — you save the two commands:
array1 = np.array([1.1, 2.2, 3.3])
array2 = np.array([1, 2, 3])
Example: (Python 3.5)
import numpy as np
result = np.subtract([1.1, 2.2, 3.3], [1, 2, 3])
print ('the difference =', result)
which gives you
the difference = [ 0.1 0.2 0.3]
Remember, however, that if you try to subtract sequences (lists or tuples) with the -
operator you will get an error. In this case, you need the above commands to transform the sequences in numpy arrays
Wrong Code:
print([1.1, 2.2, 3.3] - [1, 2, 3])
it works for me Swift 3:
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
and in ViewDidLoad:
self.navigationController?.interactivePopGestureRecognizer?.delegate = self
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
The Sierpinski triangle and the Koch curve are special types of flame fractals. Flame fractals are a very generalized type of Iterated function system, since it uses non-linear functions.
An algorithm for IFS:es are as follows:
Start with a random point.
Repeat the following many times (a million at least, depending on final image size):
Apply one of N predefined transformations (matrix transformations or similar) to the point. An example would be that multiply each coordinate with 0.5.
Plot the new point on the screen.
If the point is outside the screen, choose randomly a new one inside the screen instead.
If you want nice colors, let the color depend on the last used transformation.
If you are already spending time in Visual Studio, then you can always use the Server Explorer to connect to any .Net compliant database server.
Provided you're using Professional or greater, you can create and edit tables and databases, run queries, etc.
Note that since git1.7.11 ([ANNOUNCE] Git 1.7.11.rc1 and release note, June 2012) mentions:
"
git push --recurse-submodules
" learned to optionally look into the histories of submodules bound to the superproject and push them out.
Probably done after this patch and the --on-demand
option:
recurse-submodules=<check|on-demand>::
Make sure all submodule commits used by the revisions to be pushed are available on a remote tracking branch.
- If
check
is used, it will be checked that all submodule commits that changed in the revisions to be pushed are available on a remote.
Otherwise the push will be aborted and exit with non-zero status.- If
on-demand
is used, all submodules that changed in the revisions to be pushed will be pushed.
If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status.
So you could push everything in one go with (from the parent repo) a:
git push --recurse-submodules=on-demand
This option only works for one level of nesting. Changes to the submodule inside of another submodule will not be pushed.
With git 2.7 (January 2016), a simple git push will be enough to push the parent repo... and all its submodules.
See commit d34141c, commit f5c7cd9 (03 Dec 2015), commit f5c7cd9 (03 Dec 2015), and commit b33a15b (17 Nov 2015) by Mike Crowe (mikecrowe
).
(Merged by Junio C Hamano -- gitster
-- in commit 5d35d72, 21 Dec 2015)
push
: addrecurseSubmodules
config optionThe
--recurse-submodules
command line parameter has existed for some time but it has no config file equivalent.Following the style of the corresponding parameter for
git fetch
, let's inventpush.recurseSubmodules
to provide a default for this parameter.
This also requires the addition of--recurse-submodules=no
to allow the configuration to be overridden on the command line when required.The most straightforward way to implement this appears to be to make
push
use code insubmodule-config
in a similar way tofetch
.
The git config
doc now include:
push.recurseSubmodules
:Make sure all submodule commits used by the revisions to be pushed are available on a remote-tracking branch.
- If the value is '
check
', then Git will verify that all submodule commits that changed in the revisions to be pushed are available on at least one remote of the submodule. If any commits are missing, the push will be aborted and exit with non-zero status.- If the value is '
on-demand
' then all submodules that changed in the revisions to be pushed will be pushed. If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status. -- If the value is '
no
' then default behavior of ignoring submodules when pushing is retained.You may override this configuration at time of push by specifying '
--recurse-submodules=check|on-demand|no
'.
So:
git config push.recurseSubmodules on-demand
git push
Git 2.12 (Q1 2017)
git push --dry-run --recurse-submodules=on-demand
will actually work.
See commit 0301c82, commit 1aa7365 (17 Nov 2016) by Brandon Williams (mbrandonw
).
(Merged by Junio C Hamano -- gitster
-- in commit 12cf113, 16 Dec 2016)
push run with --dry-run
doesn't actually (Git 2.11 Dec. 2016 and lower/before) perform a dry-run when push is configured to push submodules on-demand.
Instead all submodules which need to be pushed are actually pushed to their remotes while any updates for the superproject are performed as a dry-run.
This is a bug and not the intended behaviour of a dry-run.Teach
push
to respect the--dry-run
option when configured to recursively push submodules 'on-demand'.
This is done by passing the--dry-run
flag to the child process which performs a push for a submodules when performing a dry-run.
And still in Git 2.12, you now havea "--recurse-submodules=only
" option to push submodules out without pushing the top-level superproject.
See commit 225e8bf, commit 6c656c3, commit 14c01bd (19 Dec 2016) by Brandon Williams (mbrandonw
).
(Merged by Junio C Hamano -- gitster
-- in commit 792e22e, 31 Jan 2017)
As mentioned in the other answers, you don't need jQuery to do this; you can just use the standard properties.
However, it seems you don't seem to know the difference between window.location.replace(url)
and window.location = url
.
window.location.replace(url)
replaces the current location in the address bar by a new one. The page that was calling the function, won't be included in the browser history. Therefore, on the new location, clicking the back button in your browser would make you go back to the page you were viewing before you visited the document containing the redirecting JavaScript.window.location = url
redirects to the new location. On this new page, the back button in your browser would point to the original page containing the redirecting JavaScript.Of course, both have their use cases, but it seems to me like in this case you should stick with the latter.
P.S.: You probably forgot two slashes after http:
on line 2 of your JavaScript:
url = "http://abc.com/" + temp;
Forget Everything just check out this
double num = 2.22939393;
num = Convert.ToDouble(num.ToString("#0.000"));
I use this query in order to retrieve the server name of my Oracle database.
SELECT program FROM v$session WHERE program LIKE '%(PMON)%';
For Mars (Eclipse 4.5) and WTP 3.7 use this link. http://download.eclipse.org/webtools/repository/mars/
You can also use MDIParent-child form. Set the child form's parent as MDI Parent
Eg
child.MdiParent = parentForm;
child.Show();
In this case just 1 form will be shown and the child forms will come inside the parent. Hope this helps
Don't use exit(0);
That's bad practice at the best of times. Use Yii::$app->end();
So your code would look like
$this->redirect(['index'], 302);
Yii::$app->end();
That said though the actual problem was stopping POST requests, this is the wrong solution to that problem (although it does work). To stop POST requests you need to use access control.
public function behaviors()
{
return [
'access' => [
'class' => \yii\filters\AccessControl::className(),
'only' => ['create', 'update'],
'rules' => [
// deny all POST requests
[
'allow' => false,
'verbs' => ['POST']
],
// allow authenticated users
[
'allow' => true,
'roles' => ['@'],
],
// everything else is denied
],
],
];
}
You need to "seed" the generator. Check out this short video, it will clear things up.
Communicating between fragments is fairly complicated (I find the listeners concept a little challenging to implement).
It is common to use a 'Event Bus" to abstract these communications. This is a 3rd party library that takes care of this communication for you.
'Otto' is one that is used often to do this, and might be worth looking into: http://square.github.io/otto/
If you want the threads to stop when your program exits (as implied by your example), then make them daemon threads.
If you want your threads to die on command, then you have to do it by hand. There are various methods, but all involve doing a check in your thread's loop to see if it's time to exit (see Nix's example).
Google Apps Script will not open automatically web pages, but it could be used to display a message with links, buttons that the user could click on them to open the desired web pages or even to use the Window object and methods like addEventListener() to open URLs.
It's worth to note that UiApp is now deprecated. From Class UiApp - Google Apps Script - Google Developers
Deprecated. The UI service was deprecated on December 11, 2014. To create user interfaces, use the HTML service instead.
The example in the HTML Service linked page is pretty simple,
Code.gs
// Use this code for Google Docs, Forms, or new Sheets.
function onOpen() {
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.createMenu('Dialog')
.addItem('Open', 'openDialog')
.addToUi();
}
function openDialog() {
var html = HtmlService.createHtmlOutputFromFile('index')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.showModalDialog(html, 'Dialog title');
}
A customized version of index.html to show two hyperlinks
<a href='http://stackoverflow.com' target='_blank'>Stack Overflow</a>
<br/>
<a href='http://meta.stackoverflow.com/' target='_blank'>Meta Stack Overflow</a>
The method you're using to read the http body response returns a byte slice:
func ReadAll(r io.Reader) ([]byte, error)
You can convert []byte
to a string by using
body, err := ioutil.ReadAll(resp.Body)
bodyString := string(body)
There is no :unchecked pseudo class however if you use the :checked pseudo class and the sibling selector you can differentiate between both states. I believe all of the latest browsers support the :checked pseudo class, you can find more info from this resource: http://www.whatstyle.net/articles/18/pretty_form_controls_with_css
Your going to get better browser support with jquery... you can use a click function to detect when the click happens and if its checked or not, then you can add a class or remove a class as necessary...
This worked for me. Each month on X axis
str_month_list = ['January','February','March','April','May','June','July','August','September','October','November','December']
ax.set_xticks(range(0,12))
ax.set_xticklabels(str_month_list)
Why not combine Pablo's reply with a valueOf()?
public enum Choices
{
a1, a2, b1, b2;
public static boolean contains(String s) {
try {
Choices.valueOf(s);
return true;
} catch (Exception e) {
return false;
}
}
jQuery is a JavaScript library.
Read
wiki-jQuery, github, jQuery vs. javascript?
What is JQuery?
Before JQuery, developers would create their own small frameworks (the group of code) this would allow all the developers to work around all the bugs and give them more time to work on features, so the JavaScript frameworks were born. Then came the collaboration stage, groups of developers instead of writing their own code would give it away for free and creating JavaScript code sets that everyone could use. That is what JQuery is, a library of JavaScript code. The best way to explain JQuery and its mission is well stated on the front page of the JQuery website which says:
JQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.
As you can see all JQuery is JavaScript. There is more than one type of JavaScript set of code sets like MooTools it is just that JQuery is the most popular.
Which is the best JavaScript or JQuery is a contentious discussion, really the answer is neither is best. They both have their roles I have worked on online applications where JQuery was not the right tool and what the application needed was straight JavaScript development. But for most websites JQuery is all that is needed. What a web developer needs to do is make an informed decision on what tools are best for their client. Someone first coming into web development does need some exposure to both technologies just using JQuery all the time does not teach the nuances of JavaScript and how it affects the DOM. Using JavaScript all the time slows projects down and because of the JQuery library has ironed most of the issues that JavaScript will have between each web browser it makes the deployment safe as it is sure to work across all platforms.
JavaScript is a language. jQuery is a library built with JavaScript to help JavaScript programmers who are doing common web tasks.
See here.
In my case my Android project depends on another Java project compiled for Java 7. java.lang.VerifyError
disappeared after I changed Compiler Compliance Level of that Java project to 6.0
Later I found out that this is a Dalvik issue: https://groups.google.com/forum/?fromgroups#!topic/android-developers/sKsMTZ42pwE
You are lucky that you didn't complete the rebase, so you can still do git rebase --abort
. If you had completed the rebase (it rewrites history), things would have been much more complex. Consider tagging the tips of branches before doing potentially damaging operations (particularly history rewriting), that way you can rewind if something blows up.
if you want to add the data in the increment order inside your associative array you can do this:
$newdata = array (
'wpseo_title' => 'test',
'wpseo_desc' => 'test',
'wpseo_metakey' => 'test'
);
// for recipe
$md_array["recipe_type"][] = $newdata;
//for cuisine
$md_array["cuisine"][] = $newdata;
this will get added to the recipe or cuisine depending on what was the last index.
Array push is usually used in the array when you have sequential index: $arr[0] , $ar[1].. you cannot use it in associative array directly. But since your sub array is had this kind of index you can still use it like this
array_push($md_array["cuisine"],$newdata);
This is my android:layout_height=50% activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/alipay_login"
style="@style/loginType"
android:background="#27b" >
</LinearLayout>
<LinearLayout
android:id="@+id/taobao_login"
style="@style/loginType"
android:background="#ed6d00" >
</LinearLayout>
</LinearLayout>
style:
<style name="loginType">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">match_parent</item>
<item name="android:layout_weight">0.5</item>
<item name="android:orientation">vertical</item>
</style>
4 decimal places would give you the accuracy to store the world's smallest currency sub-units. You can take it down further if you need micropayment (nanopayment?!) accuracy.
I too prefer DECIMAL
to DBMS-specific money types, you're safer keeping that kind of logic in the application IMO. Another approach along the same lines is simply to use a [long] integer, with formatting into ¤unit.subunit for human readability (¤ = currency symbol) done at the application level.
HTTP/2 supports queries multiplexing, headers compression, priority and more intelligent packet streaming management. This results in reduced latency and accelerates content download on modern web pages.
clearfix
should contain the floating elements but in your html you have added clearfix
only after floating right that is your pull-right
so you should do like this:
<div class="clearfix">
<div id="sidebar">
<ul>
<li>A</li>
<li>A</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
<li>...</li>
<li>Z</li>
</ul>
</div>
<div id="main">
<div>
<div class="pull-right">
<a>RIGHT</a>
</div>
</div>
<div>MOVED BELOW Z</div>
</div>
Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden;
as you have done in your main.
Had the same problem on another server, but realized that locales are messed.
export LC_ALL="en_US.UTF-8"
fixed the problem
If you need the difference in days accounting up to the second:
SELECT TIMESTAMPDIFF(SECOND,'2010-09-21 21:40:36','2010-10-08 18:23:13')/86400 AS diff
It will return
diff
16.8629
You dont need to give column names manually in xaml. Just set AutoGenerateColumns property to true and your list will be automatically binded to DataGrid. refer code. XAML Code:
<Grid>
<DataGrid x:Name="MyDatagrid" AutoGenerateColumns="True" Height="447" HorizontalAlignment="Left" Margin="20,85,0,0" VerticalAlignment="Top" Width="799" ItemsSource="{Binding Path=ListTest, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" CanUserAddRows="False"> </Grid>
C#
Public Class Test
{
public string m_field1_Test{get;set;}
public string m_field2_Test { get; set; }
public Test()
{
m_field1_Test = "field1";
m_field2_Test = "field2";
}
public MainWindow()
{
listTest = new List<Test>();
for (int i = 0; i < 10; i++)
{
obj = new Test();
listTest.Add(obj);
}
this.MyDatagrid.ItemsSource = ListTest;
InitializeComponent();
}
A bad example:
import sun.audio.*; //import the sun.audio package
import java.io.*;
//** add this into your application code as appropriate
// Open an input stream to the audio file.
InputStream in = new FileInputStream(Filename);
// Create an AudioStream object from the input stream.
AudioStream as = new AudioStream(in);
// Use the static class member "player" from class AudioPlayer to play
// clip.
AudioPlayer.player.start(as);
// Similarly, to stop the audio.
AudioPlayer.player.stop(as);
On SQL Server 2008 R2, I had a mismatch in table columns that caused the Rollback error. It went away when I fixed my sqlcmd table variable populated by the insert-exec statement to match that returned by the stored proc. It was missing org_code. In a windows cmd file, it loads result of stored procedure and selects it.
set SQLTXT= declare @resets as table (org_id nvarchar(9), org_code char(4), ^
tin(char9), old_strt_dt char(10), strt_dt char(10)); ^
insert @resets exec rsp_reset; ^
select * from @resets;
sqlcmd -U user -P pass -d database -S server -Q "%SQLTXT%" -o "OrgReport.txt"
I recommend you to generate an open format XML Excel file, is much more flexible than CSV.
Read Generating an Excel file in ASP.NET for more info
I kept getting results in seconds, so this worked for me:
(Time.now - self.created_at) / 86400
So i tried the above :javascript which works :) However HAML wraps the generated code in CDATA like so:
<script type="text/javascript">
//<![CDATA[
$(document).ready( function() {
$('body').addClass( 'test' );
} );
//]]>
</script>
The following HAML will generate the typical tag for including (for example) typekit or google analytics code.
%script{:type=>"text/javascript"}
//your code goes here - dont forget the indent!
I had the same issue with my virtual device. The problem is due to the Oreo image of the virtual devices that have the Play Store integrated. To solve this problem I installed a new device without the Play Store integrated and all it was fine.
Hope it helps, Bye
data, _ := ioutil.ReadAll(response.Body)
fmt.Println(string(data))
Take a look here: http://longgoldenears.blogspot.com/2007/09/triple-equals-in-javascript.html
The 3 equal signs mean "equality without type coercion". Using the triple equals, the values must be equal in type as well.
0 == false // true
0 === false // false, because they are of a different type
1 == "1" // true, automatic type conversion for value only
1 === "1" // false, because they are of a different type
null == undefined // true
null === undefined // false
'0' == false // true
'0' === false // false
I was getting the same "cannot find symbol" error when I did Build -> Make Project
. I fixed this by deleting my Maven /target
folder, right clicking my project module and doing Maven -> Reimport
, and doing Build -> Rebuild Project
. This was on IntelliJ Idea 13.1.5.
It turns out the Maven -> Reimport
was key, since the problem resurfaced a few times before I finally did that.
Here's a simple one, single for loop:
#define FOREACH(type, array, size) do { \
type it = array[0]; \
for(int i = 0; i < size; i++, it = array[i])
#define ENDFOR } while(0);
int array[] = { 1, 2, 3, 4, 5 };
FOREACH(int, array, 5)
{
printf("element: %d. index: %d\n", it, i);
}
ENDFOR
Gives you access to the index should you want it (i
) and the current item we're iterating over (it
). Note you might have naming issues when nesting loops, you can make the item and index names be parameters to the macro.
Edit: Here's a modified version of the accepted answer foreach
. Lets you specify the start
index, the size
so that it works on decayed arrays (pointers), no need for int*
and changed count != size
to i < size
just in case the user accidentally modifies 'i' to be bigger than size
and get stuck in an infinite loop.
#define FOREACH(item, array, start, size)\
for(int i = start, keep = 1;\
keep && i < size;\
keep = !keep, i++)\
for (item = array[i]; keep; keep = !keep)
int array[] = { 1, 2, 3, 4, 5 };
FOREACH(int x, array, 2, 5)
printf("index: %d. element: %d\n", i, x);
Output:
index: 2. element: 3
index: 3. element: 4
index: 4. element: 5
Here is a good table for printf
specifiers. So it should be %hu
for unsigned short int
.
And link to Wikipedia "C data types" too.
The solution was to give the "Network Service" account read permission on the EventLog/Security key.
Another option would be to set a flag variable as a Boolean
and then change that value based on your criteria.
Dim count as Integer
Dim flag as Boolean
flag = True
While flag
count = count + 1
If count = 10 Then
'Set the flag to false '
flag = false
End If
Wend
The app is stored in %LocalAppData%
in your %UserProfile%
. So the full path could be:
C:\Users\username\AppData\Local\GitHub
Use this approach to get your desired look.
button_selector.xml :
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<layer-list>
<item android:right="5dp" android:top="5dp">
<shape>
<corners android:radius="3dp" />
<solid android:color="#D6D6D6" />
</shape>
</item>
<item android:bottom="2dp" android:left="2dp">
<shape>
<gradient android:angle="270"
android:endColor="#E2E2E2" android:startColor="#BABABA" />
<stroke android:width="1dp" android:color="#BABABA" />
<corners android:radius="4dp" />
<padding android:bottom="10dp" android:left="10dp"
android:right="10dp" android:top="10dp" />
</shape>
</item>
</layer-list>
</item>
</selector>
And in your xml layout:
<Button
android:background="@drawable/button_selector"
...
..
/>
That's correct. You can find more about it in the Oracle guide on varargs.
Here's an example:
void foo(String... args) {
for (String arg : args) {
System.out.println(arg);
}
}
which can be called as
foo("foo"); // Single arg.
foo("foo", "bar"); // Multiple args.
foo("foo", "bar", "lol"); // Don't matter how many!
foo(new String[] { "foo", "bar" }); // Arrays are also accepted.
foo(); // And even no args.
This question was asked a long ago, while the RFC 2616 was still hanging around. Some answers to this question are based in such document, which is no longer relevant nowadays. Quoting Mark Nottingham who, at the time of writing, co-chairs the IETF HTTP and QUIC Working Groups:
Don’t use RFC2616. Delete it from your hard drives, bookmarks, and burn (or responsibly recycle) any copies that are printed out.
The old RFC 2616 has been supplanted by the following documents that, together, define the HTTP/1.1 protocol:
So I aim to provide an answer based in the RFC 7231 which is the current reference for HTTP/1.1 status codes.
302
status codeA response with 302
is a common way of performing URL redirection. Along with the 302
status code, the response should include a Location
header with a different URI. Such header will be parsed by the user agent and then perform the redirection:
Web browsers may change from POST
to GET
in the subsequent request. If this behavior is undesired, the 307
(Temporary Redirect) status code can be used instead.
This is how the 302
status code is defined in the RFC 7231:
The
302
(Found) status code indicates that the target resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client ought to continue to use the effective request URI for future requests.The server SHOULD generate a
Location
header field in the response containing a URI reference for the different URI. The user agent MAY use theLocation
field value for automatic redirection. The server's response payload usually contains a short hypertext note with a hyperlink to the different URI(s).Note: For historical reasons, a user agent MAY change the request method from
POST
toGET
for the subsequent request. If this behavior is undesired, the307
(Temporary Redirect) status code can be used instead.
According to MDN web docs from Mozilla, a typical use case for 302
is:
The Web page is temporarily not available for reasons that have not been unforeseen. That way, search engines don't update their links.
The RFC 7231 defines the following status codes for redirection:
The RFC 7238 was created to define another status code for redirection:
308
(Permanent Redirect)Refer to this answer for further details.
You need to use ajax.
http://api.jquery.com/jQuery.ajax/
<code>
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});
</code>
Quoting the iPhone OS Technology Overview:
iPhone OS provides support for full-screen video playback through the Media Player framework (MediaPlayer.framework). This framework supports the playback of movie files with the .mov, .mp4, .m4v, and .3gp filename extensions and using the following compression standards:
- H.264 video, up to 1.5 Mbps, 640 by 480 pixels, 30 frames per second, Low-Complexity version of the H.264 Baseline Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
- H.264 video, up to 768 Kbps, 320 by 240 pixels, 30 frames per second, Baseline Profile up to Level 1.3 with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
- MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second, Simple Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
- Numerous audio formats, including the ones listed in “Audio Technologies”
For information about the classes of the Media Player framework, see Media Player Framework Reference.
This is another option
#!/usr/bin/env python
import numpy as np
import matplotlib
matplotlib.use('TKAgg') #use matplotlib backend TkAgg (optional)
import matplotlib.pyplot as plt
sample_rate = 200 # sampling frequency in Hz (atleast 2 times f)
t = np.linspace(0,5,sample_rate) #time axis
f = 100 #Signal frequency in Hz
sig = np.sin(2*np.pi*f*(t/sample_rate))
plt.plot(t,sig)
plt.xlabel("Time")
plt.ylabel("Amplitude")
plt.tight_layout()
plt.show()
aspirinemaga, just replace:
$this->db->set('time', 'NOW()', FALSE);
$this->db->insert('mytable', $data);
for it:
$this->db->set('time', 'NOW() + INTERVAL 1 DAY', FALSE);
$this->db->insert('mytable', $data);
https://stackoverflow.com/a/17201265/12021422 Answer by @rciovati works
I spent 30 minutes trying to figure out why the new property variables aren't accessible.
Pure CSS:
.app-tooltip {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.app-tooltip:before {_x000D_
content: attr(data-title);_x000D_
background-color: rgba(97, 97, 97, 0.9);_x000D_
color: #fff;_x000D_
font-size: 12px;_x000D_
padding: 10px;_x000D_
position: absolute;_x000D_
bottom: -50px;_x000D_
opacity: 0;_x000D_
transition: all 0.4s ease;_x000D_
font-weight: 500;_x000D_
z-index: 2;_x000D_
}_x000D_
_x000D_
.app-tooltip:after {_x000D_
content: '';_x000D_
position: absolute;_x000D_
opacity: 0;_x000D_
left: 5px;_x000D_
bottom: -16px;_x000D_
border-style: solid;_x000D_
border-width: 0 10px 10px 10px;_x000D_
border-color: transparent transparent rgba(97, 97, 97, 0.9) transparent;_x000D_
transition: all 0.4s ease;_x000D_
}_x000D_
_x000D_
.app-tooltip:hover:after,_x000D_
.app-tooltip:hover:before {_x000D_
opacity: 1;_x000D_
}
_x000D_
<div href="#" class="app-tooltip" data-title="Your message here"> Test here</div>
_x000D_
You can use a static lookup map to avoid the exception and return a null, then throw as you'd like:
public enum Mammal {
COW,
MOUSE,
OPOSSUM;
private static Map<String, Mammal> lookup =
Arrays.stream(values())
.collect(Collectors.toMap(Enum::name, Function.identity()));
public static Mammal getByName(String name) {
return lookup.get(name);
}
}
You can use PyInstaller to package Python programs as standalone executables. It works on Windows, Linux, and Mac.
PyInstaller Quickstart
Install PyInstaller from PyPI:
pip install pyinstaller
Go to your program’s directory and run:
pyinstaller yourprogram.py
This will generate the bundle in a subdirectory called
dist
.For a more detailed walkthrough, see the manual.
The following regex will accept YYYY-MM-DD (within the range 1600-2999 year) formatted dates taking into consideration leap years:
^((?:(?:1[6-9]|2[0-9])\d{2})(-)(?:(?:(?:0[13578]|1[02])(-)31)|((0[1,3-9]|1[0-2])(-)(29|30))))$|^(?:(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(-)02(-)29)$|^(?:(?:1[6-9]|2[0-9])\d{2})(-)(?:(?:0[1-9])|(?:1[0-2]))(-)(?:0[1-9]|1\d|2[0-8])$
Examples:
You can test it here.
Note: if you want to accept one digit as month or day you can use:
^((?:(?:1[6-9]|2[0-9])\d{2})(-)(?:(?:(?:0?[13578]|1[02])(-)31)|((0?[1,3-9]|1[0-2])(-)(29|30))))$|^(?:(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(-)0?2(-)29)$|^(?:(?:1[6-9]|2[0-9])\d{2})(-)(?:(?:0?[1-9])|(?:1[0-2]))(-)(?:0?[1-9]|1\d|2[0-8])$
I have created the above regex starting from this solution
There is a nice script available on http://www.reddyss.com/SQLDownloads.aspx
To be able to use it on any database you can create it like in: http://nickstips.wordpress.com/2010/10/18/sql-making-a-stored-procedure-available-to-all-databases/
Not sure if there is other way.
To use it then use something like this:
use name_of_database
EXEC spUtil_SearchText 'value_searched', 0, 0
There are several levels of managing persistent data, depending on your needs:
-v host-path:container-path
to persist container directory data to a host directory.--volumes-from
to mount that data into your application container.Mine were located here on Ubuntu 18.04 when I installed JavaFX using apt install openjfx
(as noted already by @jewelsea above)
/usr/share/java/openjfx/jre/lib/ext/jfxrt.jar
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/jfxrt.jar
Just break out where you need to.
<html>
(html code)
<?php
(php code)
?>
(html code)
</html>
Do not use shortened-form. <?
conflicts with XML and is disabled by default on most servers.
So what will happen if two threads attack a volatile primitive variable at same time?
Usually each one can increment the value. However sometime, both will update the value at the same time and instead of incrementing by 2 total, both thread increment by 1 and only 1 is added.
Does this mean that whosoever takes lock on it, that will be setting its value first.
There is no lock. That is what synchronized
is for.
And in if meantime, some other thread comes up and read old value while first thread was changing its value, then doesn't new thread will read its old value?
Yes,
What is the difference between Atomic and volatile keyword?
AtomicXxxx wraps a volatile so they are basically same, the difference is that it provides higher level operations such as CompareAndSwap which is used to implement increment.
AtomicXxxx also supports lazySet. This is like a volatile set, but doesn't stall the pipeline waiting for the write to complete. It can mean that if you read a value you just write you might see the old value, but you shouldn't be doing that anyway. The difference is that setting a volatile takes about 5 ns, bit lazySet takes about 0.5 ns.
Using jQuery (which you really could be using in this case, I think), you could do this like so:
$('.column').remove();
Otherwise, you're going to need to use the parent of each element to remove it:
element.parentNode.removeChild(element);
You can use checkout or co
$ svn co http://example.com/svn/app-name directory-name
Some short codes:-
There is a good, simple example of exactly this, here: http://www.queness.com/post/77/simple-jquery-modal-window-tutorial
I found some information here Javascript Detecting Page Refresh
function UnLoadWindow() {
return 'We strongly recommends NOT closing this window yet.'
}
window.onbeforeunload = UnLoadWindow;
Save the username and password hashes in array in a php file instead of db.
When you need to authenticate the user, compute hashes of his credentials and then compare them to hashes in array.
If you use safe hash function (see hash function and hash algos in PHP documentation), it should be pretty safe (you may consider using salted hash) and also add some protections to the form itself.
The standard way to see if a file exists is with the Test-Path
cmdlet.
Test-Path -path $filename
I suggest this and all the cells for the particular table are effected.
table.tbl_classname td, th {
padding: 5px 5px 5px 4px;
}
If your database supports arrays, you can also implement a lineage column or materialized path as an array of parent ids.
Specifically with Postgres you can then use the set operators to query the hierarchy, and get excellent performance with GIN indices. This makes finding parents, children, and depth pretty trivial in a single query. Updates are pretty manageable as well.
I have a full write up of using arrays for materialized paths if you're curious.
A very good question ... I was intrigued so I did a little digging; for those who are interested, here's where I went, and what I came up with.
Looking at the source code for jQuery 1.4.2 I saw this block between lines 2361 and 2392:
jQuery.each(["bind", "one"], function( i, name ) {
jQuery.fn[ name ] = function( type, data, fn ) {
// Handle object literals
if ( typeof type === "object" ) {
for ( var key in type ) {
this[ name ](key, data, type[key], fn);
}
return this;
}
if ( jQuery.isFunction( data ) ) {
fn = data;
data = undefined;
}
var handler = name === "one" ? jQuery.proxy( fn, function( event ) {
jQuery( this ).unbind( event, handler );
return fn.apply( this, arguments );
}) : fn;
if ( type === "unload" && name !== "one" ) {
this.one( type, data, fn );
} else {
for ( var i = 0, l = this.length; i < l; i++ ) {
jQuery.event.add( this[i], type, handler, data );
}
}
return this;
};
});
There is a lot of interesting stuff going on here, but the part we are interested in is between lines 2384 and 2388:
else {
for ( var i = 0, l = this.length; i < l; i++ ) {
jQuery.event.add( this[i], type, handler, data );
}
}
Every time we call bind()
or one()
we are actually making a call to jQuery.event.add()
... so let's take a look at that (lines 1557 to 1672, if you are interested)
add: function( elem, types, handler, data ) {
// ... snip ...
var handleObjIn, handleObj;
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
}
// ... snip ...
// Init the element's event structure
var elemData = jQuery.data( elem );
// ... snip ...
var events = elemData.events = elemData.events || {},
eventHandle = elemData.handle, eventHandle;
if ( !eventHandle ) {
elemData.handle = eventHandle = function() {
// Handle the second event of a trigger and when
// an event is called after a page has unloaded
return typeof jQuery !== "undefined" && !jQuery.event.triggered ?
jQuery.event.handle.apply( eventHandle.elem, arguments ) :
undefined;
};
}
// ... snip ...
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = types.split(" ");
var type, i = 0, namespaces;
while ( (type = types[ i++ ]) ) {
handleObj = handleObjIn ?
jQuery.extend({}, handleObjIn) :
{ handler: handler, data: data };
// Namespaced event handlers
^
|
// There is is! Even marked with a nice handy comment so you couldn't miss it
// (Unless of course you are not looking for it ... as I wasn't)
if ( type.indexOf(".") > -1 ) {
namespaces = type.split(".");
type = namespaces.shift();
handleObj.namespace = namespaces.slice(0).sort().join(".");
} else {
namespaces = [];
handleObj.namespace = "";
}
handleObj.type = type;
handleObj.guid = handler.guid;
// Get the current list of functions bound to this event
var handlers = events[ type ],
special = jQuery.event.special[ type ] || {};
// Init the event handler queue
if ( !handlers ) {
handlers = events[ type ] = [];
// ... snip ...
}
// ... snip ...
// Add the function to the element's handler list
handlers.push( handleObj );
// Keep track of which events have been used, for global triggering
jQuery.event.global[ type ] = true;
}
// ... snip ...
}
At this point I realized that understanding this was going to take more than 30 minutes ... so I searched Stackoverflow for
jquery get a list of all event handlers bound to an element
and found this answer for iterating over bound events:
//log them to the console (firebug, ie8)
console.dir( $('#someElementId').data('events') );
//or iterate them
jQuery.each($('#someElementId').data('events'), function(i, event){
jQuery.each(event, function(i, handler){
console.log( handler.toString() );
});
});
Testing that in Firefox I see that the events
object in the data
attribute of every element has a [some_event_name]
attribute (click
in our case) to which is attatched an array of handler
objects, each of which has a guid, a namespace, a type, and a handler. "So", I think, "we should theoretically be able to add objects built in the same manner to the [element].data.events.[some_event_name].push([our_handler_object);
... "
And then I go to finish writing up my findings ... and find a much better answer posted by RusselUresti ... which introduces me to something new that I didn't know about jQuery (even though I was staring it right in the face.)
Which is proof that Stackoverflow is the best question-and-answer site on the internet, at least in my humble opinion.
So I'm posting this for posterity's sake ... and marking it a community wiki, since RussellUresti already answered the question so well.
The above answer was helpful for me, but it might be useful (or best practice) to add the name on submit, as I wound up doing. Hopefully this will be helpful to someone. CodePen Sample
<form id="formAddName">
<fieldset>
<legend>Add Name </legend>
<label for="firstName">First Name</label>
<input type="text" id="firstName" name="firstName" />
<button>Add</button>
</fieldset>
</form>
<ol id="demo"></ol>
<script>
var list = document.getElementById('demo');
var entry = document.getElementById('formAddName');
entry.onsubmit = function(evt) {
evt.preventDefault();
var firstName = document.getElementById('firstName').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(firstName));
list.appendChild(entry);
}
</script>
<div>_x000D_
<div style="width: 20%; float: left;">_x000D_
<p>Some Contentsssssssssss</p>_x000D_
</div>_x000D_
<div style="float: left; width: 80%;">_x000D_
<textarea style="width: 100%; max-width: 100%;"></textarea>_x000D_
</div>_x000D_
<div style="clear: both;"></div>_x000D_
</div>_x000D_
_x000D_
_x000D_
select 1 from table
will return a column of 1's for every row in the table. You could use it with a where statement to check whether you have an entry for a given key, as in:
if exists(select 1 from table where some_column = 'some_value')
What your friend was probably saying is instead of making bulk selects with select * from table, you should specify the columns that you need precisely, for two reasons:
1) performance & you might retrieve more data than you actually need.
2) the query's user may rely on the order of columns. If your table gets updated, the client will receive columns in a different order than expected.
I'm using:
$($('form').prop('elements')).each(function(){
console.info(this)
});
It Seems ugly, but to me it is still the better way to get all the elements with jQuery
.
package workouts;
import java.util.Random;
/**
*
* @author Muthu
*/
public class RandomGenerator {
public static void main(String[] args) {
for(int i=0;i<5;i++){
rndFunc();
}
}
public static void rndFunc(){
int[]a= new int[]{1,2,3};
Random rnd= new Random();
System.out.println(a[rnd.nextInt(a.length)]);
}
}
T
and TRUE
are True, F
and FALSE
are False. T
and F
can be redefined, however, so you should only rely upon TRUE
and FALSE
. If you compare 0 to FALSE and 1 to TRUE, you will find that they are equal as well, so you might consider them to be True and False as well.
If you know your format is PDF, then I don't see how the HTML tag can be useful... It definitely does not seem to work for me. The other pure LaTeX solutions obviously work just fine. But the whole point of Markdown is not to do LaTeX but to allow for multiple format compilation I believe, including HTML.
Therefore, with this in mind, what works for me is a variation of Nicolas Hamilton's answer to Color Text Stackoverflow question:
#############
## CENTER TXT
ctrFmt = function(x){
if(out_type == 'latex' || out_type == 'beamer')
paste0("\\begin{center}\n", x, "\n\\end{center}")
else if(out_type == 'html')
paste0("<center>\n", x, "\n</center>")
else
x
}
I put this inside my initial setup chunk.
Then I use it very easily in my .rmd
file:
`r ctrFmt("Centered text in html and pdf!")`
You have to give a separate id to the label too.
<label for="foo" id="foo_label">text</label>
#foo_label {display: none;}
Or hide the whole row
<tr id="foo_row">/***/</tr>
#foo_row {display: none;}
Thanks to AddRange
:
Example:
public class Person
{
private string Name;
private string FirstName;
public Person(string name, string firstname) => (Name, FirstName) = (name, firstname);
}
To add multiple Person
to a List<>
:
List<Person> listofPersons = new List<Person>();
listofPersons.AddRange(new List<Person>
{
new Person("John1", "Doe" ),
new Person("John2", "Doe" ),
new Person("John3", "Doe" ),
});
i simply had to run spotlight search and execute the Docker application under /Applications folder which brew cask install
created. Once this was run it asked to complete installation. I was then able to run docker ps
please use it like this first thing give a class name to tag p like "myp"
then on use the following code
$(document).ready(function() {
$(".myp").click(function() {
$(this).children(":first").toggleClass("classname"); // this will access the span.
})
})
Well, the only way I can think of doing everything you want is pretty ugly. First perform an AJAX call to retrieve the Javascript file contents. When this completes you can check the status code to decide if this was successful or not. Then take the responseText from the xhr object and wrap it in a try/catch, dynamically create a script tag, and for IE you can set the text property of the script tag to the JS text, in all other browsers you should be able to append a text node with the contents to script tag. If there's any code that expects a script tag to actually contain the src location of the file, this won't work, but it should be fine for most situations.
Here's how I do it using a DataTable. This is a working piece of TEST code.
using (SqlConnection con = new SqlConnection(connStr))
{
con.Open();
// Create a table with some rows.
DataTable table = MakeTable();
// Get a reference to a single row in the table.
DataRow[] rowArray = table.Select();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(con))
{
bulkCopy.DestinationTableName = "dbo.CarlosBulkTestTable";
try
{
// Write the array of rows to the destination.
bulkCopy.WriteToServer(rowArray);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}//using
The question is a little obscure. I ll do my best to explain this. First you should understand how to use moment-timezone. According to this answer here TypeError: moment().tz is not a function, you have to import moment from moment-timezone instead of the default moment (ofcourse you will have to npm install moment-timezone first!). For the sake of clarity,
const moment=require('moment-timezone')//import from moment-timezone
Now in order to use the timezone feature, use moment.tz("date_string/moment()","time_zone") (visit https://momentjs.com/timezone/ for more details). This function will return a moment object with a particular time zone. For the sake of clarity,
var newYork= moment.tz("2014-06-01 12:00", "America/New_York");/*this code will consider NewYork as the timezone.*/
Now when you try to convert newYork (the moment object) with moment's toDate() (ISO 8601 format conversion) you will get the time of Greenwich,UK. For more details, go through this article https://www.nhc.noaa.gov/aboututc.shtml, about UTC. However if you just want your local time in this format (New York time, according to this example), just add the method .utc(true) ,with the arg true, to your moment object. For the sake of clarity,
newYork.toDate()//will give you the Greenwich ,UK, time.
newYork.utc(true).toDate()//will give you the local time. according to the moment.tz method arg we specified above, it is 12:00.you can ofcourse change this by using moment()
In short, moment.tz considers the time zone you specify and compares your local time with the time in Greenwich to give you a result. I hope this was useful.
Thymeleaf has an equivalent to <c:choose>
and <c:when>
: the th:switch
and th:case
attributes introduced in Thymeleaf 2.0.
They work as you'd expect, using *
for the default case:
<div th:switch="${user.role}">
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
<p th:case="*">User is some other thing</p>
</div>
See this for a quick explanation of syntax (or the Thymeleaf tutorials).
Disclaimer: As required by StackOverflow rules, I'm the author of Thymeleaf.
I know this post is really old, but I have to reply because although BalusC's answer is marked as correct, it's not completely correct.
You have to write the query adding "[]" to foo like this:
foo[]=val1&foo[]=val2&foo[]=val3
Is your link to another web page? If so, perhaps you could put the variable in the query string and set the session variable when the page being linked to is loaded.
So the link looks like this:
<a href="home.php?variable=value" name="home">home</a>
And the homge page would parse the query string and set the session variable.
Do keep in mind that the file.getContentType
could also output application/octet-stream instead of the required application/vnd.openxmlformats-officedocument.spreadsheetml.sheet when you try to upload the file that is already open.
I spent days writing my own custom tool to parallelize the copies required for this, but then I ran across documentation on how to get the AWS S3 CLI sync command to synchronize buckets with massive parallelization. The following commands will tell the AWS CLI to use 1,000 threads to execute jobs (each a small file or one part of a multipart copy) and look ahead 100,000 jobs:
aws configure set default.s3.max_concurrent_requests 1000
aws configure set default.s3.max_queue_size 100000
After running these, you can use the simple sync command as follows:
aws s3 sync s3://source-bucket/source-path s3://destination-bucket/destination-path
On an m4.xlarge machine (in AWS--4 cores, 16GB RAM), for my case (3-50GB files) the sync/copy speed went from about 9.5MiB/s to 700+MiB/s, a speed increase of 70x over the default configuration.
Update: Note that S3CMD has been updated over the years and these changes are now only effective when you're working with lots of small files. Also note that S3CMD on Windows (only on Windows) is seriously limited in overall throughput and can only achieve about 3Gbps per process no matter what instance size or settings you use. Other systems like S5CMD have the same problem. I've spoken to the S3 team about this and they're looking into it.
You shoudn't use app.use(express.bodyParser()). BodyParser is a union of json + urlencoded + mulitpart. You shoudn't use this because multipart will be removed in connect 3.0.
To resolve that, you can do this:
app.use(express.json());
app.use(express.urlencoded());
It´s very important know that app.use(app.router) should be used after the json and urlencoded, otherwise it does not work!
typedef int (*PointerToIntArray)[];
typedef int *ArrayOfIntPointers[];
Use the next query:
DECLARE
EmpIDVar INT;
BEGIN
EmpIDVar := 1234;
SELECT *
FROM Employees
WHERE EmployeeID = EmpIDVar;
END;
You can simply use adb install command to install/update APK silently. Sample code is below
public static void InstallAPK(String filename){
File file = new File(filename);
if(file.exists()){
try {
String command;
filename = StringUtil.insertEscape(filename);
command = "adb install -r " + filename;
Process proc = Runtime.getRuntime().exec(new String[] { "su", "-c", command });
proc.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
}
}
It usually happens when there is a problem with memory allocation.
It happened to me when my program was trying to allocate an array with negative size.
<span class="txt">Some Text</span>
.txt:hover {
text-decoration: underline;
}
I was in a situation where Linq binding was not available and had to expand lambda explicitly. It resulted in a simple function:
public static T KeyByValue<T, W>(this Dictionary<T, W> dict, W val)
{
T key = default;
foreach (KeyValuePair<T, W> pair in dict)
{
if (EqualityComparer<W>.Default.Equals(pair.Value, val))
{
key = pair.Key;
break;
}
}
return key;
}
Call it like follows:
public static void Main()
{
Dictionary<string, string> dict = new Dictionary<string, string>()
{
{"1", "one"},
{"2", "two"},
{"3", "three"}
};
string key = KeyByValue(dict, "two");
Console.WriteLine("Key: " + key);
}
Works on .NET 2.0 and in other limited environments.
VS2017 - Solved by closing all instances of MSBuild.exe in the windows task manager
First of all, the provided long code:
<xsl:choose>
<xsl:when test="OU_NAME='OU_ADDR1'"> --comparing two elements coming from XML
<!--remove if adrees already contain operating unit name <xsl:value-of select="OU_NAME"/> <fo:block/>-->
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="OU_NAME"/>
<fo:block/>
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
</xsl:otherwise>
</xsl:choose>
is equivalent to this, much shorter code:
<xsl:if test="not(OU_NAME='OU_ADDR1)'">
<xsl:value-of select="OU_NAME"/>
</xsl:if>
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
Now, to your question:
how to compare two elements coming from xml as string
In Xpath 1.0 strings can be compared only for equality (or inequality), using the operator =
and the function not()
together with the operator =
.
$str1 = $str2
evaluates to true()
exactly when the string $str1
is equal to the string $str2
.
not($str1 = $str2)
evaluates to true()
exactly when the string $str1
is not equal to the string $str2
.
There is also the !=
operator. It generally should be avoided because it has anomalous behavior whenever one of its operands is a node-set.
Now, the rules for comparing two element nodes are similar:
$el1 = $el2
evaluates to true()
exactly when the string value of $el1
is equal to the string value of $el2
.
not($el1 = $el2)
evaluates to true()
exactly when the string value of $el1
is not equal to the string value of $el2
.
However, if one of the operands of =
is a node-set, then
$ns = $str
evaluates to true()
exactly when there is at least one node in the node-set $ns1
, whose string value is equal to the string $str
$ns1 = $ns2
evaluates to true()
exactly when there is at least one node in the node-set $ns1
, whose string value is equal to the string value of some node from $ns2
Therefore, the expression:
OU_NAME='OU_ADDR1'
evaluates to true()
only when there is at least one element child of the current node that is named OU_NAME
and whose string value is the string 'OU_ADDR1'.
This is obviously not what you want!
Most probably you want:
OU_NAME=OU_ADDR1
This expression evaluates to true
exactly there is at least one OU_NAME
child of the current node and one OU_ADDR1
child of the current node with the same string value.
Finally, in XPath 2.0, strings can be compared also using the value comparison operators lt
, le
, eq
, gt
, ge
and the inherited from XPath 1.0 general comparison operator =
.
Trying to evaluate a value comparison operator when one or both of its arguments is a sequence of more than one item results in error.
Try this in your batch file:
@echo off
start /d "C:\Program Files\Internet Explorer" IEXPLORE.EXE www.google.com
start /d "C:\Program Files\Internet Explorer" IEXPLORE.EXE www.yahoo.com
Since Java 11 you can simply use String.repeat(count)
to solve your problem.
Returns a string whose value is the concatenation of this string repeated
count
times.If this string is empty or
count
is zero then the empty string is returned.
So instead of a loop your code would just look like this:
" ".repeat(length);
This is the easiest way i have found to do it.
List<List<String>> matrix= new List<List<String>>(); //Creates new nested List
matrix.Add(new List<String>()); //Adds new sub List
matrix[0].Add("2349"); //Add values to the sub List at index 0
matrix[0].Add("The Prime of Your Life");
matrix[0].Add("Daft Punk");
matrix[0].Add("Human After All");
matrix[0].Add("3");
matrix[0].Add("2");
To retrieve values is even easier
string title = matrix[0][1]; //Retrieve value at index 1 from sub List at index 0
Super easy answer for those that only have this on one webpage. Edit your actionlink and a + "/" on the end of it.
@Html.ActionLink("Edit", "Edit", new { id = item.name + "/" }) |
It can be done in css and it is very simple. change the "a" to a "p". Your "page link" does not lead to somewhere anyway if you want to make it unclickable.
When you tell your css to do a hover action on this specific "p" tell it this:
(for this example I have given the "p" the "example" ID)
#example
{
cursor:default;
}
Now your cursor will stay the same as it does all over the page.
You can add this script for showing your own message.
<script>
input = document.getElementById("topicName");
input.addEventListener('invalid', function (e) {
if(input.validity.valueMissing)
{
e.target.setCustomValidity("Please enter topic name");
}
//To Remove the sticky error message at end write
input.addEventListener('input', function (e) {
e.target.setCustomValidity('');
});
});
</script>
For other validation like pattern mismatch you can add addtional if else condition
like
else if (input.validity.patternMismatch)
{
e.target.setCustomValidity("Your Message");
}
there are other validity conditions like rangeOverflow,rangeUnderflow,stepMismatch,typeMismatch,valid
The following code just declares a string variable that contains a MySQL query:
$sql = "INSERT INTO users (username, password, email)
VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')";
It does not execute the query. In order to do that you need to use some functions but let me explain something else first.
NEVER TRUST USER INPUT: You should never append user input (such as form input from $_GET
or $_POST
) directly to your query. Someone can carefully manipulate the input in such a way so that it can cause great damage to your database. That's called SQL Injection. You can read more about it here
To protect your script from such an attack you must use Prepared Statements. More on prepared statements here
Include prepared statements to your code like this:
$sql = "INSERT INTO users (username, password, email)
VALUES (?,?,?)";
Notice how the ?
are used as placeholders for the values. Next you should prepare the statement using mysqli_prepare
:
$stmt = mysqli_prepare($sql);
Then start binding the input variables to the prepared statement:
$stmt->bind_param("sss", $_POST['username'], $_POST['email'], $_POST['password']);
And finally execute the prepared statements. (This is where the actual insertion takes place)
$stmt->execute();
NOTE Although not part of the question, I strongly advice you to never store passwords in clear text. Instead you should use password_hash
to store a hash of the password
The following will give you the size of the browsers viewport.
$(window).height(); // returns height of browser viewport
$(window).width(); // returns width of browser viewport
List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia)); //copy
In this case, list1
is of type ArrayList
.
List<Integer> list2 = Arrays.asList(ia);
Here, the list is returned as a List
view, meaning it has only the methods attached to that interface. Hence why some methods are not allowed on list2
.
ArrayList<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia));
Here, you ARE creating a new ArrayList
. You're simply passing it a value in the constructor. This is not an example of casting. In casting, it might look more like this:
ArrayList list1 = (ArrayList)Arrays.asList(ia);
This works if the value contains a space:
FOR /F "skip=2 tokens=1,2*" %%A IN ('REG QUERY "%KEY_NAME%" /v "%VALUE_NAME%" 2^>nul') DO (
set ValueName=%%A
set ValueType=%%B
set ValueValue=%%C
)
if defined ValueName (
echo Value Name = %ValueName%
echo Value Type = %ValueType%
echo Value Value = %ValueValue%
) else (
@echo "%KEY_NAME%"\"%VALUE_NAME%" not found.
)
This will avoid any collision and it will be fast until we use the shifting in calculations.
int k = key.length();
int sum = 0;
for(int i = 0 ; i < k-1 ; i++){
sum += key.charAt(i)<<(5*i);
}
If its working when you are using a browser and then passing on your username and password for the first time - then this means that once authentication is done Request header of your browser is set with required authentication values, which is then passed on each time a request is made to hosting server.
So start with inspecting Request Header (this could be done using Web Developers tools), Once you established whats required in header then you could pass this within your HttpWebRequest Header.
Example with Digest Authentication:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
namespace NUI
{
public class DigestAuthFixer
{
private static string _host;
private static string _user;
private static string _password;
private static string _realm;
private static string _nonce;
private static string _qop;
private static string _cnonce;
private static DateTime _cnonceDate;
private static int _nc;
public DigestAuthFixer(string host, string user, string password)
{
// TODO: Complete member initialization
_host = host;
_user = user;
_password = password;
}
private string CalculateMd5Hash(
string input)
{
var inputBytes = Encoding.ASCII.GetBytes(input);
var hash = MD5.Create().ComputeHash(inputBytes);
var sb = new StringBuilder();
foreach (var b in hash)
sb.Append(b.ToString("x2"));
return sb.ToString();
}
private string GrabHeaderVar(
string varName,
string header)
{
var regHeader = new Regex(string.Format(@"{0}=""([^""]*)""", varName));
var matchHeader = regHeader.Match(header);
if (matchHeader.Success)
return matchHeader.Groups[1].Value;
throw new ApplicationException(string.Format("Header {0} not found", varName));
}
private string GetDigestHeader(
string dir)
{
_nc = _nc + 1;
var ha1 = CalculateMd5Hash(string.Format("{0}:{1}:{2}", _user, _realm, _password));
var ha2 = CalculateMd5Hash(string.Format("{0}:{1}", "GET", dir));
var digestResponse =
CalculateMd5Hash(string.Format("{0}:{1}:{2:00000000}:{3}:{4}:{5}", ha1, _nonce, _nc, _cnonce, _qop, ha2));
return string.Format("Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", " +
"algorithm=MD5, response=\"{4}\", qop={5}, nc={6:00000000}, cnonce=\"{7}\"",
_user, _realm, _nonce, dir, digestResponse, _qop, _nc, _cnonce);
}
public string GrabResponse(
string dir)
{
var url = _host + dir;
var uri = new Uri(url);
var request = (HttpWebRequest)WebRequest.Create(uri);
// If we've got a recent Auth header, re-use it!
if (!string.IsNullOrEmpty(_cnonce) &&
DateTime.Now.Subtract(_cnonceDate).TotalHours < 1.0)
{
request.Headers.Add("Authorization", GetDigestHeader(dir));
}
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
// Try to fix a 401 exception by adding a Authorization header
if (ex.Response == null || ((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.Unauthorized)
throw;
var wwwAuthenticateHeader = ex.Response.Headers["WWW-Authenticate"];
_realm = GrabHeaderVar("realm", wwwAuthenticateHeader);
_nonce = GrabHeaderVar("nonce", wwwAuthenticateHeader);
_qop = GrabHeaderVar("qop", wwwAuthenticateHeader);
_nc = 0;
_cnonce = new Random().Next(123400, 9999999).ToString();
_cnonceDate = DateTime.Now;
var request2 = (HttpWebRequest)WebRequest.Create(uri);
request2.Headers.Add("Authorization", GetDigestHeader(dir));
response = (HttpWebResponse)request2.GetResponse();
}
var reader = new StreamReader(response.GetResponseStream());
return reader.ReadToEnd();
}
}
Then you could call it:
DigestAuthFixer digest = new DigestAuthFixer(domain, username, password);
string strReturn = digest.GrabResponse(dir);
if Url is: http://xyz.rss.com/folder/rss then domain: http://xyz.rss.com (domain part) dir: /folder/rss (rest of the url)
you could also return it as stream and use XmlDocument Load() method.
A slightly simplified version of Oglester's solution (the sequence doesn't require a select from DUAL:
INSERT INTO account_type_standard
(account_type_Standard_id, tax_status_id, recipient_id)
VALUES(
account_type_standard_seq.nextval,
(SELECT tax_status_id FROM tax_status WHERE tax_status_code = ?),
(SELECT recipient_id FROM recipient WHERE recipient_code = ?)
)
Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.
Let me explain using step-by-step guidance.
First, download the source code from https://github.com/rmtheis/tess-two.
Import all three projects. After importing you will get an error.
To solve the error you have to create a res
folder in the tess-two project
First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"
After doing this in all three project the error should be gone.
Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.
Now you just need to import it into your workspace, but first you have to download android-ndk from this site:
http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file
Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable
Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture
done it
Now open cmd and go to on D:\Android Workspace\tess-two like below
If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:
Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest
Import test-two in this and run OCRTest and run it; you will get the best example of OCR.
Finally found a solution with a docker-compose method. Since docker-compose file format 2.1 you can define healthchecks.
I did it in a example project you need to install at least docker 1.12.0+. I also needed to extend the rabbitmq-management Dockerfile, because curl isn't installed on the official image.
Now I test if the management page of the rabbitmq-container is available. If curl finishes with exitcode 0 the container app (python pika) will be started and publish a message to hello queue. Its now working (output).
docker-compose (version 2.1):
version: '2.1'
services:
app:
build: app/.
depends_on:
rabbit:
condition: service_healthy
links:
- rabbit
rabbit:
build: rabbitmq/.
ports:
- "15672:15672"
- "5672:5672"
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:15672"]
interval: 30s
timeout: 10s
retries: 5
output:
rabbit_1 | =INFO REPORT==== 25-Jan-2017::14:44:21 ===
rabbit_1 | closing AMQP connection <0.718.0> (172.18.0.3:36590 -> 172.18.0.2:5672)
app_1 | [x] Sent 'Hello World!'
healthcheckcompose_app_1 exited with code 0
Dockerfile (rabbitmq + curl):
FROM rabbitmq:3-management
RUN apt-get update
RUN apt-get install -y curl
EXPOSE 4369 5671 5672 25672 15671 15672
Version 3 no longer supports the condition form of depends_on. So i moved from depends_on to restart on-failure. Now my app container will restart 2-3 times until it is working, but it is still a docker-compose feature without overwriting the entrypoint.
docker-compose (version 3):
version: "3"
services:
rabbitmq: # login guest:guest
image: rabbitmq:management
ports:
- "4369:4369"
- "5671:5671"
- "5672:5672"
- "25672:25672"
- "15671:15671"
- "15672:15672"
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:15672"]
interval: 30s
timeout: 10s
retries: 5
app:
build: ./app/
environment:
- HOSTNAMERABBIT=rabbitmq
restart: on-failure
depends_on:
- rabbitmq
links:
- rabbitmq
Maybe this may help you as well. I was having some trouble getting my head wrapped around how socket.io worked, so I tried to boil an example down as much as I could.
I adapted this example from the example posted here: http://socket.io/get-started/chat/
First, start in an empty directory, and create a very simple file called package.json Place the following in it.
{
"dependencies": {}
}
Next, on the command line, use npm to install the dependencies we need for this example
$ npm install --save express socket.io
This may take a few minutes depending on the speed of your network connection / CPU / etc. To check that everything went as planned, you can look at the package.json file again.
$ cat package.json
{
"dependencies": {
"express": "~4.9.8",
"socket.io": "~1.1.0"
}
}
Create a file called server.js This will obviously be our server run by node. Place the following code into it:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
//send the index.html file for all requests
res.sendFile(__dirname + '/index.html');
});
http.listen(3001, function(){
console.log('listening on *:3001');
});
//for testing, we're just going to send data to the client every second
setInterval( function() {
/*
our message we want to send to the client: in this case it's just a random
number that we generate on the server
*/
var msg = Math.random();
io.emit('message', msg);
console.log (msg);
}, 1000);
Create the last file called index.html and place the following code into it.
<html>
<head></head>
<body>
<div id="message"></div>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.on('message', function(msg){
console.log(msg);
document.getElementById("message").innerHTML = msg;
});
</script>
</body>
</html>
You can now test this very simple example and see some output similar to the following:
$ node server.js
listening on *:3001
0.9575486415997148
0.7801907607354224
0.665313188219443
0.8101786421611905
0.890920243691653
If you open up a web browser, and point it to the hostname you're running the node process on, you should see the same numbers appear in your browser, along with any other connected browser looking at that same page.
Rather than querying the DOM for elements (which isn't very angular see "Thinking in AngularJS" if I have a jQuery background?) you should perform your DOM manipulation within your directive. The element is available to you in your link function.
So in your myDirective
return {
link: function (scope, element, attr) {
element.html('Hello world');
}
}
If you must perform the query outside of the directive then it would be possible to use querySelectorAll in modern browers
angular.element(document.querySelectorAll("[my-directive]"));
however you would need to use jquery to support IE8 and backwards
angular.element($("[my-directive]"));
or write your own method as demonstrated here Get elements by attribute when querySelectorAll is not available without using libraries?
You can use this method to log the exception stack to String
public String stackTraceToString(Throwable e) {
StringBuilder sb = new StringBuilder();
for (StackTraceElement element : e.getStackTrace()) {
sb.append(element.toString());
sb.append("\n");
}
return sb.toString();
}
I simply add the return key word like:
return res.redirect("/great");
and walla!
I think in this case you want something like this:
$(window).resize(resize=function resize(){ some code...}
Now u can call resize() within some other nested functions:
$(window).scroll(function(){ resize();}
Try this:
<div id="wrapper">
<div class="float left">left</div>
<div class="float right">right</div>
</div>
#wrapper {
width:500px;
height:300px;
position:relative;
}
.float {
background-color:black;
height:300px;
margin:0;
padding:0;
color:white;
}
.left {
background-color:blue;
position:fixed;
width:400px;
}
.right {
float:right;
width:100px;
}
jsFiddle: http://jsfiddle.net/khA4m
What is the difference between Git and GitHub?
Linus Torvalds would kill you for this. Git is the name of the version manager program he wrote. GitHub is a website on which there are source code repositories manageable by Git. Thus, GitHub is completely unrelated to the original Git tool.
Is git saving every repository locally (in the user's machine) and in GitHub?
If you commit changes, it stores locally. Then, if you push the commits, it also sotres them remotely.
Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?
You can, but I'm sure you don't want to manually set up a git server for yourself. Benefits of GitHub? Well, easy to use, lot of people know it so others may find your code and follow/fork it to make improvements as well.
How does Git compare to a backup system such as Time Machine?
Git is specifically designed and optimized for source code.
Is this a manual process, in other words if you don't commit you wont have a new version of the changes made?
Exactly.
If are not collaborating and you are already using a backup system why would you use Git?
See #4.
If your exe takes arguments,
start MyApp.exe -arg1 -arg2
Actually, this example helped me to understand what does (function($) {})(jQuery);
mean.
Consider this:
// Clousure declaration (aka anonymous function)
var f = function(x) { return x*x; };
// And use of it
console.log( f(2) ); // Gives: 4
// An inline version (immediately invoked)
console.log( (function(x) { return x*x; })(2) ); // Gives: 4
And now consider this:
jQuery
is a variable holding jQuery object.$
is a variable
name like any other (a
, $b
, a$b
etc.) and it doesn't have any
special meaning like in PHP.Knowing that we can take another look at our example:
var $f = function($) { return $*$; };
var jQuery = 2;
console.log( $f(jQuery) ); // Gives: 4
// An inline version (immediately invoked)
console.log( (function($) { return $*$; })(jQuery) ); // Gives: 4
Its workaround.
If you not push to server, you will clone into new folder else washout(delete all files) from your repository folder and clone new.
There are several issues:
getElementsByClassName()
.Example (untested):
<script type="text/javascript">
function hideTd(className){
var elements = document.getElementsByClassName(className);
for(var i = 0, length = elements.length; i < length; i++) {
if( elements[i].textContent == ''){
elements[i].style.display = 'none';
}
}
}
</script>
</head>
<body onload="hideTd('td');">
<table border="1">
<tr>
<td class="td">not empty</td>
</tr>
<tr>
<td class="td"></td>
</tr>
<tr>
<td class="td"></td>
</tr>
</table>
</body>
Note that getElementsByClassName()
is not available up to and including IE8.
Update:
Alternatively you can give the table an ID and use:
var elements = document.getElementById('tableID').getElementsByTagName('td');
to get all td
elements.
To hide the parent row, use the parentNode
property of the element:
elements[i].parentNode.style.display = "none";
For apache look up SymLink or you can solve via the OS with Symbolic Links or on linux set up a library link/etc
My answer is one method specifically to windows 10.
So my method involves mapping a network drive to U:/ (e.g. I use G:/ for Google Drive)
open cmd
and type hostname
(example result: LAPTOP-G666P000
, you could use your ip instead, but using a static hostname for identifying yourself makes more sense if your network stops)
Press Windows_key + E
> right click 'This PC'
> press N
(It's Map Network drive, NOT add a network location)
If you are right clicking the shortcut on the desktop you need to press N then enter
Fill out U:
or G:
or Z:
or whatever you want
Example Address: \\LAPTOP-G666P000\c$\Users\username\
Then you can use <a href="file:///u:/2ndFile.html"><button type="submit">Local file</button>
like in your question
related: You can also use this method for FTPs, and setup multiple drives for different relative paths on that same network.
related2: I have used http://localhost/c$
etc before on some WAMP/apache servers too before, you can use .htaccess
for control/security but I recommend to not do so on a live/production machine -- or any other symlink documentroot example you can google
Using def change
means you should write migrations that are reversible. And change_column
is not reversible. You can go up but you cannot go down, since change_column
is irreversible.
Instead, though it may be a couple extra lines, you should use def up
and def down
So if you have a column with no default value, then you should do this to add a default value.
def up
change_column :users, :admin, :boolean, default: false
end
def down
change_column :users, :admin, :boolean, default: nil
end
Or if you want to change the default value for an existing column.
def up
change_column :users, :admin, :boolean, default: false
end
def down
change_column :users, :admin, :boolean, default: true
end
The advice you were given is flawed. Unconditionally setting GIT_AUTHOR_DATE in an --env-filter
would rewrite the date of every commit. Also, it would be unusual to use git commit inside --index-filter
.
You are dealing with multiple, independent problems here.
Each commit has two dates: the author date and the committer date. You can override each by supplying values through the environment variables GIT_AUTHOR_DATE and GIT_COMMITTER_DATE for any command that writes a new commit. See “Date Formats” in git-commit(1) or the below:
Git internal format = <unix timestamp> <time zone offset>, e.g. 1112926393 +0200
RFC 2822 = e.g. Thu, 07 Apr 2005 22:13:13 +0200
ISO 8601 = e.g. 2005-04-07T22:13:13
The only command that writes a new commit during normal use is git commit. It also has a --date
option that lets you directly specify the author date. Your anticipated usage includes git filter-branch --env-filter
also uses the environment variables mentioned above (these are part of the “env” after which the option is named; see “Options” in git-filter-branch(1) and the underlying “plumbing” command git-commit-tree(1).
If your repository is very simple (i.e. you only have a single branch, no tags), then you can probably use git rebase to do the work.
In the following commands, use the object name (SHA-1 hash) of the commit instead of “A”. Do not forget to use one of the “date override” methods when you run git commit.
---A---B---C---o---o---o master
git checkout master
git checkout A~0
git add path/to/file
git commit --date='whenever'
git tag ,new-commit -m'delete me later'
git checkout -
git rebase --onto ,new-commit A
git tag -d ,new-commit
---A---N (was ",new-commit", but we delete the tag)
\
B'---C'---o---o---o master
If you wanted to update A to include the new file (instead of creating a new commit where it was added), then use git commit --amend
instead of git commit
. The result would look like this:
---A'---B'---C'---o---o---o master
The above works as long as you can name the commit that should be the parent of your new commit. If you actually want your new file to be added via a new root commit (no parents), then you need something a bit different:
B---C---o---o---o master
git checkout master
git checkout --orphan new-root
git rm -rf .
git add path/to/file
GIT_AUTHOR_DATE='whenever' git commit
git checkout -
git rebase --root --onto new-root
git branch -d new-root
N (was new-root, but we deleted it)
\
B'---C'---o---o---o master
git checkout --orphan
is relatively new (Git 1.7.2), but there are other ways of doing the same thing that work on older versions of Git.
If your repository is more complex (i.e. it has more than one ref (branches, tags, etc.)), then you will probably need to use git filter-branch. Before using git filter-branch, you should make a backup copy of your entire repository. A simple tar archive of your entire working tree (including the .git directory) is sufficient. git filter-branch does make backup refs, but it is often easier to recover from a not-quite-right filtering by just deleting your .git
directory and restoring it from your backup.
Note: The examples below use the lower-level command git update-index --add
instead of git add
. You could use git add, but you would first need to copy the file from some external location to the expected path (--index-filter
runs its command in a temporary GIT_WORK_TREE that is empty).
If you want your new file to be added to every existing commit, then you can do this:
new_file=$(git hash-object -w path/to/file)
git filter-branch \
--index-filter \
'git update-index --add --cacheinfo 100644 '"$new_file"' path/to/file' \
--tag-name-filter cat \
-- --all
git reset --hard
I do not really see any reason to change the dates of the existing commits with --env-filter 'GIT_AUTHOR_DATE=…'
. If you did use it, you would have make it conditional so that it would rewrite the date for every commit.
If you want your new file to appear only in the commits after some existing commit (“A”), then you can do this:
file_path=path/to/file
before_commit=$(git rev-parse --verify A)
file_blob=$(git hash-object -w "$file_path")
git filter-branch \
--index-filter '
if x=$(git rev-list -1 "$GIT_COMMIT" --not '"$before_commit"') &&
test -n "$x"; then
git update-index --add --cacheinfo 100644 '"$file_blob $file_path"'
fi
' \
--tag-name-filter cat \
-- --all
git reset --hard
If you want the file to be added via a new commit that is to be inserted into the middle of your history, then you will need to generate the new commit prior to using git filter-branch and add --parent-filter
to git filter-branch:
file_path=path/to/file
before_commit=$(git rev-parse --verify A)
git checkout master
git checkout "$before_commit"
git add "$file_path"
git commit --date='whenever'
new_commit=$(git rev-parse --verify HEAD)
file_blob=$(git rev-parse --verify HEAD:"$file_path")
git checkout -
git filter-branch \
--parent-filter "sed -e s/$before_commit/$new_commit/g" \
--index-filter '
if x=$(git rev-list -1 "$GIT_COMMIT" --not '"$new_commit"') &&
test -n "$x"; then
git update-index --add --cacheinfo 100644 '"$file_blob $file_path"'
fi
' \
--tag-name-filter cat \
-- --all
git reset --hard
You could also arrange for the file to be first added in a new root commit: create your new root commit via the “orphan” method from the git rebase section (capture it in new_commit
), use the unconditional --index-filter
, and a --parent-filter
like "sed -e \"s/^$/-p $new_commit/\""
.
There are 2 errors: the second is because $dom is no string but an object and thus cannot be "echoed". The first error is a warning from loadHTML, caused by invalid syntax of the html document to load (probably an & (ampersand) used as parameter separator and not masked as entity with &).
You ignore and supress this error message (not the error, just the message!) by calling the function with the error control operator "@" (http://www.php.net/manual/en/language.operators.errorcontrol.php )
@$dom->loadHTML($html);
Either:
Using String(format:)
:
Typecast Double
to String
with %.3f
format specifier and then back to Double
Double(String(format: "%.3f", 10.123546789))!
Or extend Double
to handle N-Decimal places:
extension Double {
func rounded(toDecimalPlaces n: Int) -> Double {
return Double(String(format: "%.\(n)f", self))!
}
}
By calculation
multiply with 10^3, round it and then divide by 10^3...
(1000 * 10.123546789).rounded()/1000
Or extend Double
to handle N-Decimal places:
extension Double {
func rounded(toDecimalPlaces n: Int) -> Double {
let multiplier = pow(10, Double(n))
return (multiplier * self).rounded()/multiplier
}
}
Would like to thank you for some excellent replies. @AR., your a star and it works perfectly. I had noticed last night that the Excel.exe
was not closing; so I did some research and found out about how to release the COM objects. Here is my final code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.IO;
using Excel;
namespace testExcelconsoleApp
{
class Program
{
private String fileLoc = @"C:\temp\test.xls";
static void Main(string[] args)
{
Program p = new Program();
p.createExcel();
}
private void createExcel()
{
Excel.Application excelApp = null;
Excel.Workbook workbook = null;
Excel.Sheets sheets = null;
Excel.Worksheet newSheet = null;
try
{
FileInfo file = new FileInfo(fileLoc);
if (file.Exists)
{
excelApp = new Excel.Application();
workbook = excelApp.Workbooks.Open(fileLoc, 0, false, 5, "", "",
false, XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
sheets = workbook.Sheets;
//check columns exist
foreach (Excel.Worksheet sheet in sheets)
{
Console.WriteLine(sheet.Name);
sheet.Select(Type.Missing);
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
}
newSheet = (Worksheet)sheets.Add(sheets[1], Type.Missing, Type.Missing, Type.Missing);
newSheet.Name = "My New Sheet";
newSheet.Cells[1, 1] = "BOO!";
workbook.Save();
workbook.Close(null, null, null);
excelApp.Quit();
}
}
finally
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(newSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheets);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
newSheet = null;
sheets = null;
workbook = null;
excelApp = null;
GC.Collect();
}
}
}
}
Thank you for all your help.
The sample config you provided is actually valid YAML. In fact, YAML meets all of your demands, is implemented in a large number of languages, and is extremely human friendly. I would highly recommend you use it. The PyYAML project provides a nice python module, that implements YAML.
To use the yaml module is extremely simple:
import yaml
config = yaml.safe_load(open("path/to/config.yml"))
Since you seem to be on windows you can do this so python <filename.py>
. Check that python's bin folder is in your PATH, or you can do c:\python23\bin\python <filename.py>
. Python is an interpretive language and so you need the interpretor to run your file, much like you need java runtime to run a jar file.
Use following command to increase java heap size for tomcat7 (linux distributions) correctly:
echo 'export CATALINA_OPTS="-Xms512M -Xmx1024M"' > /usr/share/tomcat7/bin/setenv.sh
Regarding the remote repository, if you are using Github or Github Enterprise as the server location for saving/distributing your repository remotely, you can simply rename the repository directly in the repo settings.
From the main repo page, the settings tab is on the right, and the repo name is the first item on the page:
One very nice feature in Github when you rename a repo, is that Github will save the old repo name and all the related URLs and redirect traffic to the new URLs. Since your username/org and repo name are a part of the URL, a rename will change the URL.
Since Github saves the old repo name and redirects requests to the new URLs, if anyone uses links based on the old repo name when trying to access issues, wiki, stars, or followers they will still arrive at the new location on the Github website. Github also redirects lower level Git commands like git clone
, git fetch
, etc.
More information is in the Github Help for Renaming a Repo
As others have mentioned, the local "name" of your repo is typically considered to be the root folder/directory name, and you can change that, move, or copy the folder to any location and it will not affect the repo at all.
Git is designed to only worry about files inside the root folder.
IMHO the best place to find this information is: http://code.google.com/p/yahoo-finance-managed/
I used to use the "gummy-stuff" too but then I found this page which is far more organized and full of easy to use examples. I am using it now to get the data in CSV files and use the files in my C++/Qt project.
Try this
<input type="text"/>
It will display same in all cross browser like mozilla , chrome and internet explorer.
<style>
input{
border:2px solid #FF0000;
}
</style>
Dont add style inline because its not good practise, use class to add style for your input box.
you may also do
git pull -r origin master
fix merge conflicts if any
git rebase --continue
-r is for rebase. This will make you branch structure from
v master
o-o-o-o-o
\o-o-o
^ other branch
to
v master
o-o-o-o-o-o-o-o
^ other branch
This will lead to a cleaner history. Note: In case you have already pushed your other-branch to origin( or any other remote), you may have to force push your branch after rebase.
git push -f origin other-branch
Abstract your initialization into a method, and call the method from mounted
and wherever else you want.
new Vue({
methods:{
init(){
//call API
//Setup game
}
},
mounted(){
this.init()
}
})
Then possibly have a button in your template to start over.
<button v-if="playerWon" @click="init">Play Again</button>
In this button, playerWon
represents a boolean value in your data that you would set when the player wins the game so the button appears. You would set it back to false in init
.
Old question but here's the code on how to do what you are asking. In this case I am passing data from a selected cell in a table view to another view controller.
in the .h file of the trget view:
@property(weak, nonatomic) NSObject* dataModel;
in the .m file:
@synthesize dataModel;
dataModel
can be string
, int
, or like in this case it's a model that contains many items
- (void)someMethod {
[self performSegueWithIdentifier:@"loginMainSegue" sender:self];
}
OR...
- (void)someMethod {
UIViewController *myController = [self.storyboard instantiateViewControllerWithIdentifier:@"HomeController"];
[self.navigationController pushViewController: myController animated:YES];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if([segue.identifier isEqualToString:@"storyDetailsSegway"]) {
UITableViewCell *cell = (UITableViewCell *) sender;
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
NSDictionary *storiesDict =[topStories objectAtIndex:[indexPath row]];
StoryModel *storyModel = [[StoryModel alloc] init];
storyModel = storiesDict;
StoryDetails *controller = (StoryDetails *)segue.destinationViewController;
controller.dataModel= storyModel;
}
}
In my case, the problem was caused by not being logged in with Postman, so I opened a connection in another tab with a session cookie I took from the headers in my Chrome session.
Try This
$(function() {
var doubleClicked = false;
$(document).on("contextmenu", function (e) {
if(doubleClicked == false) {
e.preventDefault(); // To prevent the default context menu.
var windowHeight = $(window).height()/2;
var windowWidth = $(window).width()/2;
if(e.clientY > windowHeight && e.clientX <= windowWidth) {
$("#contextMenuContainer").css("left", e.clientX);
$("#contextMenuContainer").css("bottom", $(window).height()-e.clientY);
$("#contextMenuContainer").css("right", "auto");
$("#contextMenuContainer").css("top", "auto");
} else if(e.clientY > windowHeight && e.clientX > windowWidth) {
$("#contextMenuContainer").css("right", $(window).width()-e.clientX);
$("#contextMenuContainer").css("bottom", $(window).height()-e.clientY);
$("#contextMenuContainer").css("left", "auto");
$("#contextMenuContainer").css("top", "auto");
} else if(e.clientY <= windowHeight && e.clientX <= windowWidth) {
$("#contextMenuContainer").css("left", e.clientX);
$("#contextMenuContainer").css("top", e.clientY);
$("#contextMenuContainer").css("right", "auto");
$("#contextMenuContainer").css("bottom", "auto");
} else {
$("#contextMenuContainer").css("right", $(window).width()-e.clientX);
$("#contextMenuContainer").css("top", e.clientY);
$("#contextMenuContainer").css("left", "auto");
$("#contextMenuContainer").css("bottom", "auto");
}
$("#contextMenuContainer").fadeIn(500, FocusContextOut());
doubleClicked = true;
} else {
e.preventDefault();
doubleClicked = false;
$("#contextMenuContainer").fadeOut(500);
}
});
function FocusContextOut() {
$(document).on("click", function () {
doubleClicked = false;
$("#contextMenuContainer").fadeOut(500);
$(document).off("click");
});
}
});
In standard SQL syntax, you would use:
WHERE mydate <= DATE '2008-11-20'
That is, the keyword DATE should precede the string. In some DBMS, however, you don't need to be that explicit; the system will convert the DATE column into a string, or the string into a DATE value, automatically. There are nominally some interesting implications if the DATE is converted into a string - if you happen to have dates in the first millennium (0001-01-01 .. 0999-12-31) and the leading zero(es) are omitted by the formatting system.
var SelecetdSteps = Context.FFTrakingSubCriticalSteps
.Where(x => x.MeetingId == meetid)
.Select(x =>
x.StepID
);
var crtiticalsteps = Context.MT_CriticalSteps.Where(x =>x.cropid==FFT.Cropid).Select(x=>new
{
StepID= x.crsid,
x.Name,
Checked=false
});
var quer = from ax in crtiticalsteps
where (!SelecetdSteps.Contains(ax.StepID))
select ax;
$array = str_split("$string");
will actuall work pretty fine, BUT if you want to preserve the special characters in that string, and you want to do some manipulation with them, THAN I would use
do {
$array[] = mb_substr( $string, 0, 1, 'utf-8' );
} while ( $string = mb_substr( $string, 1, mb_strlen( $string ), 'utf-8' ) );
because for some of mine personal uses, it has been shown to be more reliable when there is an issue with special characters
I think you can initialize the variables a value like -1
,
because if the int
type variables is not initialized it can't be used.
When you want to check if it is not the value you want you can check if it is -1
.
Apache Commons offers commons-graph. Under http://svn.apache.org/viewvc/commons/sandbox/graph/trunk/ one can inspect the source. Sample API usage is in the SVN, too. See https://issues.apache.org/jira/browse/SANDBOX-458 for a list of implemented algorithms, also compared with Jung, GraphT, Prefuse, jBPT
Google Guava if you need good datastructures only.
JGraphT is a graph library with many Algorithms implemented and having (in my oppinion) a good graph model. Helloworld Example. License: LGPL+EPL.
JUNG2 is also a BSD-licensed library with the data structure similar to JGraphT. It offers layouting algorithms, which are currently missing in JGraphT. The most recent commit is from 2010 and packages hep.aida.*
are LGPL (via the colt library, which is imported by JUNG). This prevents JUNG from being used in projects under the umbrella of ASF and ESF. Maybe one should use the github fork and remove that dependency. Commit f4ca0cd is mirroring the last CVS commit. The current commits seem to remove visualization functionality. Commit d0fb491c adds a .gitignore
.
Prefuse stores the graphs using a matrix structure, which is not memory efficient for sparse graphs. License: BSD
Eclipse Zest has built in graph layout algorithms, which can be used independently of SWT. See org.eclipse.zest.layouts.algorithms. The graph structure used is the one of Eclipse Draw2d, where Nodes are explicit objects and not injected via Generics (as it happens in Apache Commons Graph, JGraphT, and JUNG2).
another way to create a data url from blob url may be using canvas.
var canvas = document.createElement("canvas")
var context = canvas.getContext("2d")
context.drawImage(img, 0, 0) // i assume that img.src is your blob url
var dataurl = canvas.toDataURL("your prefer type", your prefer quality)
as what i saw in mdn, canvas.toDataURL is supported well by browsers. (except ie<9, always ie<9)
time1
is the key of the most outer dictionary, eg, feb2012
. So then you're trying to index the string, but you can only do this with integers. I think what you wanted was:
for info in courses[time1][course]:
As you're going through each dictionary, you must add another nest.
Just for completeness, let's not forget the Simplest Thing That Could Possibly Work:
for i in list:
if i.n == 5:
# do something with it
print "YAY! Found one!"
The flowchart below can be of help when choosing one of the various semantic HTML5 elements: