For one thing, it says you already have that module installed. If you need to upgrade it, you should do something like this:
easy_install -U packageName
Of course, easy_install doesn't work very well if the package has some C headers that need to be compiled and you don't have the right version of Visual Studio installed. You might try using pip or distribute instead of easy_install and see if they work better.
Offset Means "the amount or distance by which something is out of line". Margin or Borders are something which makes the actual height or width of an HTML element "out of line". It will help you to remember that :
- offsetHeight is a measurement in pixels of the element's CSS height, including border, padding and the element's horizontal scrollbar.
On the other hand, clientHeight is something which is you can say kind of the opposite of OffsetHeight. It doesn't include the border or margins. It does include the padding because it is something that resides inside of the HTML container, so it doesn't count as extra measurements like margin or border. So :
- clientHeight property returns the viewable height of an element in pixels, including padding, but not the border, scrollbar or margin.
ScrollHeight is all the scrollable area, so your scroll will never run over your margin or border, so that's why scrollHeight doesn't include margin or borders but yeah padding does. So:
- scrollHeight value is equal to the minimum height the element would require in order to fit all the content in the viewport without using a vertical scrollbar. The height is measured in the same way as clientHeight: it includes the element's padding, but not its border, margin or horizontal scrollbar.
It looks like a common gaps-and-islands problem. The difference between two sequences of row numbers rn1
and rn2
give the "group" number.
Run this query CTE-by-CTE and examine intermediate results to see how it works.
Sample data
I expanded sample data from the question a little.
DECLARE @Source TABLE
(
EmployeeID int,
DateStarted date,
DepartmentID int
)
INSERT INTO @Source
VALUES
(10001,'2013-01-01',001),
(10001,'2013-09-09',001),
(10001,'2013-12-01',002),
(10001,'2014-05-01',002),
(10001,'2014-10-01',001),
(10001,'2014-12-01',001),
(10005,'2013-05-01',001),
(10005,'2013-11-09',001),
(10005,'2013-12-01',002),
(10005,'2014-10-01',001),
(10005,'2016-12-01',001);
Query for SQL Server 2008
There is no LEAD
function in SQL Server 2008, so I had to use self-join via OUTER APPLY
to get the value of the "next" row for the DateEnd
.
WITH
CTE
AS
(
SELECT
EmployeeID
,DateStarted
,DepartmentID
,ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS rn1
,ROW_NUMBER() OVER (PARTITION BY EmployeeID, DepartmentID ORDER BY DateStarted) AS rn2
FROM @Source
)
,CTE_Groups
AS
(
SELECT
EmployeeID
,MIN(DateStarted) AS DateStart
,DepartmentID
FROM CTE
GROUP BY
EmployeeID
,DepartmentID
,rn1 - rn2
)
SELECT
CTE_Groups.EmployeeID
,CTE_Groups.DepartmentID
,CTE_Groups.DateStart
,A.DateEnd
FROM
CTE_Groups
OUTER APPLY
(
SELECT TOP(1) G2.DateStart AS DateEnd
FROM CTE_Groups AS G2
WHERE
G2.EmployeeID = CTE_Groups.EmployeeID
AND G2.DateStart > CTE_Groups.DateStart
ORDER BY G2.DateStart
) AS A
ORDER BY
EmployeeID
,DateStart
;
Query for SQL Server 2012+
Starting with SQL Server 2012 there is a LEAD
function that makes this task more efficient.
WITH
CTE
AS
(
SELECT
EmployeeID
,DateStarted
,DepartmentID
,ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS rn1
,ROW_NUMBER() OVER (PARTITION BY EmployeeID, DepartmentID ORDER BY DateStarted) AS rn2
FROM @Source
)
,CTE_Groups
AS
(
SELECT
EmployeeID
,MIN(DateStarted) AS DateStart
,DepartmentID
FROM CTE
GROUP BY
EmployeeID
,DepartmentID
,rn1 - rn2
)
SELECT
CTE_Groups.EmployeeID
,CTE_Groups.DepartmentID
,CTE_Groups.DateStart
,LEAD(CTE_Groups.DateStart) OVER (PARTITION BY CTE_Groups.EmployeeID ORDER BY CTE_Groups.DateStart) AS DateEnd
FROM
CTE_Groups
ORDER BY
EmployeeID
,DateStart
;
Result
+------------+--------------+------------+------------+
| EmployeeID | DepartmentID | DateStart | DateEnd |
+------------+--------------+------------+------------+
| 10001 | 1 | 2013-01-01 | 2013-12-01 |
| 10001 | 2 | 2013-12-01 | 2014-10-01 |
| 10001 | 1 | 2014-10-01 | NULL |
| 10005 | 1 | 2013-05-01 | 2013-12-01 |
| 10005 | 2 | 2013-12-01 | 2014-10-01 |
| 10005 | 1 | 2014-10-01 | NULL |
+------------+--------------+------------+------------+
Using a single Awk:
... | awk -F '[/:]' '{print $5}'
That is, using as field separator either /
or :
, the username is always in field 5.
To store it in a variable:
username=$(... | awk -F '[/:]' '{print $5}')
A more flexible implementation with sed
that doesn't require username to be field 5:
... | sed -e s/:.*// -e s?.*/??
That is, delete everything from :
and beyond, and then delete everything up until the last /
. sed
is probably faster too than awk
, so this alternative is definitely better.
i prefer the most readable and extensible way using jquery.
Also, you can build fully dynamic content on the fly.
Since jquery version 1.4 you can pass attributes to elements which is,
imho, a killer feature.
Also the code can be kept cleaner.
$(function(){
var tablerows = new Array();
$.each(['result1', 'result2', 'result3'], function( index, value ) {
tablerows.push('<tr><td>' + value + '</td></tr>');
});
var table = $('<table/>', {
html: tablerows
});
var div = $('<div/>', {
id: 'here_table',
html: table
});
$('body').append(div);
});
Addon: passing more than one "html" tag you've to use array notation like: e.g.
var div = $('<div/>', {
id: 'here_table',
html: [ div1, div2, table ]
});
best Rgds.
Franz
I know this question was specific to JavaScript, however, there seems to be no good, clean way to ALWAYS detect when a textarea changes in all current browsers. I've learned jquery has taken care of it for us. It even handles contextual menu changes to text areas. The same syntax is used regardless of input type.
$('div.lawyerList').on('change','textarea',function(){
// Change occurred so count chars...
});
or
$('textarea').on('change',function(){
// Change occurred so count chars...
});
I had the same issue, and by Running "exec sp_updatestats" the issue solved and works now
I usually encode the binary data with MIME Base64 or URL encoding.
There's an alternative that's quite unreadable in my opinion but I'll share anyway just as a curiosity:
x = (i>100 and 2) or (i<100 and 1) or 0
More info here: https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not
You can loop through a hash map like this
<%
ArrayList list = new ArrayList();
TreeMap itemList=new TreeMap();
itemList.put("test", "test");
list.add(itemList);
pageContext.setAttribute("itemList", list);
%>
<c:forEach items="${itemList}" var="itemrow">
<input type="text" value="<c:out value='${itemrow.test}'/>"/>
</c:forEach>
For more JSTL functionality look here
See section Attributes from documentation on directives.
observing interpolated attributes: Use $observe to observe the value changes of attributes that contain interpolation (e.g. src="{{bar}}"). Not only is this very efficient but it's also the only way to easily get the actual value because during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set to undefined.
for jqLite just use triggerHandler with event name, To simulate a "click" try:
angular.element("tr").triggerHandler("click");
_x000D_
Based on the answer here by @Hendy Irawan
Show database sizes:
\l+
e.g.
=> \l+
berbatik_prd_commerce | berbatik_prd | UTF8 | en_US.UTF-8 | en_US.UTF-8 | | 19 MB | pg_default |
berbatik_stg_commerce | berbatik_stg | UTF8 | en_US.UTF-8 | en_US.UTF-8 | | 8633 kB | pg_default |
bursasajadah_prd | bursasajadah_prd | UTF8 | en_US.UTF-8 | en_US.UTF-8 | | 1122 MB | pg_default |
Show table sizes:
\d+
e.g.
=> \d+
public | tuneeca_prd | table | tomcat | 8192 bytes |
public | tuneeca_stg | table | tomcat | 1464 kB |
Only works in psql
.
I had trouble binding a value with any of the symbols in AngularJS 1.6. I did not get any value at all, only undefined
, even though I did it the exact same way as other bindings in the same file that did work.
Problem was: my variable name had an underscore.
This fails:
bindings: { import_nr: '='}
This works:
bindings: { importnr: '='}
(Not completely related to the original question, but that was one of the top search results when I looked, so hopefully this helps someone with the same problem.)
You can use a window MAX() like this:
SELECT
*,
max_date = MAX(date) OVER (PARTITION BY group)
FROM table
to get max dates per group
alongside other data:
group date cash checks max_date
----- -------- ---- ------ --------
1 1/1/2013 0 0 1/3/2013
2 1/1/2013 0 800 1/1/2013
1 1/3/2013 0 700 1/3/2013
3 1/1/2013 0 600 1/5/2013
1 1/2/2013 0 400 1/3/2013
3 1/5/2013 0 200 1/5/2013
Using the above output as a derived table, you can then get only rows where date
matches max_date
:
SELECT
group,
date,
checks
FROM (
SELECT
*,
max_date = MAX(date) OVER (PARTITION BY group)
FROM table
) AS s
WHERE date = max_date
;
to get the desired result.
Basically, this is similar to @Twelfth's suggestion but avoids a join and may thus be more efficient.
You can try the method at SQL Fiddle.
Please make sure you are not trying to open and close the database repeatedly either from main thread or background thread.
Make a singleton class in your application and try to create and open data from this class only.
Is guarantees you that database open call is made only when it does not exist.
In your entire application use the same approach of getting sqLiteDatabase object when it is required.
I used below code and my problem is solved now after 1.5 days.
...............................................................
In Your Activity class onCreate() method
public class MainActivity extends AppCompatActivity {
private AssetsDatabaseHelper helper;
@Override
protected void onCreate(Bundle savedInstanceState) {
helper = AssetsDatabaseHelper.getInstance(this);
sqLiteDatabase = helper.getDatabase();
}
}
public class AssetsDatabaseHelper {
Context context;
SQLiteDatabase sqLiteDatabase;
DatabaseHelper databaseHelper;
private static AssetsDatabaseHelper instance;
private AssetsDatabaseHelper(Context context){
this.context = context;
databaseHelper = new DatabaseHelper(context);
if(databaseHelper.checkDatabase()){
try{
databaseHelper.openDatabase();
}catch(SQLException sqle){
Log.e("Exception in opening ", " :: database :: sqle.getCause() : "+sqle.getCause());
}
}else{
try{
databaseHelper.createDatabase();
}catch(IOException ioe){
Log.d("Exception in creating ", " :: database :: ioe.getCause() : "+ioe.getCause());
}
try{
databaseHelper.openDatabase();
}catch(SQLException sqle){
Log.e("Exception in opening ", " :: database :: "+sqle.getCause());
}
}
sqLiteDatabase = databaseHelper.getSqLiteDatabase();
}
public static AssetsDatabaseHelper getInstance(Context context){
if(instance != null){
return instance;
}else {
instance = new AssetsDatabaseHelper(context);
return instance;
}
}
public SQLiteDatabase getDatabase(){
return sqLiteDatabase;
}
}
Use df.to_dict('records')
-- gives the output without having to transpose externally.
In [2]: df.to_dict('records')
Out[2]:
[{'customer': 1L, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'},
{'customer': 2L, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'},
{'customer': 3L, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}]
public static int GCD(int x, int y) {
int r;
while (y!=0) {
r = x%y;
x = y;
y = r;
}
return x;
}
the function Position
in funprog {base} also does the job. It allows you to pass an arbitrary function, and returns the first or last match.
Position(f, x, right = FALSE, nomatch = NA_integer)
You don't need align="center"
and float:left
. Remove both of these. margin: 0 auto
is sufficient.
It appears to be a known issue.
http://dev.mysql.com/doc/refman/5.1/en/unnamed-views.html
http://bugs.mysql.com/bug.php?id=16757
Many IN queries can be re-written as (left outer) joins and an IS (NOT) NULL of some sort. for example
SELECT * FROM FOO WHERE ID IN (SELECT ID FROM FOO2)
can be re-written as
SELECT FOO.* FROM FOO JOIN FOO2 ON FOO.ID=FOO2.ID
or
SELECT * FROM FOO WHERE ID NOT IN (SELECT ID FROM FOO2)
can be
SELECT FOO.* FROM FOO
LEFT OUTER JOIN FOO2
ON FOO.ID=FOO2.ID WHERE FOO.ID IS NULL
This is a short and simple example I just used:
If:
fp = open("file.txt", "w")
Then:
fp.write(line.replace('is', 'now'))
// "This is me" becomes "This now me"
Not:
line.replace('is', 'now')
fp.write(line)
// "This is me" not changed while writing
Access the field with array notation to avoid strict type checking on single field:
data['propertyName']; //will work even if data has not declared propertyName
Alternative way is (un)cast the variable for single access:
(<any>data).propertyName;//access propertyName like if data has no type
The first is shorter, the second is more explicit about type (un)casting
You can also totally disable type checking on all variable fields:
let untypedVariable:any= <any>{}; //disable type checking while declaring the variable
untypedVariable.propertyName = anyValue; //any field in untypedVariable is assignable and readable without type checking
Note: This would be more dangerous than avoid type checking just for a single field access, since all consecutive accesses on all fields are untyped
Another option:
$ cat << EOF > ~/.ipython/profile_default/startup/50-autoreload.ipy
%load_ext autoreload
%autoreload 2
EOF
Verified on ipython and ipython3 v5.1.0 on Ubuntu 14.04.
"Knowing about sites which handles such massive traffic gives lots of pointers for architects etc. to keep in mind certain stuff while designing new sites"
I think you can probably learn a lot from the design of Facebook, just as you can from the design of any successful large software system. However, it seems to me that you should not keep the current design of Facebook in mind when designing new systems.
Why do you want to be able to handle the traffic that Facebook has to handle? Odds are that you will never have to, no matter how talented a programmer you may be. Facebook itself was not designed from the start for such massive scalability, which is perhaps the most important lesson to learn from it.
If you want to learn about a non-trivial software system I can recommend the book "Dissecting a C# Application" about the development of the SharpDevelop IDE. It is out of print, but it is available for free online. The book gives you a glimpse into a real application and provides insights about IDEs which are useful for a programmer.
Because %
is only defined for integer types. That's the modulus operator.
5.6.2 of the standard:
The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]
As Oli pointed out, you can use fmod()
. Don't forget to include math.h
.
Hope this example helps too
I have done java coding in a similar way for the below json array example as follows :
following is the json data format : stored as "EMPJSONDATA.json"
[{"EMPNO":275172,"EMP_NAME":"Rehan","DOB":"29-02-1992","DOJ":"10-06-2013","ROLE":"JAVA DEVELOPER"},
{"EMPNO":275173,"EMP_NAME":"G.K","DOB":"10-02-1992","DOJ":"11-07-2013","ROLE":"WINDOWS ADMINISTRATOR"},
{"EMPNO":275174,"EMP_NAME":"Abiram","DOB":"10-04-1992","DOJ":"12-08-2013","ROLE":"PROJECT ANALYST"}
{"EMPNO":275174,"EMP_NAME":"Mohamed Mushi","DOB":"10-04-1992","DOJ":"12-08-2013","ROLE":"PROJECT ANALYST"}]
public class Jsonminiproject {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
JSONArray a = (JSONArray) parser.parse(new FileReader("F:/JSON DATA/EMPJSONDATA.json"));
for (Object o : a)
{
JSONObject employee = (JSONObject) o;
Long no = (Long) employee.get("EMPNO");
System.out.println("Employee Number : " + no);
String st = (String) employee.get("EMP_NAME");
System.out.println("Employee Name : " + st);
String dob = (String) employee.get("DOB");
System.out.println("Employee DOB : " + dob);
String doj = (String) employee.get("DOJ");
System.out.println("Employee DOJ : " + doj);
String role = (String) employee.get("ROLE");
System.out.println("Employee Role : " + role);
System.out.println("\n");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
If it's a list of string, just use the c()
function :
R> LL <- list(a="tom", b="dick")
R> c(LL, c="harry")
$a
[1] "tom"
$b
[1] "dick"
$c
[1] "harry"
R> class(LL)
[1] "list"
R>
That works on vectors too, so do I get the bonus points?
Edit (2015-Feb-01): This post is coming up on its fifth birthday. Some kind readers keep repeating any shortcomings with it, so by all means also see some of the comments below. One suggestion for list
types:
newlist <- list(oldlist, list(someobj))
In general, R types can make it hard to have one and just one idiom for all types and uses.
Another option is to use the getBoundingClientRect function. Please note that getBoundingClientRect will return an empty rect if the element's display is 'none'.
Example:
var elem = document.getElementById("myDiv");
if(elem) {
var rect = elem.getBoundingClientRect();
console.log("height: " + rect.height);
}
UPDATE: Here is the same code written in 2020:
const elem = document.querySelector("#myDiv");
if(elem) {
const rect = elem.getBoundingClientRect();
console.log(`height: ${rect.height}`);
}
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
foreach(DataRow row in dt.Rows)
{
TextBox1.Text = row["ImagePath"].ToString();
}
...assumes the connection is open and the command is set up properly. I also didn't check the syntax, but it should give you the idea.
you can achive it with group join
var result = (from c in Customers
join oi in OrderItems on c.Id equals oi.Order.Customer.Id into g
Select new { customer = c, orderItems = g});
c is Customer and g is the customers order items.
There are some actions which are not working in chrome, inside of the unload event. Alert or confirm boxes are such things.
But what is possible (AFAIK):
Example for #2:
$(window).on('beforeunload', function() {
return 'Your own message goes here...';
});
To get the absolute position of an UI element within the window you can use:
Point position = desiredElement.PointToScreen(new Point(0d, 0d));
If you are within an User Control, and simply want relative position of the UI element within that control, simply use:
Point position = desiredElement.PointToScreen(new Point(0d, 0d)),
controlPosition = this.PointToScreen(new Point(0d, 0d));
position.X -= controlPosition.X;
position.Y -= controlPosition.Y;
Stuart's answer provides a great explanation, but I'd like to provide another example.
I ran into this issue when attempting to perform a reduce
on a Stream containing null values (actually it was LongStream.average()
, which is a type of reduction). Since average() returns OptionalDouble
, I assumed the Stream could contain nulls but instead a NullPointerException was thrown. This is due to Stuart's explanation of null v. empty.
So, as the OP suggests, I added a filter like so:
list.stream()
.filter(o -> o != null)
.reduce(..);
Or as tangens pointed out below, use the predicate provided by the Java API:
list.stream()
.filter(Objects::nonNull)
.reduce(..);
From the mailing list discussion Stuart linked: Brian Goetz on nulls in Streams
After the merge, it's safe to delete the branch:
git branch -d branch1
Additionally, git will warn you (and refuse to delete the branch) if it thinks you didn't fully merge it yet. If you forcefully delete a branch (with git branch -D
) which is not completely merged yet, you have to do some tricks to get the unmerged commits back though (see below).
There are some reasons to keep a branch around though. For example, if it's a feature branch, you may want to be able to do bugfixes on that feature still inside that branch.
If you also want to delete the branch on a remote host, you can do:
git push origin :branch1
This will forcefully delete the branch on the remote (this will not affect already checked-out repositiories though and won't prevent anyone with push access to re-push/create it).
git reflog
shows the recently checked out revisions. Any branch you've had checked out in the recent repository history will also show up there. Aside from that, git fsck
will be the tool of choice at any case of commit-loss in git.
background: #13486d; /* for non-css3 browsers */
background-image: -webkit-gradient(linear, left top, left bottom, from(#9dc3c3), to(#13486d)); background: -moz-linear-gradient(top, #9dc3c3, #13486d);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#9dc3c3', endColorstr='#13486d');
background-repeat:no-repeat;
The above answer didn't work with Angular 6. So following is how I resolved it. Lets say this is how I defined my input box -
<input type="number" id="myTextBox" name="myTextBox"_x000D_
[(ngModel)]="response.myTextBox"_x000D_
#myTextBox="ngModel">
_x000D_
To check if the field is empty or not this should be the script.
<div *ngIf="!myTextBox.value" style="color:red;">_x000D_
Your field is empty_x000D_
</div>
_x000D_
Do note the subtle difference between the above answer and this answer. I have added an additional attribute .value
after my input name myTextBox
.
I don't know if the above answer worked for above version of Angular, but for Angular 6 this is how it should be done.
Some more explanation on why this check works; when there is no value present in the input box the default value of myTextBox.value
will be undefined
. As soon as you enter some text, your text becomes the new value of myTextBox.value
.
When your check is !myTextBox.value
it is checking that the value is undefined or not, it is equivalent to myTextBox.value == undefined
.
You can use this in the bat
script:
rd /s /q "c:\folder a"
Now, just change c:\folder a
to your folder's location. Quotation is only needed when your folder name contains spaces.
Alternatively, get the same "bit" version of JRE and Eclipse and then create a new shortcut with the below target (replace the installed JRE and Eclipse location/path):
"C:\studio\eclipse.exe" -vm "C:\Program Files\Java\jre7\bin\server\jvm.dll" eclipse.vm="C:\Program Files\Java\jre7\bin\server\jvm.dll" java.home="C:\Program Files\Java\jre7" java.runtime.version=1.7.0
That should do the trick.
Swift 4 answer:
// Define paragraph style - you got to pass it along to NSAttributedString constructor
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
// Define attributed string attributes
let attributes = [NSAttributedStringKey.paragraphStyle: paragraphStyle]
let attributedString = NSAttributedString(string:"Test", attributes: attributes)
The GMail web client supports mailto:
links
For regular @gmail.com
accounts: https://mail.google.com/mail/?extsrc=mailto&url=...
For G Suite accounts on domain gsuitedomain.com
: https://mail.google.com/a/gsuitedomain.com/mail/?extsrc=mailto&url=...
...
needs to be replaced with a urlencoded mailto:
link.
Generate a file from the string of your folder directory
String path="Folder directory";
File file = new File(path);
and use method exist.
If you want to generate the folder you sould use mkdir()
if (!file.exists()) {
System.out.print("No Folder");
file.mkdir();
System.out.print("Folder created");
}
1)install "lite server" and then try below command :
npm run lite
Raw Javascript can accomplish the same thing pretty quickly also:
document.getElementById("myElement").onclick = function() { return false; }
I may be wrong here but I had the same problem, after spending more time than I'm proud of I realised I had set chrome to block all pop ups and hence kept reloading without showing me the alert box. So close your window and open the page again.
If that doesn't work then you problem might be something deeper because all the solutions already given should work.
The call to InitializeComponent()
(which is usually called in the default constructor of at least Window
and UserControl
) is actually a method call to the partial class of the control (rather than a call up the object hierarchy as I first expected).
This method locates a URI to the XAML for the Window
/UserControl
that is loading, and passes it to the System.Windows.Application.LoadComponent()
static method. LoadComponent()
loads the XAML file that is located at the passed in URI, and converts it to an instance of the object that is specified by the root element of the XAML file.
In more detail, LoadComponent
creates an instance of the XamlParser
, and builds a tree of the XAML. Each node is parsed by the XamlParser.ProcessXamlNode()
. This gets passed to the BamlRecordWriter
class. Some time after this I get a bit lost in how the BAML is converted to objects, but this may be enough to help you on the path to enlightenment.
Note: Interestingly, the InitializeComponent
is a method on the System.Windows.Markup.IComponentConnector
interface, of which Window
/UserControl
implement in the partial generated class.
Hope this helps!
Bootstrap 4 (update 2019)
A multi-item carousel can be accomplished in several ways as explained here. Another option is to use separate thumbnails to navigate the carousel slides.
Bootstrap 3 (original answer)
This can be done using the grid inside each carousel item.
<div id="myCarousel" class="carousel slide">
<div class="carousel-inner">
<div class="item active">
<div class="row">
<div class="col-sm-3">..
</div>
<div class="col-sm-3">..
</div>
<div class="col-sm-3">..
</div>
<div class="col-sm-3">..
</div>
</div>
<!--/row-->
</div>
...add more item(s)
</div>
</div>
Demo example thumbnail slider using the carousel:
http://www.bootply.com/81478
Another example with carousel indicators as thumbnails: http://www.bootply.com/79859
You need the common-io.1.4.jar
file to be included in your lib
directory, or if you're working in any editor, like NetBeans, then you need to go to project properties and just add the JAR file and you will be done.
To get the common.io.jar
file just google it or just go to the Apache Tomcat website where you get the option for a free download of this file. But remember one thing: download the binary ZIP file if you're a Windows user.
One of the comments here used gs on Windows. I had some success with that on Linux/OSX too, with the following syntax:
gs \
-q \
-dNODISPLAY \
-dSAFER \
-dDELAYBIND \
-dWRITESYSTEMDICT \
-dSIMPLE \
-f ps2ascii.ps \
"${input}" \
-dQUIET \
-c quit
I used dSIMPLE
instead of dCOMPLEX
because the latter outputs 1 character per line.
The easiest is to use HTML5 API, namely FileReader
HTML is pretty straightforward:
<input type="file" id="file" name="file"/>
<button ng-click="add()">Add</button>
In your controller define 'add' method:
$scope.add = function() {
var f = document.getElementById('file').files[0],
r = new FileReader();
r.onloadend = function(e) {
var data = e.target.result;
//send your binary data via $http or $resource or do anything else with it
}
r.readAsBinaryString(f);
}
Browser Compatibility
Desktop Browsers
Edge 12, Firefox(Gecko) 3.6(1.9.2), Chrome 7, Opera* 12.02, Safari 6.0.2
Mobile Browsers
Firefox(Gecko) 32, Chrome 3, Opera* 11.5, Safari 6.1
Note : readAsBinaryString() method is deprecated and readAsArrayBuffer() should be used instead.
Also remember that all info()
, error()
, and debug()
logging calls provide internal documentation within any application.
It's because you're missing position:relative;
on #contentframe
<div id="contentframe" style="position:relative; top: 160px; left: 0px;">
position:absolute;
positions itself against the closest ancestor that has a position
that is not static
. Since the default is static
that is what was causing your issue.
I got an error message when following the examples with a newline parameter in the csv.writer function. The following code worked for me.
with open(strFileName, "w") as f:
writer = csv.writer(f, delimiter=',', quoting=csv.QUOTE_MINIMAL)
writer.writerows(result)
This solution add the deselection of the text after the copy to the clipboard:
function copyDivToClipboard(elem) {
var range = document.createRange();
range.selectNode(document.getElementById(elem));
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
document.execCommand("copy");
window.getSelection().removeAllRanges();
}
you cannot update ,but i wrote a batch file that removes my plugins and install again so in this case my all plugins are updated automatically, hope this solves your problem
@echo off
for %%a in (
"com.ionic.keyboard"
"com.phonegap.plugins.PushPlugin"
"cordova-instagram-plugin"
"cordova-plugin-camera"
"cordova-plugin-crosswalk-webview"
"cordova-plugin-file"
"cordova-plugin-file-transfer"
) do call cordova plugin rm %%a
for %%b in (
"com.ionic.keyboard"
"com.phonegap.plugins.PushPlugin"
"cordova-instagram-plugin"
"cordova-plugin-camera"
"cordova-plugin-crosswalk-webview"
"cordova-plugin-file"
"cordova-plugin-file-transfer"
) do call cordova plugin add %%b
If your table t1 and it's backup t2 have many columns, here's a compact way to do it.
In addition, my related problem was that only some of the columns were modified and many rows had no edits to these columns, so I wanted to leave those alone - basically restore a subset of columns from a backup of the entire table. If you want to just restore all rows, skip the where clause.
Of course the simpler way would be to delete and insert as select, but in my case I needed a solution with just updates.
The trick is that when you do select * from a pair of tables with duplicate column names, the 2nd one will get named _1. So here's what I came up with:
update (
select * from t1 join t2 on t2.id = t1.id
where id in (
select id from (
select id, col1, col2, ... from t2
minus select id, col1, col2, ... from t1
)
)
) set col1=col1_1, col2=col2_1, ...
This seems like the best choice to me:
val1, val2, ignored1, ignored2 = some_function()
It's not cryptic or ugly (like the func()[index] method), and clearly states your purpose.
A little bit off topic but useful is the pythonic numpy
approach. Its robust and fast but just does compare pixels and not the objects or data the picture contains (and it requires images of same size and shape):
A very simple and fast approach to do this without openCV and any library for computer vision is to norm the picture arrays by
import numpy as np
picture1 = np.random.rand(100,100)
picture2 = np.random.rand(100,100)
picture1_norm = picture1/np.sqrt(np.sum(picture1**2))
picture2_norm = picture2/np.sqrt(np.sum(picture2**2))
After defining both normed pictures (or matrices) you can just sum over the multiplication of the pictures you like to compare:
1) If you compare similar pictures the sum will return 1:
In[1]: np.sum(picture1_norm**2)
Out[1]: 1.0
2) If they aren't similar, you'll get a value between 0 and 1 (a percentage if you multiply by 100):
In[2]: np.sum(picture2_norm*picture1_norm)
Out[2]: 0.75389941124629822
Please notice that if you have colored pictures you have to do this in all 3 dimensions or just compare a greyscaled version. I often have to compare huge amounts of pictures with arbitrary content and that's a really fast way to do so.
there are many ways. as awk
solutions shows, it's the clean solution
sed solution is to delete anything till the last space. So if there is no space at the end, it should work
sed 's/.* //g' <file>
you can avoid sed
also and go for a while
loop.
while read line
do [ -z "$line" ] && continue ;
echo $line|rev|cut -f1 -d' '|rev
done < file
it reads a line, reveres it, cuts the first (i.e. last in the original) and restores back
the same can be done in a pure bash way
while read line
do [ -z "$line" ] && continue ;
echo ${line##* }
done < file
it is called parameter expansion
If you're like me and you don't like the idea of deleting things that were part of the standard system installation (which others have suggested) then you might like the solution I ended up using:
.profile
, or whatever is appropriate, and put /usr/local/bin
at the start
of your PATH
so that Homebrew binaries are found before system binariesbrew install python
- this installs a newer version of python in /usr/local
pip install pandas
This worked for me in OS X 10.8.2, and I can't see any reason it shouldn't work in 10.6.8.
I found this answer ( Prevent Highlight of Text Table ) most helpful, and perhaps it can be combined with another way of providing IE compatibility.
#yourTable
{
-moz-user-select: none;
-khtml-user-select: none;
-webkit-user-select: none;
user-select: none;
}
First to install your app:
adb install -r path\ProjectName.apk
The great thing about the -r is it works even if it wasn’t already installed.
To launch MainActivity, so you can launch it like:
adb shell am start -n com.other.ProjectName/.MainActivity
If you've got V3, you can take advantage of auto-enumeration, the -Raw switch in Get-Content, and some of the new line contiunation syntax to simply it to this, using the string .replace() method instead of the -replace operator:
(Get-ChildItem "[FILEPATH]" -recurse).FullName |
Foreach-Object {
(Get-Content $_ -Raw).
Replace('abt7d9epp4','w2svuzf54f').
Replace('AccountName=adtestnego','AccountName=zadtestnego').
Replace('AccountKey=eKkij32jGEIYIEqAR5RjkKgf4OTiMO6SAyF68HsR/Zd/KXoKvSdjlUiiWyVV2+OUFOrVsd7jrzhldJPmfBBpQA==','AccountKey=DdOegAhDmLdsou6Ms6nPtP37bdw6EcXucuT47lf9kfClA6PjGTe3CfN+WVBJNWzqcQpWtZf10tgFhKrnN48lXA==') |
Set-Content $_
}
Using the .replace() method uses literal strings for the replaced text argument (not regex), so you don't need to worry about escaping regex metacharacters in the text-to-replace argument.
public static class StringExtensions
{
public static bool Contains(this string s, params string[] predicates)
{
return predicates.All(s.Contains);
}
}
string d = "You hit someone for 50 damage";
string a = "damage";
string b = "someone";
string c = "you";
if (d.Contains(a, b))
{
Console.WriteLine("d contains a and b");
}
Servers tab
--> doubleclick servername
--> Server Options: tick "Publish module contexts to separate XML files"
restart your server
I had same problem. it happen because javascript
expect json
data type in returning data. but if you use echo or print in your php this situation occur. if you use echo
function in php
to return data, Simply remove dataType : "json"
working pretty well.
I updated "max_allowed_packet" to 1024M, but it still wasn't working. It turns out my deployment script was running:
mysql --max_allowed_packet=512M --database=mydb -u root < .\db\db.sql
Be sure to explicitly specify a bigger number from the command line if you are donig it this way.
getline(fin, buffer, '\n')
where fin
is opened file(ifstream object) and buffer
is of string/char
type where you want to copy line.
2019's answer as this is still actively seen today
You should likely change the .container to .container-fluid, which will cause your container to stretch the entire screen. This will allow any div's inside of it to naturally stretch as wide as they need.
original hack from 2015 that still works in some situations
You should pull that div outside of the container. You're asking a div to stretch wider than its parent, which is generally not recommended practice.
If you cannot pull it out of the div for some reason, you should change the position style with this css:
.full-width-div {
position: absolute;
width: 100%;
left: 0;
}
Instead of absolute, you could also use fixed, but then it will not move as you scroll.
Even i face similar problem after I did some modification in code related to Cursor.
public boolean onContextItemSelected(MenuItem item)
{
AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
Cursor c = (Cursor)adapter.getItem(info.position);
long id = c.getLong(...);
String tempCity = c.getString(...);
//c.close();
...
}
After i commented out //c.close(); It is working fine. Try out at your end and update Initial setup is as... I have a list view in Fragment, and trying to delete and item from list via contextMenu.
IndexError: invalid index to scalar variable
happens when you try to index a numpy
scalar such as numpy.int64
or numpy.float64
. It is very similar to TypeError: 'int' object has no attribute '__getitem__'
when you try to index an int
.
>>> a = np.int64(5)
>>> type(a)
<type 'numpy.int64'>
>>> a[3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: invalid index to scalar variable.
>>> a = 5
>>> type(a)
<type 'int'>
>>> a[3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object has no attribute '__getitem__'
You'd have to define alphanumerics exactly, but
/^(\w{3,5})$/
Should match any digit/character/_ combination of length 3-5.
If you also need the dash, make sure to escape it ( add it, like this: :\-
)
/^([\w\-]{3,5})$/
Also: the ^
anchor means that the sequence has to start at the beginning of the line (character string), and the $
that it ends at the end of the line (character string). So your value
string mustn't contain anything else, or it won't match.
You just need to transfer the first value to float, before it gets involved in further computations:
float z = x * 1.0 / y;
You're looking for the FromBase64Transform
class, used with the CryptoStream
class.
If you have a string, you can also call Convert.FromBase64String
.
Using the browser's parser is the probably the best bet in current browsers. The following will work, with the following caveats:
<div>
element. HTML contained within <body>
or <html>
or <head>
tags is not valid within a <div>
and may therefore not be parsed correctly.textContent
(the DOM standard property) and innerText
(non-standard) properties are not identical. For example, textContent
will include text within a <script>
element while innerText
will not (in most browsers). This only affects IE <=8, which is the only major browser not to support textContent
.<script>
elements.null
<img onerror='alert(\"could run arbitrary JS here\")' src=bogus>
Code:
var html = "<p>Some HTML</p>";
var div = document.createElement("div");
div.innerHTML = html;
var text = div.textContent || div.innerText || "";
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<---------Content Here --------------->
</LinearLayout>
</ScrollView>
</LinearLayout>
Yes, it is possible both in Sublime Text 2 and 3 (which you should really upgrade to if you haven't already). Select View ? Ruler ? 80
(there are several other options there as well). If you like to actually wrap your text at 80 columns, select View ? Word Wrap Column ? 80
. Make sure that View ? Word Wrap
is selected.
To make your selections permanent (the default for all opened files or views), open Preferences ? Settings—User
and use any of the following rules:
{
// set vertical rulers in specified columns.
// Use "rulers": [80] for just one ruler
// default value is []
"rulers": [80, 100, 120],
// turn on word wrap for source and text
// default value is "auto", which means off for source and on for text
"word_wrap": true,
// set word wrapping at this column
// default value is 0, meaning wrapping occurs at window width
"wrap_width": 80
}
These settings can also be used in a .sublime-project
file to set defaults on a per-project basis, or in a syntax-specific .sublime-settings
file if you only want them to apply to files written in a certain language (Python.sublime-settings
vs. JavaScript.sublime-settings
, for example). Access these settings files by opening a file with the desired syntax, then selecting Preferences ? Settings—More ? Syntax Specific—User
.
As always, if you have multiple entries in your settings file, separate them with commas ,
except for after the last one. The entire content should be enclosed in curly braces { }
. Basically, make sure it's valid JSON.
If you'd like a key combo to automatically set the ruler at 80 for a particular view/file, or you are interested in learning how to set the value without using the mouse, please see my answer here.
Finally, as mentioned in another answer, you really should be using a monospace font in order for your code to line up correctly. Other types of fonts have variable-width letters, which means one 80-character line may not appear to be the same length as another 80-character line with different content, and your indentations will look all messed up. Sublime has monospace fonts set by default, but you can of course choose any one you want. Personally, I really like Liberation Mono. It has glyphs to support many different languages and Unicode characters, looks good at a variety of different sizes, and (most importantly for a programming font) clearly differentiates between 0
and O
(digit zero and capital letter oh) and 1
and l
(digit one and lowercase letter ell), which not all monospace fonts do, unfortunately. Version 2.0 and later of the font are licensed under the open-source SIL Open Font License 1.1 (here is the FAQ).
Considering a check for retina display use the following code snippet:
#import <QuartzCore/QuartzCore.h>
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
UIGraphicsBeginImageContextWithOptions(self.window.bounds.size, NO, [UIScreen mainScreen].scale);
} else {
UIGraphicsBeginImageContext(self.window.bounds.size);
}
[self.window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imageData = UIImagePNGRepresentation(image);
if (imageData) {
[imageData writeToFile:@"screenshot.png" atomically:YES];
} else {
NSLog(@"error while taking screenshot");
}
If we don't provide any scope then the default scope is compile, If you want to confirm, simply go to Effective pom tab in eclipse editor, it will show you as compile.
use cut
$ cut -f4-13 file
or if you insist on awk and $13 is the last field
$ awk '{$1=$2=$3="";print}' file
else
$ awk '{for(i=4;i<=13;i++)printf "%s ",$i;printf "\n"}' file
I simplified your code to isolate the test for "%" being in the cell. Once you get that to work, you can add in the rest of your code.
Try this:
Option Explicit
Sub DoIHavePercentSymbol()
Dim rng As Range
Set rng = ActiveCell
Do While rng.Value <> Empty
If InStr(rng.Value, "%") = 0 Then
MsgBox "I know nothing about percentages!"
Set rng = rng.Offset(1)
rng.Select
Else
MsgBox "I contain a % symbol!"
Set rng = rng.Offset(1)
rng.Select
End If
Loop
End Sub
InStr
will return the number of times your search text appears in the string. I changed your if
test to check for no matches first.
The message boxes and the .Selects
are there simply for you to see what is happening while you are stepping through the code. Take them out once you get it working.
Even though the answer for this question has been selected already, however, I believe the simplest query will be
SELECT *
FROM table
WHERE
date_created BETWEEN (CURRENT_DATE() - INTERVAL 1 MONTH) AND CURRENT_DATE();
Check your home folder ~/.gradle/gradle.properties
. Sometimes if you have gradle.properties
in home directory it takes details from the there. Either you can change that or delete the files. Then it will take required details from your local folder.
We also had this problem. My colleague found a solution. It turned up to be a redefinition of "main" in a third party library header:
#define main SDL_main
So the solution was to add:
#undef main
before our main function.
This is clearly a stupidity!
In the way that you're doing things, it won't happen. You're changing the background image of the image, which is being blocked by the original image. Changing the height and width also won't happen. To change the src attribute of the image, you would need Javascript or a Javascript Library such as jQuery. You could however, change the image to a simple div (text) box, and have a background image that changes on hover, even though the div box itself will be empty. Here's how.
<div id="emptydiv"></div>
#emptydiv {
background-image: url("LibraryHover.png");
height: 70px;
width: 120px;
}
#emptydiv:hover {
background-image: url("LibraryHoverTrans.png");
height: 700px;
width: 1200px;
}
I hope this is what you're asking for :)
make sure settings.py has
USE_TZ = True
In your python file:
from django.utils import timezone
timezone.now() # use its value in model field
I encountered an issue like this using the Maven Release Plugin. Resolving using relative paths (i.e. for the parent pom in the child module ../parent/pom.xml) did not seem to work in this scenario, it keeps looking for the released parent pom in the Nexus repository. Moving the parent pom to the parent folder of the module resolved this.
Depends on the RDBMS or even the JDBC driver.
Most of the times you can use java.sql.Timestamp most of the times along with a prepared statement:
pstmt.setTimestamp( index, new Timestamp( yourJavaUtilDateInstance.getTime() );
Android N (Api level 24) update (no warnings):
Locale getCurrentLocale(Context context){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
return context.getResources().getConfiguration().getLocales().get(0);
} else{
//noinspection deprecation
return context.getResources().getConfiguration().locale;
}
}
Windows users should read Troubleshooting > Upgrading on Windows in the npm wiki.
The link above Troubleshooting#upgrading-on-windows points to a github page npm-windows-upgrade the lines below are quotes from the readme. I successfully upgraded from npm 2.7.4 to npm 3.9.3 using node v5.7.0 and powershell (presumably powershell version 5.0.10586.122)
First, ensure that you can execute scripts on your system by running the following command from an elevated PowerShell. To run PowerShell as Administrator, click Start, search for PowerShell, right-click PowerShell and select Run as Administrator.
Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force
Then, to install and use this upgrader tool, run (also from an elevated PowerShell or cmd.exe):
npm install --global --production npm-windows-upgrade
npm-windows-upgrade
For the Platform Independent Users or Windows users, what you can do is:
import runtime:
import (
"runtime"
"strings"
)
and then trim the string like this:
if runtime.GOOS == "windows" {
input = strings.TrimRight(input, "\r\n")
} else {
input = strings.TrimRight(input, "\n")
}
now you can compare it like that:
if strings.Compare(input, "a") == 0 {
//....yourCode
}
This is a better approach when you're making use of STDIN on multiple platforms.
This happens because on windows lines end with "\r\n"
which is known as CRLF, but on UNIX lines end with "\n"
which is known as LF and that's why we trim "\n"
on unix based operating systems while we trim "\r\n"
on windows.
It's easy to calculate insets dynamically, this code will always center your cells:
NSInteger const SMEPGiPadViewControllerCellWidth = 332;
...
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
NSInteger numberOfCells = self.view.frame.size.width / SMEPGiPadViewControllerCellWidth;
NSInteger edgeInsets = (self.view.frame.size.width - (numberOfCells * SMEPGiPadViewControllerCellWidth)) / (numberOfCells + 1);
return UIEdgeInsetsMake(0, edgeInsets, 0, edgeInsets);
}
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
[super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
[self.collectionView.collectionViewLayout invalidateLayout];
}
I've used bc
(binary calculator), asking them for PI with a big lot of decimals.
$ for ((i=0;i<$NUMCPU;i++));do
echo 'scale=100000;pi=4*a(1);0' | bc -l &
done ;\
sleep 4; \
killall bc
with NUMCPU (under Linux):
$ NUMCPU=$(grep $'^processor\t*:' /proc/cpuinfo |wc -l)
This method is strong but seem system friendly, as I've never crashed a system using this.
It is better to avoid using mod_rewrite when you can.
In your case I would replace the Rewrite with this:
<If "%{HTTPS} == 'on'" >
Redirect permanent / http://production_server/
</If>
The <If>
directive is only available in Apache 2.4+ as per this blog here.
I faced the same situation a couple of days ago, and my solution was to define a function in the module to test and just mock that:
def get_date_now():
return datetime.datetime.now()
Today I found out about FreezeGun, and it seems to cover this case beautifully
from freezegun import freeze_time
import datetime
import unittest
@freeze_time("2012-01-14")
def test():
assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)
One like with events
(keydown)="$event.keyCode != 32 ? $event:$event.preventDefault()"
OpCache is compiled by default on PHP5.5+. However it is disabled by default. In order to start using OpCache in PHP5.5+ you will first have to enable it. To do this you would have to do the following.
Add the following line to your php.ini
:
zend_extension=/full/path/to/opcache.so (nix)
zend_extension=C:\path\to\php_opcache.dll (win)
Note that when the path contains spaces you should wrap it in quotes:
zend_extension="C:\Program Files\PHP5.5\ext\php_opcache.dll"
Also note that you will have to use the zend_extension
directive instead of the "normal" extension
directive because it affects the actual Zend engine (i.e. the thing that runs PHP).
Currently there are four functions which you can use:
opcache_get_configuration()
:Returns an array containing the currently used configuration OpCache uses. This includes all ini settings as well as version information and blacklisted files.
var_dump(opcache_get_configuration());
opcache_get_status()
:This will return an array with information about the current status of the cache. This information will include things like: the state the cache is in (enabled, restarting, full etc), the memory usage, hits, misses and some more useful information. It will also contain the cached scripts.
var_dump(opcache_get_status());
opcache_reset()
:Resets the entire cache. Meaning all possible cached scripts will be parsed again on the next visit.
opcache_reset();
opcache_invalidate()
:Invalidates a specific cached script. Meaning the script will be parsed again on the next visit.
opcache_invalidate('/path/to/script/to/invalidate.php', true);
There are some GUI's created to help maintain OpCache and generate useful reports. These tools leverage the above functions.
OpCacheGUI
Disclaimer I am the author of this project
Features:
Screenshots:
URL: https://github.com/PeeHaa/OpCacheGUI
opcache-status
Features:
Screenshot:
URL: https://github.com/rlerdorf/opcache-status
opcache-gui
Features:
Screenshot:
I'm still going suggest the 2 map solution, but with a tweest
Map<K2, K1> m2;
Map<K1, V> m1;
This scheme lets you have an arbitrary number of key "aliases".
It also lets you update the value through any key without the maps getting out of sync.
This problem occures when you use your service via other application.If application has config file just add your service config information to this file. In my situation there wasn't any config file so I use this technique and it worked fine.Just store url address in application,read it and using BasicHttpBinding() method send it to service application as parameter.This is simple demonstration how I did it:
Configuration config = new Configuration(dataRowSet[0]["ServiceUrl"].ToString());
var remoteAddress = new System.ServiceModel.EndpointAddress(config.Url);
SimpleService.PayPointSoapClient client =
new SimpleService.PayPointSoapClient(new System.ServiceModel.BasicHttpBinding(),
remoteAddress);
SimpleService.AccountcredResponse response = client.AccountCred(request);
The answer shared by @mockinterface is correct. Although I would like to add my 2 cents to it.
If someone is using frameworks like scrapy
the you will have to use /html/body//a[contains(@href,'com')][2]/@href
along with get() like this:
response.xpath('//a[contains(@href,'com')][2]/@href').get()
You have to compile with Java 1.7. But if you have *.jsp files, you should also completely remove Java 1.8 from the system. If you use Mac, here is how you can do it.
I would suggest using TRUNCATE TABLE, it's quicker and uses less resources than DELETE FROM xxx
Here's the related MSDN article
Use a BigDecimal. It even lets you specify rounding rules (like ROUND_HALF_EVEN, which will minimize statistical error by rounding to the even neighbor if both are the same distance; i.e. both 1.5 and 2.5 round to 2).
Check if have not set a open_basedir in php.ini or .htaccess of domain what you use. That will jail you in directory of your domain and php will get only access to execute inside this directory.
When you're doing this
var model = @Html.Raw(Json.Encode(Model));
You're probably getting a JSON string, and not a JavaScript object.
You need to parse it in to an object:
var model = JSON.parse(model); //or $.parseJSON() since if jQuery is included
console.log(model.Sections);
There's also Powershell (which is part of Windows). It ain't quick but it's flexible, here's the basic command. People have written various cmdlets and scripts for it if you need better formatting.
PS C:\Users\Troll> Compare-Object (gc $file1) (gc $file2)
Not part of Windows, but if you are a developer with Visual Studio, it comes with WinDiff (graphical)
But my personal favorite is BeyondCompare, which costs $30.
I checked a few similar discussions and found out the best way to locate all python2/python3 builds is:
which -a python python3
You need echo -e for the newline characters to take affect
you wrote
echo "oldpassword\nnewpasswd123\nnewpasswd123" | passwd user
you should try
echo -e "oldpassword\nnewpasswd123\nnewpasswd123" | passwd user
more than likely, you will not need the oldpassword\n portion of that command, you should just need the two new passwords. Don't forget to use single quotes around exclamation points!
echo -e "new"'!'"passwd123\nnew"'!'"passwd123" | passwd user
I had the same issue and was not satisfied with any of the answers so far since none of them guaranteed unique IDs.
I too wanted to print object IDs for debugging purposed. I knew there must be some way to do it, because in the Eclipse debugger, it specifies unique IDs for each object.
I came up with a solution based on the fact that the "==" operator for objects only returns true if the two objects are actually the same instance.
import java.util.HashMap;
import java.util.Map;
/**
* Utility for assigning a unique ID to objects and fetching objects given
* a specified ID
*/
public class ObjectIDBank {
/**Singleton instance*/
private static ObjectIDBank instance;
/**Counting value to ensure unique incrementing IDs*/
private long nextId = 1;
/** Map from ObjectEntry to the objects corresponding ID*/
private Map<ObjectEntry, Long> ids = new HashMap<ObjectEntry, Long>();
/** Map from assigned IDs to their corresponding objects */
private Map<Long, Object> objects = new HashMap<Long, Object>();
/**Private constructor to ensure it is only instantiated by the singleton pattern*/
private ObjectIDBank(){}
/**Fetches the singleton instance of ObjectIDBank */
public static ObjectIDBank instance() {
if(instance == null)
instance = new ObjectIDBank();
return instance;
}
/** Fetches a unique ID for the specified object. If this method is called multiple
* times with the same object, it is guaranteed to return the same value. It is also guaranteed
* to never return the same value for different object instances (until we run out of IDs that can
* be represented by a long of course)
* @param obj The object instance for which we want to fetch an ID
* @return Non zero unique ID or 0 if obj == null
*/
public long getId(Object obj) {
if(obj == null)
return 0;
ObjectEntry objEntry = new ObjectEntry(obj);
if(!ids.containsKey(objEntry)) {
ids.put(objEntry, nextId);
objects.put(nextId++, obj);
}
return ids.get(objEntry);
}
/**
* Fetches the object that has been assigned the specified ID, or null if no object is
* assigned the given id
* @param id Id of the object
* @return The corresponding object or null
*/
public Object getObject(long id) {
return objects.get(id);
}
/**
* Wrapper around an Object used as the key for the ids map. The wrapper is needed to
* ensure that the equals method only returns true if the two objects are the same instance
* and to ensure that the hash code is always the same for the same instance.
*/
private class ObjectEntry {
private Object obj;
/** Instantiates an ObjectEntry wrapper around the specified object*/
public ObjectEntry(Object obj) {
this.obj = obj;
}
/** Returns true if and only if the objects contained in this wrapper and the other
* wrapper are the exact same object (same instance, not just equivalent)*/
@Override
public boolean equals(Object other) {
return obj == ((ObjectEntry)other).obj;
}
/**
* Returns the contained object's identityHashCode. Note that identityHashCode values
* are not guaranteed to be unique from object to object, but the hash code is guaranteed to
* not change over time for a given instance of an Object.
*/
@Override
public int hashCode() {
return System.identityHashCode(obj);
}
}
}
I believe that this should ensure unique IDs throughout the lifetime of the program. Note, however, that you probably don't want to use this in a production application because it maintains references to all of the objects for which you generate IDs. This means that any objects for which you create an ID will never be garbage collected.
Since I'm using this for debug purposes, I'm not too concerned with the memory being freed.
You could modify this to allow clearing Objects or removing individual objects if freeing memory is a concern.
Make sure to download these from here:
Also create PATH
enviroment variable on you computer like this (if it doesn't exist already):
PATH
variable doesn't exist among "User variables" click New
(Variable name: PATH, Variable value : C:\Program Files\Java\jdk1.8.0\bin;
<-- please check out the right version, this may differ as Oracle keeps updating Java). ;
in the end enables assignment of multiple values to PATH
variable.To be sure that everything works, open CMD Prompt and type: java -version
to check for Java version and javac
to be sure that compiler responds.
I hope this helps. Good luck!
You get this error because one of your variables is actually a factor variable . Execute
str(df)
to check this. Then do this double variable change to keep the year numbers instead of transforming into "1,2,3,4" level numbers:
df$year <- as.numeric(as.character(df$year))
EDIT: it appears that your data.frame has a variable of class "array" which might cause the pb. Try then:
df <- data.frame(apply(df, 2, unclass))
and plot again?
Just an addendum to the answers here.
You can also do a local case insensitive test using:
- (BOOL)localizedCaseInsensitiveContainsString:(NSString *)aString
Example:
import Foundation
var string: NSString = "hello Swift"
if string.localizedCaseInsensitiveContainsString("Hello") {
println("TRUE")
}
UPDATE
This is part of the Foundation Framework for iOS & Mac OS X 10.10.x and was part of 10.10 at Time of my original Posting.
Document Generated: 2014-06-05 12:26:27 -0700 OS X Release Notes Copyright © 2014 Apple Inc. All Rights Reserved.
OS X 10.10 Release Notes Cocoa Foundation Framework
NSString now has the following two convenience methods:
- (BOOL)containsString:(NSString *)str;
- (BOOL)localizedCaseInsensitiveContainsString:(NSString *)str;
This error can also appear if your git branch is not correct even though case sensitive wise. In my case I was getting this error as actual branch name was "CORE-something" but I was taking pull like "core-something".
open the sql file on Notepad++ and ctrl + H.
Then you put "utf8mb4
" on search and "utf8
" on replace.
The issue will be fixed then.
An empty border is transparent. You need to specify a Line Border or some other visible border when you set the border in order to see it.
Based on Edit to question:
The painting does not honor the border. Add this line of code to your test and you will see the border:
jboard.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
jboard.add(new JButton("Test")); //Add this line
frame.add(jboard);
What I do is something just a little bit different from @Chase answer:
var employees = {};
// ...and then:
employees.accounting = new Array();
for (var i = 0; i < someArray.length; i++) {
var temp_item = someArray[i];
// Maybe, here make something like:
// temp_item.name = 'some value'
employees.accounting.push({
"firstName" : temp_item.firstName,
"lastName" : temp_item.lastName,
"age" : temp_item.age
});
}
And that work form me!
I hope it could be useful for some body else!
Adding to Jim's elaborate answer:
Check the typing
module -- this module supports type hints as specified by PEP 484.
For example, the function below takes and returns values of type str
and is annotated as follows:
def greeting(name: str) -> str:
return 'Hello ' + name
The typing
module also supports:
Try this:
$('#click_advance').click(function(){
$('#display_advance').toggle('1000');
icon = $(this).find("i");
icon.hasClass("icon-circle-arrow-down"){
icon.addClass("icon-circle-arrow-up").removeClass("icon-circle-arrow-down");
}else{
icon.addClass("icon-circle-arrow-down").removeClass("icon-circle-arrow-up");
}
})
or even better, as Kevin said:
$('#click_advance').click(function(){
$('#display_advance').toggle('1000');
icon = $(this).find("i");
icon.toggleClass("icon-circle-arrow-up icon-circle-arrow-down")
})
iOS 8 (swift)
let font: UIFont = UIFont(name: "fontName", size: 17)
let color = UIColor.backColor()
self.navigationController?.navigationBar.topItem?.backBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: font,NSForegroundColorAttributeName: color], forState: .Normal)
I like Daniel Cerecedo's answer using toJSON()
and regex. An even simpler form would be:
var now = new Date();
var regex = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).*$/;
var token_array = regex.exec(now.toJSON());
// [ "2017-10-31T02:24:45.868Z", "2017", "10", "31", "02", "24", "45" ]
var myFormat = token_array.slice(1).join('');
// "20171031022445"
None of these worked for me. I'm on a mac using Microsoft 360. I found this which DID work: This workaround is for Excel 2010 and 2007, it is best for a small number of chart data points.
Click twice on a label to select it. Click in formula bar. Type = Use your mouse to click on a cell that contains the value you want to use. The formula bar changes to perhaps =Sheet1!$D$3
Repeat step 1 to 5 with remaining data labels.
Simple
Here is a long (easy to understand) version but takes care of leap years.
cheers, JK
def last_day_month(year, month):
leap_year_flag = 0
end_dates = {
1: 31,
2: 28,
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31
}
# Checking for regular leap year
if year % 4 == 0:
leap_year_flag = 1
else:
leap_year_flag = 0
# Checking for century leap year
if year % 100 == 0:
if year % 400 == 0:
leap_year_flag = 1
else:
leap_year_flag = 0
else:
pass
# return end date of the year-month
if leap_year_flag == 1 and month == 2:
return 29
elif leap_year_flag == 1 and month != 2:
return end_dates[month]
else:
return end_dates[month]
For example if you want to repeat a word called "HELP" for 1000 times the following is the best way.
word = ['HELP']
repeat = 1000 * word
Then you will get the list of 1000 words and make that into a data frame if you want by using following command
word_data =pd.DataFrame(repeat)
word_data.columns = ['list_of_words'] #To change the column name
And for now, here is https://github.com/google/go-cmp which
is intended to be a more powerful and safer alternative to
reflect.DeepEqual
for comparing whether two values are semantically equal.
package main
import (
"fmt"
"github.com/google/go-cmp/cmp"
)
func main() {
a := []byte{1, 2, 3}
b := []byte{1, 2, 3}
fmt.Println(cmp.Equal(a, b)) // true
}
When you are using a self signed cert urllib3 version 1.25.3 refuses to ignore the SSL cert
To fix remove urllib3-1.25.3 and install urllib3-1.24.3
pip3 uninstall urllib3
pip3 install urllib3==1.24.3
Tested on Linux MacOS and Window$
If you want to get content of given directory, and only it (i.e. no subdirectories), the best way is to use opendir/readdir/closedir:
opendir my $dir, "/some/path" or die "Cannot open directory: $!";
my @files = readdir $dir;
closedir $dir;
You can also use:
my @files = glob( $dir . '/*' );
But in my opinion it is not as good - mostly because glob is quite complex thing (can filter results automatically) and using it to get all elements of directory seems as a too simple task.
On the other hand, if you need to get content from all of the directories and subdirectories, there is basically one standard solution:
use File::Find;
my @content;
find( \&wanted, '/some/path');
do_something_with( @content );
exit;
sub wanted {
push @content, $File::Find::name;
return;
}
Yet another answer, derived from @chsh. MD5 with usings and shortcuts for file same, file not exists and differing lengths:
/// <summary>
/// Performs an md5 on the content of both files and returns true if
/// they match
/// </summary>
/// <param name="file1">first file</param>
/// <param name="file2">second file</param>
/// <returns>true if the contents of the two files is the same, false otherwise</returns>
public static bool IsSameContent(string file1, string file2)
{
if (file1 == file2)
return true;
FileInfo file1Info = new FileInfo(file1);
FileInfo file2Info = new FileInfo(file2);
if (!file1Info.Exists && !file2Info.Exists)
return true;
if (!file1Info.Exists && file2Info.Exists)
return false;
if (file1Info.Exists && !file2Info.Exists)
return false;
if (file1Info.Length != file2Info.Length)
return false;
using (FileStream file1Stream = file1Info.OpenRead())
using (FileStream file2Stream = file2Info.OpenRead())
{
byte[] firstHash = MD5.Create().ComputeHash(file1Stream);
byte[] secondHash = MD5.Create().ComputeHash(file2Stream);
for (int i = 0; i < firstHash.Length; i++)
{
if (i>=secondHash.Length||firstHash[i] != secondHash[i])
return false;
}
return true;
}
}
It's easy to do multiline replace in Notepad++. You have to use \n
to represent the newline in your string, and it works for both search and replace strings. You have to make sure to select "Extended" search mode in the bottom left corner of the search window.
I found a good article describing the features here: http://markantoniou.blogspot.com/2008/06/notepad-how-to-use-regular-expressions.html
For generic use (run python/haskell/ruby/C++... from vim based on the filetype
), there's a nice plugin called vim-quickrun. It supports many programming languages by default. It is easily configurable, too, so one can define preferred behaviours for any filetype if needed. The github repo does not have a fancy readme, but it is well documented with the doc file.
To fully overload it you also need to implement the __setitem__
and __delitem__
methods.
edit
I almost forgot... if you want to completely emulate a list, you also need __getslice__, __setslice__ and __delslice__
.
There are all documented in http://docs.python.org/reference/datamodel.html
One more possible reason if you are using Tycho and Maven to build bundles, that you have wrong execution environment (Bundle-RequiredExecutionEnvironment
) in the manifest file (manifest.mf
) defined. For example:
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Engine Plug-in
Bundle-SymbolicName: com.foo.bar
Bundle-Version: 4.6.5.qualifier
Bundle-Activator: com.foo.bar.Activator
Bundle-Vendor: Foobar Technologies Ltd.
Require-Bundle: org.eclipse.core.runtime,
org.jdom;bundle-version="1.0.0",
org.apache.commons.codec;bundle-version="1.3.0",
bcprov-ext;bundle-version="1.47.0"
Bundle-RequiredExecutionEnvironment: JavaSE-1.5
Export-Package: ...
...
Import-Package: ...
...
In my case everything else was ok. The compiler plugins (normal maven and tycho as well) were set correctly, still m2 generated old compliance level because of the manifest. I thought I share the experience.
Simple:
[DataType(DataType.Date)]
Public DateTime Ldate {get;set;}
Assuming a Css class of "image" :
input.image {
background: url(/i/bg.png) no-repeat top left;
width: /* img-width */;
height: /* img-height */
}
If you don't know what the image width and height are, you can set this dynamically with javascript.
All these answers are nice.
But I cannot be sure that variable is a string, doesn't contain only spaces (this is important for me), and can contain '0' (string).
My version:
function empty(str){
return !str || !/[^\s]+/.test(str);
}
empty(null); // true
empty(0); // true
empty(7); // false
empty(""); // true
empty("0"); // false
empty(" "); // true
Sample on jsfiddle.
Below code will help you:
public class DeckListAdapter extends BaseAdapter{
private LayoutInflater mInflater;
ArrayList<String> teams=new ArrayList<String>();
ArrayList<Integer> teamcolor=new ArrayList<Integer>();
public DeckListAdapter(Context context) {
// Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context);
teams.add("Upload");
teams.add("Download");
teams.add("Device Browser");
teams.add("FTP Browser");
teams.add("Options");
teamcolor.add(Color.WHITE);
teamcolor.add(Color.LTGRAY);
teamcolor.add(Color.WHITE);
teamcolor.add(Color.LTGRAY);
teamcolor.add(Color.WHITE);
}
public int getCount() {
return teams.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.decklist, null);
holder = new ViewHolder();
holder.icon = (ImageView) convertView.findViewById(R.id.deckarrow);
holder.text = (TextView) convertView.findViewById(R.id.textname);
.......here you can use holder.text.setonclicklistner(new View.onclick.
for each textview
System.out.println(holder.text.getText().toString());
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(teams.get(position));
if(position<teamcolor.size())
holder.text.setBackgroundColor(teamcolor.get(position));
holder.icon.setImageResource(R.drawable.arraocha);
return convertView;
}
class ViewHolder {
ImageView icon;
TextView text;
}
}
Hope this helps.
Instead of using a split, I think it would be easier to simply execute a match and process all the found matches.
This expression will:
Regex: (?:^|,)(?=[^"]|(")?)"?((?(1)[^"]*|[^,"]*))"?(?=,|$)
Sample Text
123,2.99,AMO024,Title,"Description, more info",,123987564
ASP example using the non-java expression
Set regEx = New RegExp
regEx.Global = True
regEx.IgnoreCase = True
regEx.MultiLine = True
sourcestring = "your source string"
regEx.Pattern = "(?:^|,)(?=[^""]|("")?)""?((?(1)[^""]*|[^,""]*))""?(?=,|$)"
Set Matches = regEx.Execute(sourcestring)
For z = 0 to Matches.Count-1
results = results & "Matches(" & z & ") = " & chr(34) & Server.HTMLEncode(Matches(z)) & chr(34) & chr(13)
For zz = 0 to Matches(z).SubMatches.Count-1
results = results & "Matches(" & z & ").SubMatches(" & zz & ") = " & chr(34) & Server.HTMLEncode(Matches(z).SubMatches(zz)) & chr(34) & chr(13)
next
results=Left(results,Len(results)-1) & chr(13)
next
Response.Write "<pre>" & results
Matches using the non-java expression
Group 0 gets the entire substring which includes the comma
Group 1 gets the quote if it's used
Group 2 gets the value not including the comma
[0][0] = 123
[0][1] =
[0][2] = 123
[1][0] = ,2.99
[1][1] =
[1][2] = 2.99
[2][0] = ,AMO024
[2][1] =
[2][2] = AMO024
[3][0] = ,Title
[3][1] =
[3][2] = Title
[4][0] = ,"Description, more info"
[4][1] = "
[4][2] = Description, more info
[5][0] = ,
[5][1] =
[5][2] =
[6][0] = ,123987564
[6][1] =
[6][2] = 123987564
For the special case of existing Windows Forms applications:
There is a way - though I don't know how well it works.
It goes like this:
Take the Windows Forms implementation from Mono.
Port it to .NET Core or NetStandard.
Recompile your Windows Forms applications against the new System.Windows.Forms.
Fix anything that may be broken by .NET Core.
Pray that mono implements the parts you need flawlessly.
(If it doesn't, you can always stop praying, and send the Mono project a pull request with your fix/patch/feature.)
Here's my CoreFX Windows Forms repository:
https://github.com/ststeiger/System.CoreFX.Forms
Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium
This is a very simple RegEx for validating US Zipcode (not ZipCode Plus Four):
(?!([089])\1{4})\d{5}
Seems all five digit numeric are valid zipcodes except 00000
, 88888
& 99999
.
I have tested this RegEx with http://regexpal.com/
SP
git error: failed to push some refs to also comes when the local repository name does match with the corresponding remote repository name. Make sure you are working on the correct pair of repository before you Pull changes to remote repository. In case you spell incorrectly and you want to remove the local repository use following steps
Remove the local repo from windows
del /F /S /Q /A .git
rmdir .git
XXXX02
->XXXX20
) or if it is a newly created repo delete it and recreate the repo (XXXX02
Repo name changed to XXXX20
).git init
git remote add origin https://github.com/<username>/XXXX20.git
git push -u origin master
variable = id if variable.to_s.empty?
Update the apache-maven-3.5.0-bin\apache-maven-3.5.0\conf\settings.xml file.
Check your internet explorer proxy --> Setting --> Internet explorer -->Connection --> LAN Setting
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<username>user</username>
<password>****</password>
<host>proxy</host>
<port>8080</port>
</proxy>
@jason-mccreary is totally right. Besides I recommend you this code to get more info in case of malfunction:
$rest = curl_exec($crl);
if ($rest === false)
{
// throw new Exception('Curl error: ' . curl_error($crl));
print_r('Curl error: ' . curl_error($crl));
}
curl_close($crl);
print_r($rest);
EDIT 1
To debug you can set CURLOPT_HEADER
to true to check HTTP response with firebug::net or similar.
curl_setopt($crl, CURLOPT_HEADER, true);
EDIT 2
About Curl error: SSL certificate problem, verify that the CA cert is OK
try adding this headers (just to debug, in a production enviroment you should keep these options in true
):
curl_setopt($crl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($crl, CURLOPT_SSL_VERIFYPEER, false);
Create a dictionary with tuple as the key, and print the keys.
k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]
dict_tuple = {tuple(item): index for index, item in enumerate(k)}
print [list(itm) for itm in dict_tuple.keys()]
# prints [[1, 2], [5, 6, 2], [3], [4]]
Highcharts will automatically try to find the best format for the current zoom-range. This is done if the xAxis has the type 'datetime'
. Next the unit of the current zoom is calculated, it could be one of:
This unit is then used find a format for the axis labels. The default patterns are:
second: '%H:%M:%S',
minute: '%H:%M',
hour: '%H:%M',
day: '%e. %b',
week: '%e. %b',
month: '%b \'%y',
year: '%Y'
If you want the day to be part of the "hour"-level labels you should change the dateTimeLabelFormats
option for that level include %d
or %e
.
These are the available patters:
http://api.highcharts.com/highcharts#xAxis.dateTimeLabelFormats
Try this:
var var1=42;
var var2;
alert(var2 = var1); //show result of assignment expression is assigned value
alert(var2); // show assignment did occur.
Note the single '=' in the first alert. This will show that the result of an assignment expression is the assigned value, and the 2nd alert will show you that assignment did occur.
It follows logically that assignment must have chained from right to left. However, since this is all atomic to the javascript (there's no threading) a particular engine may choose to actually optimize it a little differently.
I have a mac but would assume all linux are the same for this part...
In my case I got this:
2018-12-03 11:13:27 - Start server:
2018-12-03 11:13:27 - Server start done.
2018-12-03 11:13:27 - Checking server status...
2018-12-03 11:13:27 - Trying to connect to MySQL...
2018-12-03 11:13:27 - Lost connection to MySQL server at 'reading authorization packet', system error: 0 (2013)
2018-12-03 11:13:27 - Assuming server is not running
I ran this:
sudo killall mysqld
And then started the mysql again through mysqlworkbench although in your case it might be like this:
mysql.server start
*sidenote: I tried running mysql.server stop
and got this Shutting down MySQL
.... SUCCESS!
but after running ps aux | grep mysql
I saw that it hasn't really shut down...
Just to include one more alternative, you could also use this:
find "/starting/path" -type f -regextype posix-extended -regex "^.*\.(php|html|js)$" -exec grep -EH '(document\.cookie|setcookie)' {} \;
Where:
-regextype posix-extended
tells find
what kind of regex to expect-regex "^.*\.(php|html|js)$"
tells find
the regex itself filenames must match-exec grep -EH '(document\.cookie|setcookie)' {} \;
tells find
to run the command (with its options and arguments) specified between the -exec
option and the \;
for each file it finds, where {}
represents where the file path goes in this command.
while
E
option tells grep
to use extended regex (to support the parentheses) and...H
option tells grep
to print file paths before the matches.And, given this, if you only want file paths, you may use:
find "/starting/path" -type f -regextype posix-extended -regex "^.*\.(php|html|js)$" -exec grep -EH '(document\.cookie|setcookie)' {} \; | sed -r 's/(^.*):.*$/\1/' | sort -u
Where
|
[pipe] send the output of find
to the next command after this (which is sed
, then sort
) r
option tells sed
to use extended regex.s/HI/BYE/
tells sed
to replace every First occurrence (per line) of "HI" with "BYE" and...s/(^.*):.*$/\1/
tells it to replace the regex (^.*):.*$
(meaning a group [stuff enclosed by ()
] including everything [.*
= one or more of any-character] from the beginning of the line [^
] till' the first ':' followed by anything till' the end of line [$
]) by the first group [\1
] of the replaced regex.u
tells sort to remove duplicate entries (take sort -u
as optional)....FAR from being the most elegant way. As I said, my intention is to increase the range of possibilities (and also to give more complete explanations on some tools you could use).
You can use js2py context to execute your js code and get output from document.write with mock document object:
import js2py
js = """
var output;
document = {
write: function(value){
output = value;
}
}
""" + your_script
context = js2py.EvalJs()
context.execute(js)
print(context.output)
I realize this is an old entry, but someone may find it useful. As the full domain name may not exceed a total length of 253 characters replace .* with .\{1, 255\}
You can use a lookaround:
^(?=.*[A-Za-z0-9])[A-Za-z0-9 _]*$
It will check ahead that the string has a letter or number, if it does it will check that the rest of the chars meet your requirements. This can probably be improved upon, but it seems to work with my tests.
UPDATE:
Adding modifications suggested by Chris Lutz:
^(?=.*[^\W_])[\w ]*$/
The code below is enough for "Check if a String contains numbers in Java"
Pattern p = Pattern.compile("([0-9])");
Matcher m = p.matcher("Here is ur string");
if(m.find()){
System.out.println("Hello "+m.find());
}
In your test code your are trying to pass App
to the spyOn function, but spyOn will only work with objects, not classes. Generally you need to use one of two approaches here:
1) Where the click handler calls a function passed as a prop, e.g.
class App extends Component {
myClickFunc = () => {
console.log('clickity clickcty');
this.props.someCallback();
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro" onClick={this.myClickFunc}>
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
You can now pass in a spy function as a prop to the component, and assert that it is called:
describe('my sweet test', () => {
it('clicks it', () => {
const spy = jest.fn();
const app = shallow(<App someCallback={spy} />)
const p = app.find('.App-intro')
p.simulate('click')
expect(spy).toHaveBeenCalled()
})
})
2) Where the click handler sets some state on the component, e.g.
class App extends Component {
state = {
aProperty: 'first'
}
myClickFunc = () => {
console.log('clickity clickcty');
this.setState({
aProperty: 'second'
});
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro" onClick={this.myClickFunc}>
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
You can now make assertions about the state of the component, i.e.
describe('my sweet test', () => {
it('clicks it', () => {
const app = shallow(<App />)
const p = app.find('.App-intro')
p.simulate('click')
expect(app.state('aProperty')).toEqual('second');
})
})
createdb
is a command line utility which you can run from bash and not from psql. To create a database from psql, use the create database statement like so:
create database [databasename];
Note: be sure to always end your SQL statements with ;
For Mac via homebrew:
brew tap petere/postgresql
,
brew install <formula>
(eg: brew install petere/postgresql/postgresql-9.6
)
Remove old Postgres:
brew unlink postgresql
brew link -f postgresql-9.6
If any error happen, don't forget to read and follow brew instruction in each step.
Check this out for more: https://github.com/petere/homebrew-postgresql
Make your life easier by using CSS Selectors
I know I have come late to party but I have a nice suggestion for you.
Using BeautifulSoup
is already been suggested I would rather prefer using CSS Selectors
to scrape data inside HTML
import urllib2
from bs4 import BeautifulSoup
main_url = "http://www.example.com"
main_page_html = tryAgain(main_url)
main_page_soup = BeautifulSoup(main_page_html)
# Scrape all TDs from TRs inside Table
for tr in main_page_soup.select("table.class_of_table"):
for td in tr.select("td#id"):
print(td.text)
# For acnhors inside TD
print(td.select("a")[0].text)
# Value of Href attribute
print(td.select("a")[0]["href"])
# This is method that scrape URL and if it doesnt get scraped, waits for 20 seconds and then tries again. (I use it because my internet connection sometimes get disconnects)
def tryAgain(passed_url):
try:
page = requests.get(passed_url,headers = random.choice(header), timeout = timeout_time).text
return page
except Exception:
while 1:
print("Trying again the URL:")
print(passed_url)
try:
page = requests.get(passed_url,headers = random.choice(header), timeout = timeout_time).text
print("-------------------------------------")
print("---- URL was successfully scraped ---")
print("-------------------------------------")
return page
except Exception:
time.sleep(20)
continue
Try using a format like %d.%02d
int iAmount = 10050;
printf("The number with fake decimal point is %d.%02d", iAmount/100, iAmount%100);
Another approach is to type cast it to double before printing it using %f like this:
printf("The number with fake decimal point is %0.2f", (double)(iAmount)/100);
My 2 cents :)
You can open multiple windows on single click... Try this..
<a href="http://--"
onclick=" window.open('http://--','','width=700,height=700');
window.open('http://--','','width=700,height=500'); ..// add more"
>Click Here</a>`
import glob
jpgFilenamesList = glob.glob('145592*.jpg')
See glob
in python documenttion
Because if an exception is thrown you won't ever see it - failing silently is the worst possible option - you'll get erroneous behavior and no idea to look where it's happening. At least put a log message there! Even if it's something that 'can never happen'!
You see the two empty -D
entries in the g++
command line? They're causing the problem. You must have values in the -D
items e.g. -DWIN32
if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:
SYSTEM ?= generic
ENVIRONMENT ?= generic
in the makefile which gives them default values.
Your output looks to be missing the all important output:
<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers
just to clarify, what actually got sent to g++
was -D -DWindows_NT
, i.e. define a preprocessor macro called -DWindows_NT
; which is of course not a valid identifier (similarly for -D -I.
)
For the next person Googling this topic, I've written a small NPM package to make it simple to generate Google Calendar URLs. It includes TypeScript type definitions, for those who need that. Hope it helps!
Forward port of .live()
for jQuery >= 1.9
Avoids refactoring JS dependencies on .live()
Uses optimized DOM selector context
/**
* Forward port jQuery.live()
* Wrapper for newer jQuery.on()
* Uses optimized selector context
* Only add if live() not already existing.
*/
if (typeof jQuery.fn.live == 'undefined' || !(jQuery.isFunction(jQuery.fn.live))) {
jQuery.fn.extend({
live: function (event, callback) {
if (this.selector) {
jQuery(document).on(event, this.selector, callback);
}
}
});
}
Looks a lot like Oracle, but that doesn't work on SQL Server.
You can, instead, adopt the following syntax...
SELECT
*
INTO
new_table
FROM
old_source(s)
try using the on error event of the client to find the issue.
var http = require('http');
var options = {
host: 'google.com',
path: '/'
}
var request = http.request(options, function (res) {
var data = '';
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
console.log(data);
});
});
request.on('error', function (e) {
console.log(e.message);
});
request.end();
my solution to the problem:
in footer add <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script>
Swift 3, with extension:
extension UIView{
var globalPoint :CGPoint? {
return self.superview?.convert(self.frame.origin, to: nil)
}
var globalFrame :CGRect? {
return self.superview?.convert(self.frame, to: nil)
}
}
<input type="text" id="txtCode" name="name" class="text_cs">
and js:
<script type="text/javascript">
$('.text_cs').on('change', function () {
var pid = $(this).val();
console.log("Value text: " + pid);
});
</script>
There are various ways to achieve this. Here are three.
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
System.out.println("using entrySet and toString");
for (Entry<String, String> entry : map.entrySet()) {
System.out.println(entry);
}
System.out.println();
System.out.println("using entrySet and manual string creation");
for (Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
System.out.println();
System.out.println("using keySet");
for (String key : map.keySet()) {
System.out.println(key + "=" + map.get(key));
}
System.out.println();
using entrySet and toString
key1=value1
key2=value2
key3=value3
using entrySet and manual string creation
key1=value1
key2=value2
key3=value3
using keySet
key1=value1
key2=value2
key3=value3
Sounds like you're calling df.plot()
. That error indicates that you're trying to plot a frame that has no numeric data. The data types shouldn't affect what you print()
.
Use print(df.iloc[159220])
There's no need to downgrade Android Tools. On Windows, Gradle moved from:
C:\Users\you_username\AppData\Local\Android\sdk\tools
to:
C:\Program Files\Android\Android Studio\plugins\android\lib\templates\gradle\wrapper
So you just need to adjust your path so that it points to the right folder.
For a more graceful way, try the following:
Caveat: I'm running Debian 7, not Ubuntu, though it is a Debian derivative
If you're running Tomcat as a service, you can get a list of all running services by typing:
sudo service --status-all
I'm running Tomcat 7, which is displayed as tomcat7 in said list. Then, to shut it down just type:
sudo service tomcat7 stop
If you are in an interactive environment like Jupyter
or ipython
you might be interested in clearing unwanted var's if they are getting heavy.
The magic-commands reset
and reset_selective
is vailable on interactive python sessions like ipython
and Jupyter
1) reset
reset
Resets the namespace by removing all names defined by the user, if called without arguments.
in
and the out
parameters specify whether you want to flush the in/out caches. The directory history is flushed with the dhist
parameter.
reset in out
Another interesting one is array
that only removes numpy Arrays:
reset array
2) reset_selective
Resets the namespace by removing names defined by the user. Input/Output history are left around in case you need them.
Clean Array Example:
In [1]: import numpy as np
In [2]: littleArray = np.array([1,2,3,4,5])
In [3]: who_ls
Out[3]: ['littleArray', 'np']
In [4]: reset_selective -f littleArray
In [5]: who_ls
Out[5]: ['np']
Source: http://ipython.readthedocs.io/en/stable/interactive/magics.html
Sometimes its because of ssh. So you can use this:
git clone https://cfdem.git.sourceforge.net/gitroot/cfdem/liggghts
instead of:
git clone git://cfdem.git.sourceforge.net/gitroot/cfdem/liggghts
You can use the JavaScript String concat() Method,
var str1 = "Hello ";
var str2 = "world!";
var res = str1.concat(str2); //will return "Hello world!"
Its syntax is:
string.concat(string1, string2, ..., stringX)
pip is run from the command line, not the Python interpreter. It is a program that installs modules, so you can use them from Python. Once you have installed the module, then you can open the Python shell and do import selenium
.
The Python shell is not a command line, it is an interactive interpreter. You type Python code into it, not commands.
I was working on the Contoso University tutorial offline and encountered the same issue when trying to create my first controller using EF. I had to use the Package Manager Console to load EF from the nuget cache and created a connection string to my local instance of SQL Server, my point here is my webConfig setting for EF may not be set as you all out there but I was able to resolve my issue by completely deleting the "providers" section within "entityFramework"
Robert
These both work fine for me...
<?php
$db = mysql_connect('localhost','user','pass');
mysql_select_db('test_db');
$stmt = "INSERT INTO `test` (`first`,`last`,`whenadded`) VALUES ".
"('{$first}','{$last}','NOW())";
$rslt = mysql_query($stmt);
$stmt = "INSERT INTO `users` (`first`,`last`,`whenadded`) VALUES ".
"('{$first}', '{$last}', CURRENT_TIMESTAMP)";
$rslt = mysql_query($stmt);
?>
Side note: mysql_query() is not the best way to connect to MySQL in current versions of PHP.
1) To remove white space everywhere:
df.columns = df.columns.str.replace(' ', '')
2) To remove white space at the beginning of string:
df.columns = df.columns.str.lstrip()
3) To remove white space at the end of string:
df.columns = df.columns.str.rstrip()
4) To remove white space at both ends:
df.columns = df.columns.str.strip()
5) To replace white space everywhere
df.columns = df.columns.str.replace(' ', '_')
6) To replace white space at the beginning:
df.columns = df.columns.str.replace('^ +', '_')
7) To replace white space at the end:
df.columns = df.columns.str.replace(' +$', '_')
8) To replace white space at both ends:
df.columns = df.columns.str.replace('^ +| +$', '_')
All above applies to a specific column as well, assume you have a column named col
, then just do:
df[col] = df[col].str.strip() # or .replace as above
In November 2017 Google released the Room Persistence Library.
From the documentation:
The Room persistence library provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.
The library helps you create a cache of your app's data on a device that's running your app. This cache, which serves as your app's single source of truth, allows users to view a consistent copy of the key information within your app, regardless of whether users have an internet connection.
The Room database has a callback when the database is first created or opened. You can use the create callback to populate your database.
Room.databaseBuilder(context.applicationContext,
DataDatabase::class.java, "Sample.db")
// prepopulate the database after onCreate was called
.addCallback(object : Callback() {
override fun onCreate(db: SupportSQLiteDatabase) {
super.onCreate(db)
// moving to a new thread
ioThread {
getInstance(context).dataDao()
.insert(PREPOPULATE_DATA)
}
}
})
.build()
Code from this blog post.
See in the android sdk directory.
In \platforms\android-X\data\res\values\themes.xml
:
<item name="textAppearanceLarge">@android:style/TextAppearance.Large</item>
<item name="textAppearanceMedium">@android:style/TextAppearance.Medium</item>
<item name="textAppearanceSmall">@android:style/TextAppearance.Small</item>
In \platforms\android-X\data\res\values\styles.xml
:
<style name="TextAppearance.Large">
<item name="android:textSize">22sp</item>
</style>
<style name="TextAppearance.Medium">
<item name="android:textSize">18sp</item>
</style>
<style name="TextAppearance.Small">
<item name="android:textSize">14sp</item>
<item name="android:textColor">?textColorSecondary</item>
</style>
TextAppearance.Large
means style is inheriting from TextAppearance
style, you have to trace it also if you want to see full definition of a style.
Link: http://developer.android.com/design/style/typography.html
To reference the contents of the single array containing one or more objects i.e. everything in the brackets of something like this {messages: [{"a":1,"b":2}] } ,just add [0] to the query to get the first array element
e.g. messages[0] will reference the object {"a":1,"b":2} as opposed to just messages which would reference the entire array [{"a":1,"b":2}]
from there you can work with the result as typical object and use Object.keys for example to get "a" and "b".
You have to insert your <table>
into a <div>
that it has fixed size, and in <div>
style you have to set overflow: scroll
.
If you want to have lists only when they are necessary, and values in any other cases, then you can do this:
class DictList(dict):
def __setitem__(self, key, value):
try:
# Assumes there is a list on the key
self[key].append(value)
except KeyError: # If it fails, because there is no key
super(DictList, self).__setitem__(key, value)
except AttributeError: # If it fails because it is not a list
super(DictList, self).__setitem__(key, [self[key], value])
You can then do the following:
dl = DictList()
dl['a'] = 1
dl['b'] = 2
dl['b'] = 3
Which will store the following {'a': 1, 'b': [2, 3]}
.
I tend to use this implementation when I want to have reverse/inverse dictionaries, in which case I simply do:
my_dict = {1: 'a', 2: 'b', 3: 'b'}
rev = DictList()
for k, v in my_dict.items():
rev_med[v] = k
Which will generate the same output as above: {'a': 1, 'b': [2, 3]}
.
CAVEAT: This implementation relies on the non-existence of the append
method (in the values you are storing). This might produce unexpected results if the values you are storing are lists. For example,
dl = DictList()
dl['a'] = 1
dl['b'] = [2]
dl['b'] = 3
would produce the same result as before {'a': 1, 'b': [2, 3]}
, but one might expected the following: {'a': 1, 'b': [[2], 3]}
.
Slick has a very easy way to customize its buttons through two variables in its own configuration: prevArrow
and nextArrow
.
Both types are: string (html | jQuery selector) | object (DOM node | jQuery object), so in your settings slick slider you can set the classes:
prevArrow: $('.prev')
nextArrow: $('.next')
and add to these elements the styles you want.
For example:
//HTML
<div class="slider-box _clearfix">
<div class="slick-slider">
<div>
<img src="img/home_carousel/home_carorusel_1.jpg">
</div>
<div>
<img src="img/home_carousel/home_carorusel_2.jpg">
</div>
<div>
<img src="img/home_carousel/home_carorusel_3.jpg">
</div>
<div>
<img src="img/home_carousel/home_carorusel_4.jpg">
</div>
</div>
</div>
<div class="paginator-center text-color text-center">
<h6>VER MAS LANZAMIENTOS</h6>
<ul>
<li class="prev"></li>
<li class="next"></li>
</ul>
</div>
//JS
$(document).ready(function () {
$('.slick-slider').slick({
centerMode: true,
centerPadding: '60px',
slidesToShow: 3,
prevArrow: $('.prev'),
nextArrow: $('.next'),
});
//CSS
.paginator{
position: relative;
float: right;
margin-bottom: 20px;
li{
margin-top: 20px;
position: relative;
float: left;
margin-right: 20px;
&.prev{
display: block;
height: 20px;
width: 20px;
background: url('../img/back.png') no-repeat;
}
&.next{
display: block;
height: 20px;
width: 20px;
background: url('../img/next.png') no-repeat;
}
}
}
Use simple and easy code
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let myCell = tableView.dequeueReusableCellWithIdentifier("mannaCustumCell") as! CustomCell
let heightForCell = myCell.bounds.size.height;
return heightForCell;
}
The same can be applied to a scenario where the data has been normalized, but now you want a table to have values found in a third table. The following will allow you to update a table with information from a third table that is liked by a second table.
UPDATE t1
LEFT JOIN
t2
ON
t2.some_id = t1.some_id
LEFT JOIN
t3
ON
t2.t3_id = t3.id
SET
t1.new_column = t3.column;
This would be useful in a case where you had users and groups, and you wanted a user to be able to add their own variation of the group name, so originally you would want to import the existing group names into the field where the user is going to be able to modify it.
For me, works this way: mvn -f /path/to/pom.xml [goals]
I am also having This Error!
Then i change this
$("#from").datepicker('disable');
to This
$("#from").datepicker("disable");
mistake : single and double quotes..
Now its Work fine for me..
You can try something like this:
def details_to_json
{
:id => self.id,
:credit_period_type => self.credit_period_type,
:credit_payment_period => self.credit_payment_period,
}.to_json
end
HttpWebRequest request =(HttpWebRequest)WebRequest.Create("some url");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 7.1; Trident/5.0)";
request.Accept = "/";
request.UseDefaultCredentials = true;
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
doc.Save(request.GetRequestStream());
HttpWebResponse resp = request.GetResponse() as HttpWebResponse;
Hope it helps
While it may not directly determine whether the phone is connected to a network, the simplest(, cleanest?) solution would be to 'ping' Google, or some other server, (which isn't possible unless the phone is connected to a network):
private var urlSession:URLSession = {
var newConfiguration:URLSessionConfiguration = .default
newConfiguration.waitsForConnectivity = false
newConfiguration.allowsCellularAccess = true
return URLSession(configuration: newConfiguration)
}()
public func canReachGoogle() -> Bool
{
let url = URL(string: "https://8.8.8.8")
let semaphore = DispatchSemaphore(value: 0)
var success = false
let task = urlSession.dataTask(with: url!)
{ data, response, error in
if error != nil
{
success = false
}
else
{
success = true
}
semaphore.signal()
}
task.resume()
semaphore.wait()
return success
}
If you're concerned that the server may be down or may block your IP, you can always ping multiple servers in a similar fashion and return whether any of them are reachable. Or have someone set up a dedicated server just for this purpose.
Use a regex to remove the formating (dollar and comma), and use parseFloat to convert the string to a floating point number.`
var currency = "$1,100.00";
currency.replace(/[$,]+/g,"");
var result = parseFloat(currency) + .05;
On Linux, you can get ELF header information by using either of the following two commands:
file {YOUR_JRE_LOCATION_HERE}/bin/java
o/p: ELF 64-bit LSB executable, AMD x86-64, version 1 (SYSV), for GNU/Linux 2.4.0, dynamically linked (uses shared libs), for GNU/Linux 2.4.0, not stripped
or
readelf -h {YOUR_JRE_LOCATION_HERE}/bin/java | grep 'Class'
o/p: Class: ELF64
You could open two textstreams, one for reading
Set filestreamIn = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Test.txt,1)
and one for appending
Set filestreamOUT = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Test.txt,8,true)
The filestreamIN can read from the begining of the file, and the filestreamOUT can write to the end of the file.
If you have problems with accessing to the path, maybe you need to put this:
$root = $_SERVER['DOCUMENT_ROOT'];
$path = "/cv/";
// Open the folder
$dir_handle = @opendir($root . $path) or die("Unable to open $path");
$('div.alldivs :first-child');
Or you can just refer to the id directly:
$('#div1');
As suggested, you might be better of using the child selector:
$('div.alldivs > div:first-child')
If you dont have to use first-child
, you could use :first
as also suggested, or $('div.alldivs').children(0)
.
One more alternative cross-platform solution on powershell 6.2.3:
$headers = @{
'Authorization' = 'Token 12d119ad48f9b70ed53846f9e3d051dc31afab27'
}
$body = @"
{
"value":"3.92.0",
"product":"847"
}
"@
$params = @{
Uri = 'http://local.vcs:9999/api/v1/version/'
Headers = $headers
Method = 'POST'
Body = $body
ContentType = 'application/json'
}
Invoke-RestMethod @params
It's a little memory-inefficient but if you're using the data anyway, I use this frequently:
$rows = $q->fetchAll();
$num_rows = count($rows);