Automatically fill all form fields from an array
http://jsfiddle.net/brynner/wf0rk7tz/2/
JS
function fill(a){
for(var k in a){
$('[name="'+k+'"]').val(a[k]);
}
}
array_example = {"God":"Jesus","Holy":"Spirit"};
fill(array_example);
HTML
<form>
<input name="God">
<input name="Holy">
</form>
I know this does not answer your question, but why don't you use a date handling routine to check if it's a valid date? Even if you modify the regexp with a negative lookahead assertion like (?!31/0?2) (ie, do not match 31/2 or 31/02) you'll still have the problem of accepting 29 02 on non leap years and about a single separator date format.
The problem is not easy if you want to really validate a date, check this forum thread.
For an example or a better way, in C#, check this link
If you are using another platform/language, let us know
select tableA.id from tableA left outer join tableB on (tableA.id = tableB.id)
where tableB.id is null
order by tableA.id desc
If your db knows how to do index intersections, this will only touch the primary key index
I don't know whether there's a better answer out there as time goes by but this is simple and it works;
input[type='email'] {
background: white url(images/mail.svg) no-repeat ;
}
input[type='email']:focus {
background-image: none;
}
Style it up to suit.
You can download the free Visual C++ 2008 Express Edition from http://go.microsoft.com/?linkid=7729279, which will set the VS90COMNTOOLS environment variable during installation and therefore build with a compatible compiler.
As @PiotrDobrogost mentioned in a comment, his answer to this other question goes into details about why Visual C++ 2008 is the right thing to build with, but this can change as the Windows build of Python moves to newer versions of Visual Studio: Building lxml for Python 2.7 on Windows
For now, If you want to move a column over just 4 column units for instance, I would suggest to use just a dummy placeholder like in my example below
<div class="row">
<div class="col-md-4">Offset 4 column</div>
<div class="col-md-8">
//content
</div>
</div>
This code works perfectly well:
Actions builder = new Actions(driver);
WebElement element = driver.findElement(By.linkText("Put your text here"));
builder.moveToElement(element).build().perform();
After the mouse over, you can then go on to perform the next action you want on the revealed information
To answer your question, and get the Prefix
too, for MySQL you can do:
select Prefix, CR, length(CR) from table1 order by length(CR) DESC limit 1;
and it will return
+-------+----------------------------+--------------------+
| Prefix| CR | length(CR) |
+-------+----------------------------+--------------------+
| g | ;#WR_1;#WR_2;#WR_3;#WR_4;# | 26 |
+-------+----------------------------+--------------------+
1 row in set (0.01 sec)
This answer doesn't help for SQL databases where SharePoint is connected. db_securityadmin is required for the configuration databases. In order to add db_securityadmin, you will need to change the owner of the database to an administrative account. You can use that account just for dbo roles.
For Kotlin developers, remember the Java transient
keyword becomes the built-in Kotlin @Transient
annotation. Therefore, make sure you have the JPA import if you're using JPA @Transient
in your entity:
import javax.persistence.Transient
For me this worked $ ? git branch -D -r origin/mybranch
Details
$ ? git branch -a | grep mybranch remotes/origin/mybranch
$ ? git branch -r | grep mybranch origin/mybranch
$ ? git branch develop * feature/pre-deployment
$ ? git push origin --delete mybranch error: unable to delete 'mybranch': remote ref does not exist error: failed to push some refs to '[email protected]:config/myrepo.git'
$ ? git branch -D -r origin/mybranch Deleted remote branch origin/mybranch (was 62c7421).
$ ? git branch -a | grep mybranch
$ ? git branch -r | grep mybranch
git pull
= git fetch
+ git merge origin/branch
git pull
and git pull origin branch
only differ in that the latter will only "update" origin/branch and not all origin/* as git pull
does.
git pull origin/branch
will just not work because it's trying to do a git fetch origin/branch
which is invalid.
Question related: git fetch + git merge origin/master vs git pull origin/master
Had similar error with the same result with Gradle and was able to solve it by following:
//compile 'org.slf4j:slf4j-api:1.7.1'
compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.1'
compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.1'
compile group: 'org.apache.logging.log4j', name: 'log4j-slf4j-impl', version: '2.1'
Out-commented line is the one which caused the error output. I believe you can transfer this to Maven.
Put your div inside another div, apply the border to the outer div with n amount of padding/margin where n is the space you want between them.
I am using xampp. For me best option is to change environment variables. Environment variable changing window is shared by @Abu Bakr in this thread
I change the path value as C:\xampp\mysql\bin; and it is working nice
I think your questions will all be answered if you understand how Sets, and in particular HashSets work. A set is a collection of unique objects, with Java defining uniqueness in that it doesn't equal anything else (equals returns false).
The HashSet takes advantage of hashcodes to speed things up. It assumes that two objects that equal eachother will have the same hash code. However it does not assume that two objects with the same hash code mean they are equal. This is why when it detects a colliding hash code, it only compares with other objects (in your case one) in the set with the same hash code.
I get it to work without any reference to "class" or "ClassLoader".
Let's say we have three scenarios with the location of the file 'example.file' and your working directory (where your app executes) is home/mydocuments/program/projects/myapp:
a)A sub folder descendant to the working directory: myapp/res/files/example.file
b)A sub folder not descendant to the working directory: projects/files/example.file
b2)Another sub folder not descendant to the working directory: program/files/example.file
c)A root folder: home/mydocuments/files/example.file (Linux; in Windows replace home/ with C:)
1) Get the right path:
a)String path = "res/files/example.file";
b)String path = "../projects/files/example.file"
b2)String path = "../../program/files/example.file"
c)String path = "/home/mydocuments/files/example.file"
Basically, if it is a root folder, start the path name with a leading slash. If it is a sub folder, no slash must be before the path name. If the sub folder is not descendant to the working directory you have to cd to it using "../". This tells the system to go up one folder.
2) Create a File object by passing the right path:
File file = new File(path);
3) You are now good to go:
BufferedReader br = new BufferedReader(new FileReader(file));
You could create a wrapper application that you run instead of directly running your real app. The wrapper application can listen to stdout and redirect everything to Trace. Then change the run settings to launch your wrapper and pass in the path to the real app to run.
You could also have the wrapper auto-attach the debugger to the new process if a debugger is attached to the wrapper.
Node is complaining because there is no function called define
, which your code tries to call on its very first line.
define
comes from AMD, which is not used in standard node development.
It is possible that the developer you got your project from used some kind of trickery to use AMD in node. You should ask this person what special steps are necessary to run the code.
this can be done very easily with HTML 5, see this link http://www.html5rocks.com/en/tutorials/file/dndfiles/
When I added IIS_IUSRS permission to site folder - resources, like js and css, still were unaccessible (error 401, forbidden). However, when I added IUSR - it became ok. So for sure "you CANNOT remove the permissions for IUSR without worrying", dear @Travis G@
In the second .c
file use extern
keyword with the same variable name.
<input name="searchbox" onfocus="if (this.value=='search') this.value = ''" type="text" value="search">
A better example would be the SO search button! That's where I got this code from. Viewing page source is a valuable tool.
If searching for a value, you will have to loop through all the data. But to minimize code involved, you can use LINQ
.
Given Dictionary defined as following:
Dictionary<Int32, String> dict;
You can use following code :
// Search for all keys with given value
Int32[] keys = dict.Where(kvp => kvp.Value.Equals("SomeValue")).Select(kvp => kvp.Key).ToArray();
// Search for first key with given value
Int32 key = dict.First(kvp => kvp.Value.Equals("SomeValue")).Key;
.nvmrc
If you are using NVM like this, which you likely should, then you can indicate the nodejs version required for given project in a git-tracked .nvmrc
file:
echo v10.15.1 > .nvmrc
This does not take effect automatically on cd
, which is sane: the user must then do a:
nvm use
and now that version of node will be used for the current shell.
You can list the versions of node that you have with:
nvm list
.nvmrc
is documented at: https://github.com/creationix/nvm/tree/02997b0753f66c9790c6016ed022ed2072c22603#nvmrc
How to automatically select that node version on cd
was asked at: Automatically switch to correct version of Node based on project
Tested with NVM 0.33.11.
You formaction for multiple submit button in one form example
<input type="submit" name="" class="btn action_bg btn-sm loadGif" value="Add Address" title="" formaction="/addAddress">
<input type="submit" name="" class="btn action_bg btn-sm loadGif" value="update Address" title="" formaction="/updateAddress">
KOTLIN
Following the google doc, there is a easy way :
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) hideSystemUI() }
private fun hideSystemUI() {
// Enables regular immersive mode.
// For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE.
// Or for "sticky immersive," replace it with SYSTEM_UI_FLAG_IMMERSIVE_STICKY
window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE
// Set the content to appear under the system bars so that the
// content doesn't resize when the system bars hide and show.
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
// Hide the nav bar and status bar
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_FULLSCREEN) }
// Shows the system bars by removing all the flags
// except for the ones that make the content appear under the system bars.
private fun showSystemUI() {
window.decorView.systemUiVisibility =
(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN) }
here's an example using html2canvas & jspdf, although how you generate the canvas doesn't matter--we're just going to use the height of that as the breakpoint on a for loop
, in which a new page is created and content added to it.
after the for loop, the pdf is saved.
function makePDF() {
var quotes = document.getElementById('container-fluid');
html2canvas(quotes)
.then((canvas) => {
//! MAKE YOUR PDF
var pdf = new jsPDF('p', 'pt', 'letter');
for (var i = 0; i <= quotes.clientHeight/980; i++) {
//! This is all just html2canvas stuff
var srcImg = canvas;
var sX = 0;
var sY = 980*i; // start 980 pixels down for every new page
var sWidth = 900;
var sHeight = 980;
var dX = 0;
var dY = 0;
var dWidth = 900;
var dHeight = 980;
window.onePageCanvas = document.createElement("canvas");
onePageCanvas.setAttribute('width', 900);
onePageCanvas.setAttribute('height', 980);
var ctx = onePageCanvas.getContext('2d');
// details on this usage of this function:
// https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images#Slicing
ctx.drawImage(srcImg,sX,sY,sWidth,sHeight,dX,dY,dWidth,dHeight);
// document.body.appendChild(canvas);
var canvasDataURL = onePageCanvas.toDataURL("image/png", 1.0);
var width = onePageCanvas.width;
var height = onePageCanvas.clientHeight;
//! If we're on anything other than the first page,
// add another page
if (i > 0) {
pdf.addPage(612, 791); //8.5" x 11" in pts (in*72)
}
//! now we declare that we're working on that page
pdf.setPage(i+1);
//! now we add content to that page!
pdf.addImage(canvasDataURL, 'PNG', 20, 40, (width*.62), (height*.62));
}
//! after the for loop is finished running, we save the pdf.
pdf.save('Test.pdf');
}
});
}
lst = ["a", "b", "a", "c", "c", "a", "c"]
temp=set(lst)
result={}
for i in temp:
result[i]=lst.count(i)
print result
Output:
{'a': 3, 'c': 3, 'b': 1}
Assuming 96dpi is a huge mistake. Even if the assumption is right, there's also an option to scale fonts. So a font set for 10pts may actually be shown as if it's 12.5pt (125%).
I was using View.INVISIBLE
and View.VISIBLE
and the ProgressBar
would slowly flash instead of constantly being visible, switched to View.GONE
and View.VISIBLE
and it works perfectly
Well, for me this is the expected result; adding six months to Jan. 1st July.
mysql> SELECT DATE_ADD( '2011-01-01', INTERVAL 6 month );
+--------------------------------------------+
| DATE_ADD( '2011-01-01', INTERVAL 6 month ) |
+--------------------------------------------+
| 2011-07-01 |
+--------------------------------------------+
Use the format()
function:
>>> format(14, '#010b')
'0b00001110'
The format()
function simply formats the input following the Format Specification mini language. The #
makes the format include the 0b
prefix, and the 010
size formats the output to fit in 10 characters width, with 0
padding; 2 characters for the 0b
prefix, the other 8 for the binary digits.
This is the most compact and direct option.
If you are putting the result in a larger string, use an formatted string literal (3.6+) or use str.format()
and put the second argument for the format()
function after the colon of the placeholder {:..}
:
>>> value = 14
>>> f'The produced output, in binary, is: {value:#010b}'
'The produced output, in binary, is: 0b00001110'
>>> 'The produced output, in binary, is: {:#010b}'.format(value)
'The produced output, in binary, is: 0b00001110'
As it happens, even for just formatting a single value (so without putting the result in a larger string), using a formatted string literal is faster than using format()
:
>>> import timeit
>>> timeit.timeit("f_(v, '#010b')", "v = 14; f_ = format") # use a local for performance
0.40298633499332936
>>> timeit.timeit("f'{v:#010b}'", "v = 14")
0.2850222919951193
But I'd use that only if performance in a tight loop matters, as format(...)
communicates the intent better.
If you did not want the 0b
prefix, simply drop the #
and adjust the length of the field:
>>> format(14, '08b')
'00001110'
Learn to customize and write your own tags using JSTL
Note that EL is EviL (runtime exceptions and refactoring).
Wicket may be evil too (performance and toilsome for small applications or simple view tier).
This must be added to the web application's web.xml
<taglib>
<taglib-uri>/java2s</taglib-uri>
<taglib-location>/WEB-INF/java2s.tld</taglib-location>
</taglib>
Create file java2s.tld in the /WEB-INF/
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<!-- A tab library descriptor -->
<taglib xmlns="http://java.sun.com/JSP/TagLibraryDescriptor">
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>Java2s Simple Tags</short-name>
<!-- This tag manipulates its body content by converting it to upper case
-->
<tag>
<name>bodyContentTag</name>
<tag-class>com.java2s.BodyContentTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<name>howMany</name>
</attribute>
</tag>
</taglib>
Compile the following code into WEB-INF\classes\com\java2s
package com.java2s;
import java.io.IOException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;
public class BodyContentTag extends BodyTagSupport{
private int iterations, howMany;
public void setHowMany(int i){
this.howMany = i;
}
public void setBodyContent(BodyContent bc){
super.setBodyContent(bc);
System.out.println("BodyContent = '" + bc.getString() + "'");
}
public int doAfterBody(){
try{
BodyContent bodyContent = super.getBodyContent();
String bodyString = bodyContent.getString();
JspWriter out = bodyContent.getEnclosingWriter();
if ( iterations % 2 == 0 )
out.print(bodyString.toLowerCase());
else
out.print(bodyString.toUpperCase());
iterations++;
bodyContent.clear(); // empty buffer for next evaluation
}
catch (IOException e) {
System.out.println("Error in BodyContentTag.doAfterBody()" + e.getMessage());
e.printStackTrace();
} // End of catch
int retValue = SKIP_BODY;
if ( iterations < howMany )
retValue = EVAL_BODY_AGAIN;
return retValue;
}
}
Start the server and load the bodyContent.jsp file in the browser:
<%@ taglib uri="/java2s" prefix="java2s" %>
<html>
<head>
<title>A custom tag: body content</title>
</head>
<body>
This page uses a custom tag manipulates its body content.Here is its output:
<ol>
<java2s:bodyContentTag howMany="3">
<li>java2s.com</li>
</java2s:bodyContentTag>
</ol>
</body>
</html>
you can use the custom datetime by using...
create table noteTable3
(created_at DATETIME DEFAULT (STRFTIME('%d-%m-%Y %H:%M', 'NOW','localtime')),
title text not null, myNotes text not null);
use 'NOW','localtime' to get the current system date else it will show some past or other time in your Database after insertion time in your db.
Thanks You...
pip uninstall pip
will work
Put the table in a container element that has
overflow:scroll; max-width:95vw;
or make the table fit to the screen and overflow:scroll all table cells.
You also can use special change_table method in the migration for adding new columns:
change_table(:users) do |t|
t.column :email, :string
end
use
System.out.print( nir[0].length);
look at this for loop which print the content of the 2 dimension array the second loop iterate over the column in each row
for(int row =0 ; row < ntr.length; ++row)
for(int column =0; column<ntr[row].length;++column)
System.out.print(ntr[row][column]);
You can just AND the results together if they are stored as TRUE / FALSE values:
=AND(A1:D2)
Or if stored as text, use an array formula - enter the below and press Ctrl+Shift+Enter instead of Enter.
=AND(EXACT(A1:D2,"TRUE"))
Just reposting @bucababy's answer as a "bookmarklet", as it's sometimes easier than using those lookup pages:
alert(prompt('Enter characters to htmlEncode', '').replace(/[\u00A0-\u2666]/g, function(c) {
return '&#'+c.charCodeAt(0)+';';
}));
DECLARE @FromDate DATETIME
SET @FromDate = 'Jan 10 2016 12:00AM'
DECLARE @ToDate DATETIME
SET @ToDate = 'Jan 10 2017 12:00AM'
DECLARE @Dynamic_Qry nvarchar(Max) =''
SET @Dynamic_Qry='SELECT
(CONVERT(DATETIME,(SELECT
CASE WHEN ( ''IssueDate'' =''IssueDate'') THEN
EMP_DOCUMENT.ISSUE_DATE
WHEN (''IssueDate'' =''ExpiryDate'' ) THEN
EMP_DOCUMENT.EXPIRY_DATE ELSE EMP_DOCUMENT.APPROVED_ON END
CHEKDATE ), 101)
)FROM CR.EMP_DOCUMENT as EMP_DOCUMENT WHERE 1=1
AND (
CONVERT(DATETIME,(SELECT
CASE WHEN ( ''IssueDate'' =''IssueDate'') THEN
EMP_DOCUMENT.ISSUE_DATE
WHEN (''IssueDate'' =''ExpiryDate'' ) THEN EMP_DOCUMENT.EXPIRY_DATE
ELSE EMP_DOCUMENT.APPROVED_ON END
CHEKDATE ), 101)
) BETWEEN '''+ CONVERT(CHAR(10), @FromDate, 126) +''' AND '''+CONVERT(CHAR(10), @ToDate , 126
)
+'''
'
print @Dynamic_Qry
EXEC(@Dynamic_Qry)
Define what GetData is. At the moment it is not defined.
Function getData(currentWorksheet as Worksheet, dataStartRow as Integer, dataEndRow as Integer, DataStartCol as Integer, dataEndCol as Integer) as variant
defaultMember
already is an alias - it doesn't need to be the name of the exported function/thing. Just do
import alias from 'my-module';
Alternatively you can do
import {default as alias} from 'my-module';
but that's rather esoteric.
This one worked for me:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
If you create a new Date object, by default it will be set to the current time:
import java.util.Date;
Date now = new Date();
Leave blank catch block is the worse thing to do. If there is an error the best way to handle it is to:
You can setup global parameter with
jQuery.ajaxSettings.traditional = true;
This is a highly inefficient way of doing it. You can use the merge
statement and then there's no need for cursors, looping or (if you can do without) PL/SQL.
MERGE INTO studLoad l
USING ( SELECT studId, studName FROM student ) s
ON (l.studId = s.studId)
WHEN MATCHED THEN
UPDATE SET l.studName = s.studName
WHERE l.studName != s.studName
WHEN NOT MATCHED THEN
INSERT (l.studID, l.studName)
VALUES (s.studId, s.studName)
Make sure you commit
, once completed, in order to be able to see this in the database.
To actually answer your question I would do it something like as follows. This has the benefit of doing most of the work in SQL and only updating based on the rowid, a unique address in the table.
It declares a type, which you place the data within in bulk, 10,000 rows at a time. Then processes these rows individually.
However, as I say this will not be as efficient as merge
.
declare
cursor c_data is
select b.rowid as rid, a.studId, a.studName
from student a
left outer join studLoad b
on a.studId = b.studId
and a.studName <> b.studName
;
type t__data is table of c_data%rowtype index by binary_integer;
t_data t__data;
begin
open c_data;
loop
fetch c_data bulk collect into t_data limit 10000;
exit when t_data.count = 0;
for idx in t_data.first .. t_data.last loop
if t_data(idx).rid is null then
insert into studLoad (studId, studName)
values (t_data(idx).studId, t_data(idx).studName);
else
update studLoad
set studName = t_data(idx).studName
where rowid = t_data(idx).rid
;
end if;
end loop;
end loop;
close c_data;
end;
/
The assembly was introduced with .NET 3.5 and is in the GAC.
Simply add a .NET reference to your project.
Project -> Right Click References
-> Select .NET
tab -> System.Web.Extensions
If it is not there, you need to install .NET 3.5 or 4.0.
It will look like this
<head>
<script type="text/javascript">
var image1 = new Image()
image1.src = "images/pentagg.jpg"
var image2 = new Image()
image2.src = "images/promo.jpg"
</script>
</head>
<body>
<p><img src="images/pentagg.jpg" width="500" height="300" name="slide" /></p>
<script type="text/javascript">
var step=1;
function slideit()
{
document.images.slide.src = eval("image"+step+".src");
if(step<2)
step++;
else
step=1;
setTimeout("slideit()",2500);
}
slideit();
</script>
</body>
This will convert n seconds into d days, h hours, m minutes, and s seconds.
from datetime import datetime, timedelta
def GetTime():
sec = timedelta(seconds=int(input('Enter the number of seconds: ')))
d = datetime(1,1,1) + sec
print("DAYS:HOURS:MIN:SEC")
print("%d:%d:%d:%d" % (d.day-1, d.hour, d.minute, d.second))
Two things:
Use:
DECLARE @temp VARCHAR(10)
SET @temp = 'm'
IF @temp = 'm'
SELECT 'yes'
ELSE
SELECT 'no'
VARCHAR(10)
means the VARCHAR will accommodate up to 10 characters. More examples of the behavior -
DECLARE @temp VARCHAR
SET @temp = 'm'
IF @temp = 'm'
SELECT 'yes'
ELSE
SELECT 'no'
...will return "yes"
DECLARE @temp VARCHAR
SET @temp = 'mtest'
IF @temp = 'm'
SELECT 'yes'
ELSE
SELECT 'no'
...will return "no".
UILabel
has a property lineBreakMode
that you can set as per your requirement.
You can now use select
with the where
selection helper. select_if
is superceded, but still functional as of dplyr 1.0.2. (thanks to @mcstrother for bringing this to attention).
library(dplyr)
temp <- data.frame(x = 1:5, y = c(1,2,NA,4, 5), z = rep(NA, 5))
not_all_na <- function(x) any(!is.na(x))
not_any_na <- function(x) all(!is.na(x))
> temp
x y z
1 1 1 NA
2 2 2 NA
3 3 NA NA
4 4 4 NA
5 5 5 NA
> temp %>% select(where(not_all_na))
x y
1 1 1
2 2 2
3 3 NA
4 4 4
5 5 5
> temp %>% select(where(not_any_na))
x
1 1
2 2
3 3
4 4
5 5
dplyr
now has a select_if
verb that may be helpful here:
> temp
x y z
1 1 1 NA
2 2 2 NA
3 3 NA NA
4 4 4 NA
5 5 5 NA
> temp %>% select_if(not_all_na)
x y
1 1 1
2 2 2
3 3 NA
4 4 4
5 5 5
> temp %>% select_if(not_any_na)
x
1 1
2 2
3 3
4 4
5 5
Update for 2020 - BinaryPrimitives
should now be preferred over BitConverter
. It provides endian-specific APIs, and is less allocatey.
byte[] bytes = BitConverter.GetBytes(i);
although note also that you might want to check BitConverter.IsLittleEndian
to see which way around that is going to appear!
Note that if you are doing this repeatedly you might want to avoid all those short-lived array allocations by writing it yourself via either shift operations (>>
/ <<
), or by using unsafe
code. Shift operations also have the advantage that they aren't affected by your platform's endianness; you always get the bytes in the order you expect them.
In a case where you are using a custom cell type, say ArticleCell, you might get an error that says :
Initializer for conditional binding must have Optional type, not 'ArticleCell'
You will get this error if your line of code looks something like this:
if let cell = tableView.dequeReusableCell(withIdentifier: "ArticleCell",for indexPath: indexPath) as! ArticleCell
You can fix this error by doing the following :
if let cell = tableView.dequeReusableCell(withIdentifier: "ArticleCell",for indexPath: indexPath) as ArticleCell?
If you check the above, you will see that the latter is using optional casting for a cell of type ArticleCell.
It should be MM
for months. You are asking for minutes.
DateTime.Now.ToString("dd/MM/yyyy");
See Custom Date and Time Format Strings on MSDN for details.
queNumMin = 23;
queNumMax= 26;
result = 0;
for (let index = this.queNumMin; index <= this.queNumMax; index++) {
this.result = index
console.log( this.result);
}
Range min and max number
Have you unistalled your Internet Explorer? I did, and I had the same issues, if so, you have to:
Finally it works!
you can still use
String Item = getIntent().getExtras().getString("name");
in the fragment
, you just need call getActivity()
first:
String Item = getActivity().getIntent().getExtras().getString("name");
This saves you having to write some code.
Long version:
private bool booleanMethod () {
if (your_condition) {
return true;
} else {
return false;
}
}
But since you are using the outcome of your condition as the result of the method you can shorten it to
private bool booleanMethod () {
return your_condition;
}
The problem you referenced about /dev/random
is not with the SecureRandom
algorithm, but with the source of randomness that it uses. The two are orthogonal. You should figure out which one of the two is slowing you down.
Uncommon Maths page that you linked explicitly mentions that they are not addressing the source of randomness.
You can try different JCE providers, such as BouncyCastle, to see if their implementation of SecureRandom
is faster.
A brief search also reveals Linux patches that replace the default implementation with Fortuna. I don't know much more about this, but you're welcome to investigate.
I should also mention that while it's very dangerous to use a badly implemented SecureRandom
algorithm and/or randomness source, you can roll your own JCE Provider with a custom implementation of SecureRandomSpi
. You will need to go through a process with Sun to get your provider signed, but it's actually pretty straightforward; they just need you to fax them a form stating that you're aware of the US export restrictions on crypto libraries.
All this peace of code put into *.bat file and run all at once:
My code for creating user in oracle. crate_drop_user.sql file
drop user "USER" cascade;
DROP TABLESPACE "USER";
CREATE TABLESPACE USER DATAFILE 'D:\ORA_DATA\ORA10\USER.ORA' SIZE 10M REUSE
AUTOEXTEND
ON NEXT 5M EXTENT MANAGEMENT LOCAL
SEGMENT SPACE MANAGEMENT AUTO
/
CREATE TEMPORARY TABLESPACE "USER_TEMP" TEMPFILE
'D:\ORA_DATA\ORA10\USER_TEMP.ORA' SIZE 10M REUSE AUTOEXTEND
ON NEXT 5M EXTENT MANAGEMENT LOCAL
UNIFORM SIZE 1M
/
CREATE USER "USER" PROFILE "DEFAULT"
IDENTIFIED BY "user_password" DEFAULT TABLESPACE "USER"
TEMPORARY TABLESPACE "USER_TEMP"
/
alter user USER quota unlimited on "USER";
GRANT CREATE PROCEDURE TO "USER";
GRANT CREATE PUBLIC SYNONYM TO "USER";
GRANT CREATE SEQUENCE TO "USER";
GRANT CREATE SNAPSHOT TO "USER";
GRANT CREATE SYNONYM TO "USER";
GRANT CREATE TABLE TO "USER";
GRANT CREATE TRIGGER TO "USER";
GRANT CREATE VIEW TO "USER";
GRANT "CONNECT" TO "USER";
GRANT SELECT ANY DICTIONARY to "USER";
GRANT CREATE TYPE TO "USER";
create file import.bat and put this lines in it:
SQLPLUS SYSTEM/systempassword@ORA_alias @"crate_drop_user.SQL"
IMP SYSTEM/systempassword@ORA_alias FILE=user.DMP FROMUSER=user TOUSER=user GRANTS=Y log =user.log
Be carefull if you will import from one user to another. For example if you have user named user1 and you will import to user2 you may lost all grants , so you have to recreate it.
Good luck, Ivan
There is a 3rd party debugger in the works, it's currently in preview, but you can install the debugger Android extension in VSCode right now and get more information on it here:
One thing you might want to look at is the Commons DBCP project. It provides a BasicDataSource that is configured fairly similarly to your example. To use that you need the database vendor's JDBC JAR in your classpath and you have to specify the vendor's driver class name and the database URL in the proper format.
Edit:
If you want to configure a BasicDataSource
for MySQL, you would do something like this:
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUsername("username");
dataSource.setPassword("password");
dataSource.setUrl("jdbc:mysql://<host>:<port>/<database>");
dataSource.setMaxActive(10);
dataSource.setMaxIdle(5);
dataSource.setInitialSize(5);
dataSource.setValidationQuery("SELECT 1");
Code that needs a DataSource
can then use that.
Return false from the anonymous function:
$(xml).find("strengths").each(function() {
// Code
// To escape from this block based on a condition:
if (something) return false;
});
From the documentation of the each method:
Returning 'false' from within the each function completely stops the loop through all of the elements (this is like using a 'break' with a normal loop). Returning 'true' from within the loop skips to the next iteration (this is like using a 'continue' with a normal loop).
Try this:
SELECT * FROM [TestData] WHERE Id IN(SELECT DISTINCT MIN(Id) FROM [TestData] GROUP BY Product)
try this
$('#Selector_ID').attr("placeholder", "your Placeholder");
You never give any value to your strings in main
so they are empty, and thus obviously the function returns an empty string.
Replace:
string str1, str2, str3;
with:
string str1 = "the dog jumped over the fence";
string str2 = "the";
string str3 = "that";
Also, you have several problems in your replaceSubstring
function:
int index = s1.find(s2, 0);
s1.replace(index, s2.length(), s3);
std::string::find
returns a std::string::size_type
(aka. size_t
) not an int
. Two differences: size_t
is unsigned, and it's not necessarily the same size as an int
depending on your platform (eg. on 64 bits Linux or Windows size_t
is unsigned 64 bits while int
is signed 32 bits).s2
is not part of s1
? I'll leave it up to you to find how to fix that. Hint: std::string::npos
;)System.setProperty("javax.net.ssl.trustStore", path_to_your_jks_file);
For a specific column, there is an alternative with sapply
DF <- data.frame(A = letters[1:5],
B = letters[6:10],
C = c(2, 5, NA, 8, NA))
DF_NEW <- sapply(seq(1, nrow(DF)),
function(i) ifelse(is.na(DF[i,3]) ==
TRUE,
0,
DF[i,3]))
DF[,3] <- DF_NEW
DF
Try something like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
Write-Host $_.Exception.ToString()
}
The exception is in the $_
variable. You might explore $_
like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
$_ | fl * -Force
}
I think it will give you all the info you need.
My rule: if there is some data that is not displayed, try to use -force
.
I am using the following code in one of my current projects where i download data from the internet. It is all inside my activity class.
// ---------------------------- START DownloadFileAsync // -----------------------//
class DownloadFileAsync extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// DIALOG_DOWNLOAD_PROGRESS is defined as 0 at start of class
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
@Override
protected String doInBackground(String... urls) {
try {
String xmlUrl = urls[0];
URL u = new URL(xmlUrl);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
int lengthOfFile = c.getContentLength();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
long total = 0;
while ((len1 = in.read(buffer)) > 0) {
total += len1; // total = total + len1
publishProgress("" + (int) ((total * 100) / lengthOfFile));
xmlContent += buffer;
}
} catch (Exception e) {
Log.d("Downloader", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Retrieving latest announcements...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
Why not just iterate through the string?
a_string="abcd"
for letter in a_string:
print letter
returns
a
b
c
d
So, in pseudo-ish code, I would do this:
user_string = raw_input()
list_of_output = []
for letter in user_string:
list_of_output.append(morse_code_ify(letter))
output_string = "".join(list_of_output)
Note: the morse_code_ify
function is pseudo-code.
You definitely want to make a list of the characters you want to output rather than just concatenating on them on the end of some string. As stated above, it's O(n^2): bad. Just append them onto a list, and then use "".join(the_list)
.
As a side note: why are you removing the spaces? Why not just have morse_code_ify(" ")
return a "\n"
?
First, I'd like to apologize for bringing this question back up, but I felt that it could use another answer.
Derek Schultz is kind of correct. The '\b' character moves the printing cursor one character backwards, allowing you to overwrite the character that was printed there (it does not delete the entire line or even the character that was there unless you print new information on top). The following is an example of a progress bar using Java though it does not follow your format, it shows how to solve the core problem of overwriting characters (this has only been tested in Ubuntu 12.04 with Oracle's Java 7 on a 32-bit machine, but it should work on all Java systems):
public class BackSpaceCharacterTest
{
// the exception comes from the use of accessing the main thread
public static void main(String[] args) throws InterruptedException
{
/*
Notice the user of print as opposed to println:
the '\b' char cannot go over the new line char.
*/
System.out.print("Start[ ]");
System.out.flush(); // the flush method prints it to the screen
// 11 '\b' chars: 1 for the ']', the rest are for the spaces
System.out.print("\b\b\b\b\b\b\b\b\b\b\b");
System.out.flush();
Thread.sleep(500); // just to make it easy to see the changes
for(int i = 0; i < 10; i++)
{
System.out.print("."); //overwrites a space
System.out.flush();
Thread.sleep(100);
}
System.out.print("] Done\n"); //overwrites the ']' + adds chars
System.out.flush();
}
}
There is an overload with 3 arguments. Html.DropdownList(name, selectList, optionLabel)
Update: there was a typo in the below code snippet.
@Html.DropDownList("Cat", new SelectList(ViewBag.Categories,"ID", "CategoryName"), "-Select Category-")
For the validator use
@Html.ValidationMessage("Cat")
python3
, self explanatory I guess
from urllib.parse import urlparse, urlencode, parse_qsl
url = 'https://www.linkedin.com/jobs/search?keywords=engineer'
parsed = urlparse(url)
current_params = dict(parse_qsl(parsed.query))
new_params = {'location': 'United States'}
merged_params = urlencode({**current_params, **new_params})
parsed = parsed._replace(query=merged_params)
print(parsed.geturl())
# https://www.linkedin.com/jobs/search?keywords=engineer&location=United+States
Bad practice definitely. One reason is that it is not very 'user-friendly' for the fact that every JFrame
shows a new taskbar icon. Controlling multiple JFrame
s will have you ripping your hair out.
Personally, I would use ONE JFrame
for your kind of application. Methods of displaying multiple things is up to you, there are many. Canvas
es, JInternalFrame
, CardLayout
, even JPanel
s possibly.
Multiple JFrame objects = Pain, trouble, and problems.
What you put directly under src/main/java
is in the default package, at the root of the classpath. It's the same for resources put under src/main/resources
: they end up at the root of the classpath.
So the path of the resource is app-context.xml
, not main/resources/app-context.xml
.
I've found an issue happen to be with the Firewall. So, make sure your IP is whitelisted and the firewall does not block your connection. You can check connectivity with:
tsql -H somehost.com -p 1433
In my case, the output was:
Error 20009 (severity 9):
Unable to connect: Adaptive Server is unavailable or does not exist
OS error 111, "Connection refused"
There was a problem connecting to the server
You have to distinct sub routines and functions in vba... Generally (as far as I know), sub routines do not return anything and the surrounding parantheses are optional. For functions, you need to write the parantheses.
As for your example, MsgBox is not a function but a sub routine and therefore the parantheses are optional in that case. One exception with functions is, when you do not assign the returned value, or when the function does not consume a parameter, you can leave away the parantheses too.
This answer goes into a bit more detail, but basically you should be on the save side, when you provide parantheses for functions and leave them away for sub routines.
A char
is actually a numeric datatype - you can add one to an int
, for example. It's an unsigned short
(16 bits). In that regard you can just cast the output to, say, an int
to get the numeric value.
However you need to think a little more about what it is you're asking - not all characters are ASCII values. What output do you expect for â
, for example, or ?
?
Moreover, why do you want this? In this day and age you ought to be thinking about Unicode, not ASCII. If you let people know what your goal is, and how you intend to use this returned value, we can almost certainly let you know of a better way to achieve it.
You can try something like this-
as.vector(unlist(aframe$a2))
A good place to start is the sample application provided on the developer docs.
Take a look at other IME's to see what you should be aiming for. Some (like the official one) are open source.
You probably don't really want to be doing this, as it's going to be a nightmare to debug, but it seems to be possible. The key is the part where you assign by reference in the constructor.
$GLOBALS = array(
'MyNumber' => 1
);
class Foo {
protected $glob;
public function __construct() {
global $GLOBALS;
$this->glob =& $GLOBALS;
}
public function getGlob() {
return $this->glob['MyNumber'];
}
}
$f = new Foo;
echo $f->getGlob() . "\n";
$GLOBALS['MyNumber'] = 2;
echo $f->getGlob() . "\n";
The output will be
1
2
which indicates that it's being assigned by reference, not value.
As I said, it will be a nightmare to debug, so you really shouldn't do this. Have a read through the wikipedia article on encapsulation; basically, your object should ideally manage its own data and the methods in which that data is modified; even public properties are generally, IMHO, a bad idea.
Hello you can access your xampp localhost by
I find the second style (declaration + initialization in one go) superior. Reasons:
Of course, if the initialization value is different in different constructors (or even calculated in the constructor), you must do it in the constructor.
Let's dissect it. There are three parts:
cd
-- This is change directory command./d
-- This switch makes cd
change both drive and directory at once. Without it you would have to do cd %~d0 & cd %~p0
. (%~d0
Changs active drive, cd %~p0
change the directory).%~dp0
-- This can be dissected further into three parts:
%0
-- This represents zeroth parameter of your batch script. It expands into the name of the batch file itself.%~0
-- The ~
there strips double quotes ("
) around the expanded argument.%dp0
-- The d
and p
there are modifiers of the expansion. The d
forces addition of a drive letter and the p
adds full path.Swift 3
let secondviewController:UIViewController = self.storyboard?.instantiateViewController(withIdentifier: "StoryboardIdOfsecondviewController") as? SecondViewController
self.navigationController?.pushViewController(secondviewController, animated: true)
The more general answer is
UPDATE mysql.user SET host = {newhost} WHERE user = {youruser}
src
folder which is immediately inside the project's folder.
Note the hollow 'J' in the image. That indicates that the file is not part of a project.
I contacted GitHub to say that github.io-hosted SVGs are no longer displayed in GitHub READMEs. I received this reply:
We have had to disable svg image rendering on GitHub.com due to potential cross site scripting vulnerabilities.
If you are assigning default value for boolean fact then ensure that no quotes is used inside default().
- name: create bool default
set_fact:
name: "{{ my_bool | default(true) }}"
For other variables used the same method given in verified answer.
- name: Create user
user:
name: "{{ my_variable | default('default_value') }}"
You could actually use xlsread
to accomplish this. After first placing your sample data above in a file 'input_file.csv'
, here is an example for how you can get the numeric values, text values, and the raw data in the file from the three outputs from xlsread
:
>> [numData,textData,rawData] = xlsread('input_file.csv')
numData = % An array of the numeric values from the file
51.9358 4.1833
51.9354 4.1841
51.9352 4.1846
51.9343 4.1864
51.9343 4.1864
51.9341 4.1869
textData = % A cell array of strings for the text values from the file
'ABC'
'ABC'
'ABC'
'ABC'
'ABC'
'ABC'
rawData = % All the data from the file (numeric and text) in a cell array
'ABC' [51.9358] [4.1833]
'ABC' [51.9354] [4.1841]
'ABC' [51.9352] [4.1846]
'ABC' [51.9343] [4.1864]
'ABC' [51.9343] [4.1864]
'ABC' [51.9341] [4.1869]
You can then perform whatever processing you need to on the numeric data, then resave a subset of the rows of data to a new file using xlswrite
. Here's an example:
index = sqrt(sum(numData.^2,2)) >= 50; % Find the rows where the point is
% at a distance of 50 or greater
% from the origin
xlswrite('output_file.csv',rawData(index,:)); % Write those rows to a new file
You didn't provide many relevant details so I will guess that you called getInvoice
and then you used result object to set some values and call save
with assumption that your object changes will be saved.
However, persist
operation is intended for brand new transient objects and it fails if id is already assigned. In your case you probably want to call saveOrUpdate
instead of persist
.
You can find some discussion and references here "detached entity passed to persist error" with JPA/EJB code
jQuery does only make some regexp checking before calling the native browser method window.JSON.parse()
. If that is not available, it uses eval()
or more exactly new Function()
to create a Javascript object.
The opposite of JSON.parse()
is JSON.stringify()
which serializes a Javascript object into a string. jQuery does not have functionality of its own for that, you have to use the browser built-in version or json2.js
from http://www.json.org
JSON.stringify()
is available in all major browsers, but to be compatible with older browsers you still need that fallback.
Yes, definietly requests is great package to use in something related to HTTP requests. but we need to be careful with the encoding type of the incoming data as well below is an example which explains the difference
from requests import get
# case when the response is byte array
url = 'some_image_url'
response = get(url)
with open('output', 'wb') as file:
file.write(response.content)
# case when the response is text
# Here unlikely if the reponse content is of type **iso-8859-1** we will have to override the response encoding
url = 'some_page_url'
response = get(url)
# override encoding by real educated guess as provided by chardet
r.encoding = r.apparent_encoding
with open('output', 'w', encoding='utf-8') as file:
file.write(response.content)
I got the same error but I solved by using regsvr32.exe in C:\Windows\SysWOW64. Because we use x64 system. So if your machine is also x64, the ocx/dll must registered also with regsvr32 x64 version
But this is obviously performing a 'string' comparison
No. The string will be automatically cast into a DATETIME value.
See 11.2. Type Conversion in Expression Evaluation.
When an operator is used with operands of different types, type conversion occurs to make the operands compatible. Some conversions occur implicitly. For example, MySQL automatically converts numbers to strings as necessary, and vice versa.
var d = new Date("Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)");
document.getElementById("demo").innerHTML = d.toLocaleDateString();
I think this is simple enough
uint8_t reverse(uint8_t a)
{
unsigned w = ((a << 7) & 0x0880) | ((a << 5) & 0x0440) | ((a << 3) & 0x0220) | ((a << 1) & 0x0110);
return static_cast<uint8_t>(w | (w>>8));
}
or
uint8_t reverse(uint8_t a)
{
unsigned w = ((a & 0x11) << 7) | ((a & 0x22) << 5) | ((a & 0x44) << 3) | ((a & 0x88) << 1);
return static_cast<uint8_t>(w | (w>>8));
}
Map.Entry
Java 1.6 and upper have two implementation of Map.Entry
interface pairing a key with a value:
For example
Map.Entry < Month, Boolean > pair =
new AbstractMap.SimpleImmutableEntry <>(
Month.AUGUST ,
Boolean.TRUE
)
;
pair.toString(): AUGUST=true
I use it when need to store pairs (like size and object collection).
This piece from my production code:
public Map<L1Risk, Map.Entry<int[], Map<L2Risk, Map.Entry<int[], Map<L3Risk, List<Event>>>>>>
getEventTable(RiskClassifier classifier) {
Map<L1Risk, Map.Entry<int[], Map<L2Risk, Map.Entry<int[], Map<L3Risk, List<Event>>>>>> l1s = new HashMap<>();
Map<L2Risk, Map.Entry<int[], Map<L3Risk, List<Event>>>> l2s = new HashMap<>();
Map<L3Risk, List<Event>> l3s = new HashMap<>();
List<Event> events = new ArrayList<>();
...
map.put(l3s, events);
map.put(l2s, new AbstractMap.SimpleImmutableEntry<>(l3Size, l3s));
map.put(l1s, new AbstractMap.SimpleImmutableEntry<>(l2Size, l2s));
}
Code looks complicated but instead of Map.Entry you limited to array of object (with size 2) and lose type checks...
You can use either one of these to check null, whitespace and empty strings.
WHERE COLUMN <> ''
WHERE LEN(COLUMN) > 0
WHERE NULLIF(LTRIM(RTRIM(COLUMN)), '') IS NOT NULL
Yes, It is possible,
Just add a class like anyclass
and give some CSS style. Live
.anyClass {
height:150px;
overflow-y: scroll;
}
.anyClass {_x000D_
height:150px;_x000D_
overflow-y: scroll;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class=" col-md-2">_x000D_
<ul class="nav nav-pills nav-stacked anyClass">_x000D_
<li class="nav-item">_x000D_
<a class="nav-link active" href="#">Active</a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href="#">Link</a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href="#">Link</a>_x000D_
</li><li class="nav-item">_x000D_
<a class="nav-link" href="#">Link</a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href="#">Link</a>_x000D_
</li><li class="nav-item">_x000D_
<a class="nav-link" href="#">Link</a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href="#">Link</a>_x000D_
</li><li class="nav-item">_x000D_
<a class="nav-link" href="#">Link</a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href="#">Link</a>_x000D_
</li><li class="nav-item">_x000D_
<a class="nav-link" href="#">Link</a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href="#">Link</a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link disabled" href="#">Disabled</a>_x000D_
</li>_x000D_
</ul>_x000D_
</div>
_x000D_
I had a different approach , used bootstrap panel to show it little more rich. Just to help someone and improve the answer.
.text-on-pannel {_x000D_
background: #fff none repeat scroll 0 0;_x000D_
height: auto;_x000D_
margin-left: 20px;_x000D_
padding: 3px 5px;_x000D_
position: absolute;_x000D_
margin-top: -47px;_x000D_
border: 1px solid #337ab7;_x000D_
border-radius: 8px;_x000D_
}_x000D_
_x000D_
.panel {_x000D_
/* for text on pannel */_x000D_
margin-top: 27px !important;_x000D_
}_x000D_
_x000D_
.panel-body {_x000D_
padding-top: 30px !important;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="container">_x000D_
<div class="panel panel-primary">_x000D_
<div class="panel-body">_x000D_
<h3 class="text-on-pannel text-primary"><strong class="text-uppercase"> Title </strong></h3>_x000D_
<p> Your Code </p>_x000D_
</div>_x000D_
</div>_x000D_
<div>
_x000D_
Note: We need to change the styles in order to use different header size.
since you are using jquery
library, i would advise you utilize the reset()
method.
Firstly, add an id attribute to the form tag
<form id='myForm'>
Then on completion, clear your input fields as:
$('#myForm')[0].reset();
You can simply traverse through the object and return if a match is found.
Here is the code:
returnKeyforValue : function() {
var JsonObj= { "one":1, "two":2, "three":3, "four":4, "five":5 };
for (key in JsonObj) {
if(JsonObj[key] === "Keyvalue") {
return key;
}
}
}
There are two ways to go about doing this.
Create a state in the constructor that contains the text input. Attach an onChange event to the input box that updates state each time. Then onClick you could just alert the state object.
handleClick: function() { alert(this.refs.myInput.value); },
long second = TimeUnit.MILLISECONDS.toSeconds(millis);
long minute = TimeUnit.MILLISECONDS.toMinutes(millis);
long hour = TimeUnit.MILLISECONDS.toHours(millis);
millis -= TimeUnit.SECONDS.toMillis(second);
return String.format("%02d:%02d:%02d:%d", hour, minute, second, millis);
For win7 chrome can be found at:
C:\Users\[UserName]\AppData\Local\Google\Chrome\Application\chrome.exe
For VS2017 click the little down arrow next to the run in debug/release mode button to find the "browse with..." option.
Static member functions must refer to static variables of that class. So in your case,
static void CP_StringToPString( std::string& inString, unsigned char *outString);
Since your member function CP_StringToPstring
is static, the parameters in that function, inString
and outString
should be declared as static too.
The static member functions does not refer to the object that it is working on but the variables your declared refers to its current object so it return error.
You could either remove the static from the member function or add static while declaring the parameters you used for the member function as static too.
Basically we had to enable TLS 1.2 for .NET 4.x. Making this registry changed worked for me, and stopped the event log filling up with the Schannel error.
More information on the answer can be found here
Enable TLS 1.2 at the system (SCHANNEL) level:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2]
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001
(equivalent keys are probably also available for other TLS versions)
Tell .NET Framework to use the system TLS versions:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
This may not be desirable for edge cases where .NET Framework 4.x applications need to have different protocols enabled and disabled than the OS does.
I had similar issue when I had to install from github repo, but did not want to install git , etc.
The simple way to do it is using zip archive of the package. Add /zipball/master
to the repo URL:
$ pip install https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
Downloading/unpacking https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
Downloading master
Running setup.py egg_info for package from https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
Installing collected packages: django-debug-toolbar-mongo
Running setup.py install for django-debug-toolbar-mongo
Successfully installed django-debug-toolbar-mongo
Cleaning up...
This way you will make pip work with github source repositories.
Got the same problem today. Fixed it by changing the jdk location in the project structure from \java\jdk1.7.0_05
to \java\jdk1.7.0_25
(which I didn´t know existed until now).
I´m using Android Studio 0.8.6.
Yes you can. Just check my fiddle for clarification. For demo purpose i kept the code in fiddle at same location. You can extract that code as shown in two different Javascript files and load them in html file.
https://jsfiddle.net/mvora/mrLmkxmo/
/******** PUT THIS CODE IN ONE JS FILE *******/
var secondFileFuntion = function(){
this.name = 'XYZ';
}
secondFileFuntion.prototype.getSurname = function(){
return 'ABC';
}
var secondFileObject = new secondFileFuntion();
/******** Till Here *******/
/******** PUT THIS CODE IN SECOND JS FILE *******/
function firstFileFunction(){
var name = secondFileObject.name;
var surname = secondFileObject.getSurname()
alert(name);
alert(surname );
}
firstFileFunction();
If you make an object using the constructor function and trying access the property or method from it in second file, it will give you the access of properties which are present in another file.
Just take care of sequence of including these files in index.html
Just don't include the columns that you want to use the default value for in your insert statement. For instance:
INSERT INTO table1 (field1, field3) VALUES (5, 10);
...will take the default values for field2
and field4
, and assign 5 to field1
and 10 to field3
.
Since my other answer was obviously not well understood, here's a second attempt:
There's two approaches to answer the question.
Forget about the :after
pseudo-selector, and go for something like
.pdflink {
min-height: 20px;
padding-right: 10px;
background-position: right bottom;
background-size: 10px 20px;
background-repeat: no-repeat;
}
The question is: Can you style generated content? The answer is: No, you can't. There's been a lengthy discussion on the W3C mailing list on this issue, but no solution so far.
Generated content is rendered into a generated box, and you can style that box, but not the content as such. Different browsers show very different behaviour
#foo {content: url("bar.jpg"); width: 42px; height:42px;} #foo::before {content: url("bar.jpg"); width: 42px; height:42px;}
Chrome resizes the first one, but uses the intrinsic dimensions of the image for the second
firefox and ie don't support the first, and use intrinsic dimensions for the second
opera uses intrinsic dimensions for both cases
(from http://lists.w3.org/Archives/Public/www-style/2011Nov/0451.html )
Similarly, browsers show very different results on things like http://jsfiddle.net/Nwupm/1/ , where more than one element is generated. Keep in mind that CSS3 is still in early development stage, and this issue has yet to be solved.
Take a look at OPENROWSET
, and do something like:
SELECT * INTO #TEMPTABLE FROM OPENROWSET('SQLNCLI'
, 'Server=(local)\SQL2008;Trusted_Connection=yes;',
'SELECT * FROM ' + @tableName)
The technique i used before discovering .Any()
:
var hasJohn = (from customer in list
where customer.FirstName == "John"
select customer).FirstOrDefault() != null;
Often our databases are really big and the take time to take dump directly from remote machine to other machine as our friends other have suggested above.
In such cases what you can do is to take the dump on remote machine using MYSQLDUMP Command
MYSQLDUMP -uuser -p --all-databases > file_name.sql
and than transfer that file from remote server to your machine using Linux SCP Command
scp user@remote_ip:~/mysql_dump_file_name.sql ./
This worked for me, it works in firefox, ie and chrome.
var content = "This is a test Message";
var contentHtml = [
'<div><b>',
'TestReport',
'<button style="float:right; margin-right:10px;"',
'id="printButton" onclick="printDocument()">Print</button></div>',
content
].join('');
var printWindow = window.open();
printWindow.document.write('<!DOCTYPE HTML><html><head<title>Reports</title>',
'<script>function printDocument() {',
'window.focus();',
'window.print();',
'window.close();',
'}',
'</script>');
printWindow.document.write("stylesheet link here");
printWindow.document.write('</head><body>');
printWindow.document.write(contentHtml);
printWindow.document.write('</body>');
printWindow.document.write('</html>');
printWindow.document.close();
If you're writing for Android you can do this...
android.text.HtmlCompat.fromHtml(instruction, HtmlCompat.FROM_HTML_MODE_LEGACY).toString()
As for the workaround (without using non-portable -P
), you can temporary replace a new-line character with the different one and change it back, e.g.:
grep -o "_foo_" <(paste -sd_ file) | tr -d '_'
Basically it's looking for exact match _foo_
where _
means \n
(so __
= \n\n
). You don't have to translate it back by tr '_' '\n'
, as each pattern would be printed in the new line anyway, so removing _
is enough.
Working fine chartJs sector onclick
ChartJS : pie Chart - Add options "onclick"
options: {
legend: {
display: false
},
'onClick' : function (evt, item) {
console.log ('legend onClick', evt);
console.log('legd item', item);
}
}
There is, however, no guarantee that the output of SDTOUT
and STDERR
are interweaved line-by-line in timely order, using the POSIX
redirect merge syntax.
If an application uses buffered output, it may happen that the text of one stream is inserted in the other at a buffer boundary, which may appear in the middle of a text line.
A dedicated console output logger (I.e. the "StdOut/StdErr Logger"
by 'LoRd MuldeR'
) may be more reliable for such a task.
Try doing something like this:
Pattern p = Pattern.compile("^.+(\\d+).+");
Matcher m = p.matcher("Testing123Testing");
if (m.find()) {
System.out.println(m.group(1));
}
The following are some comparisons:
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");
System.out.println(s1 == s2); //true
System.out.println(s1.equals(s2)); //true
System.out.println(s1 == s3); //false
System.out.println(s1.equals(s3)); //true
s3 = s3.intern();
System.out.println(s1 == s3); //true
System.out.println(s1.equals(s3)); //true
When intern()
is called the reference is changed.
For your case, just use:
var votevalue = +$(this).data('votevalue');
There are some ways to convert string to number in javascript.
The best way:
var str = "1";
var num = +str; //simple enough and work with both int and float
You also can:
var str = "1";
var num = Number(str); //without new. work with both int and float
or
var str = "1";
var num = parseInt(str,10); //for integer number
var num = parseFloat(str); //for float number
DON'T:
var str = "1";
var num = new Number(str); //num will be an object. typeof num == 'object'
Use parseInt only for special case, for example
var str = "ff";
var num = parseInt(str,16); //255
var str = "0xff";
var num = parseInt(str); //255
In the viewmodel you can have:
public MyEnumType SelectedMyEnumType
{
get { return _selectedMyEnumType; }
set {
_selectedMyEnumType = value;
OnPropertyChanged("SelectedMyEnumType");
}
}
public IEnumerable<MyEnumType> MyEnumTypeValues
{
get
{
return Enum.GetValues(typeof(MyEnumType))
.Cast<MyEnumType>();
}
}
In XAML the ItemSource
binds to MyEnumTypeValues
and SelectedItem
binds to SelectedMyEnumType
.
<ComboBox SelectedItem="{Binding SelectedMyEnumType}" ItemsSource="{Binding MyEnumTypeValues}"></ComboBox>
Some solution is first to copy() the file (as mentioned above) and when the destination file exists - unlink() file from previous localization. Additionally you can validate the MD5 checksum before unlinking to be sure
try this:
$(window).unbind('scroll');
it works in my project
What I usually do is use clock()
or time()
from the time
library. clock
measures interpreter time, while time
measures system time. Additional caveats can be found in the docs.
For example,
def fn():
st = time()
dostuff()
print 'fn took %.2f seconds' % (time() - st)
Or alternatively, you can use timeit
. I often use the time
approach due to how fast I can bang it out, but if you're timing an isolate-able piece of code, timeit
comes in handy.
From the timeit docs,
def test():
"Stupid test function"
L = []
for i in range(100):
L.append(i)
if __name__=='__main__':
from timeit import Timer
t = Timer("test()", "from __main__ import test")
print t.timeit()
Then to convert to minutes, you can simply divide by 60. If you want the script runtime in an easily readable format, whether it's seconds or days, you can convert to a timedelta
and str
it:
runtime = time() - st
print 'runtime:', timedelta(seconds=runtime)
and that'll print out something of the form [D day[s], ][H]H:MM:SS[.UUUUUU]
. You can check out the timedelta docs.
And finally, if what you're actually after is profiling your code, Python makes available the profile library as well.
As an addendum to @xmechanix's answer, I noticed through writing the contents to a file:
echo | set /p dummyName=Hello World > somefile.txt
That this will add an extra space at the end of the printed string, which can be inconvenient, specially since we're trying to avoid adding a new line (another whitespace character) to the end of the string.
Fortunately, quoting the string to be printed, i.e. using:
echo | set /p dummyName="Hello World" > somefile.txt
Will print the string without any newline or space character at the end.
i wrote a simple function for this:
Function (stringVar param)
(
Local stringVar oneChar := '0';
Local numberVar strLen := Length(param);
Local numberVar index := strLen;
oneChar = param[strLen];
while index > 0 and oneChar = '0' do
(
oneChar := param[index];
index := index - 1;
);
Left(param , index + 1);
)
I may be just repeating everyone else but I do have a pretty piece of code that extends the DependencyObject class with a method FindChild() that will get you the child by type and name. Just include and use.
public static class UIChildFinder
{
public static DependencyObject FindChild(this DependencyObject reference, string childName, Type childType)
{
DependencyObject foundChild = null;
if (reference != null)
{
int childrenCount = VisualTreeHelper.GetChildrenCount(reference);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(reference, i);
// If the child is not of the request child type child
if (child.GetType() != childType)
{
// recursively drill down the tree
foundChild = FindChild(child, childName, childType);
}
else if (!string.IsNullOrEmpty(childName))
{
var frameworkElement = child as FrameworkElement;
// If the child's name is set for search
if (frameworkElement != null && frameworkElement.Name == childName)
{
// if the child's name is of the request name
foundChild = child;
break;
}
}
else
{
// child element found.
foundChild = child;
break;
}
}
}
return foundChild;
}
}
Hope you find it useful.
I found a clean solution, which affects only rest controllers.
@SpringBootApplication
public class WebApp extends SpringBootServletInitializer {
@Autowired
private ApplicationContext context;
@Bean
public ServletRegistrationBean restApi() {
XmlWebApplicationContext applicationContext = new XmlWebApplicationContext();
applicationContext.setParent(context);
applicationContext.setConfigLocation("classpath:/META-INF/rest.xml");
DispatcherServlet dispatcherServlet = new DispatcherServlet();
dispatcherServlet.setApplicationContext(applicationContext);
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(dispatcherServlet, "/rest/*");
servletRegistrationBean.setName("restApi");
return servletRegistrationBean;
}
static public void main(String[] args) throws Exception {
SpringApplication.run(WebApp.class,args);
}
}
Spring boot will register two dispatcher servlets - default dispatcherServlet
for controllers, and restApi
dispatcher for @RestControllers
defined in rest.xml
:
2016-06-07 09:06:16.205 INFO 17270 --- [ main] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'restApi' to [/rest/*]
2016-06-07 09:06:16.206 INFO 17270 --- [ main] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
The example rest.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="org.example.web.rest"/>
<mvc:annotation-driven/>
<!-- Configure to plugin JSON as request and response in method handler -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonMessageConverter"/>
</list>
</property>
</bean>
<!-- Configure bean to convert JSON to POJO and vice versa -->
<bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</bean>
</beans>
But, you're not limited to:
XmlWebApplicationContext
, you may use any else context type available, ie. AnnotationConfigWebApplicationContext
, GenericWebApplicationContext
, GroovyWebApplicationContext
, ...jsonMessageConverter
, messageConverters
beans in rest context, they may be defined in parent contextyou can do it by two ways
import file_name
exec(open('file_name').read())
but make sure that file should be stored where your program is running
I found this:
EXECUTE xp_regread
@rootkey = 'HKEY_LOCAL_MACHINE',
@key = 'SOFTWARE\Microsoft\Microsoft SQL Server',
@value_name = 'InstalledInstances'
That will give you list of all instances installed in your server.
The
ServerName
property of theSERVERPROPERTY
function and@@SERVERNAME
return similar information. TheServerName
property provides the Windows server and instance name that together make up the unique server instance.@@SERVERNAME
provides the currently configured local server name.
And Microsoft example for current server is:
SELECT CONVERT(sysname, SERVERPROPERTY('servername'));
This scenario is useful when there are multiple instances of SQL Server installed on a Windows server, and the client must open another connection to the same instance used by the current connection.
string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g,'_');
Alternatively, to change all characters except numbers and letters, try:
string = string.replace(/[^a-zA-Z0-9]/g,'_');
Follow these Steps:
1: Enter:
git reflog show
This will display all the Commit history, you need to select the sha-1 that has the last commit that you want to get back
2: create a branch name with the Sha-1 ID you selected eg: 8c87714
git branch your-branch-name 8c87714
You can see the button "Code" in the attached screenshot, press it and you can get your code in many different languages including PHP cURL
Use adb kill-server
. It should helps.
or
adb -s emulator-5554 emu kill
, where emulator-5554
is the emulator name.
For Ubuntu users I found a good command to stop all running emulators (Thanks to @uwe)
adb devices | grep emulator | cut -f1 | while read line; do adb -s $line emu kill; done
I have added for this:
server.compression.enabled=true
server.compression.min-response-size=2048
server.compression.mime-types=application/json,application/xml,text/html,text/xml,text/plain
taken from http://bisaga.com/blog/programming/web-compression-on-spring-boot-application/
in your location block you can do:
location / {
try_files $uri $uri/index.html;
}
which will tell ngingx to look for a file with the exact name given first, and if none such file is found it will try uri/index.html. So if a request for https://www.example.com/ comes it it would look for an exact file match first, and not finding that would then check for index.html
Try imaskjs. It has Number, RegExp and other masks. Very simple to extend.
It won't get much cleaner. This is not a very clean thing to do. At best (which would be more readable anyway, since the condition for the break
is up there with the while
), you could create a variable result = None
and loop while it is None
. You should also adjust the variables and you can replace continue
with the semantically perhaps correct pass
(you don't care if an error occurs, you just want to ignore it) and drop the break
- this also gets the rest of the code, which only executes once, out of the loop. Also note that bare except:
clauses are evil for reasons given in the documentation.
Example incorporating all of the above:
result = None
while result is None:
try:
# connect
result = get_data(...)
except:
pass
# other code that uses result but is not involved in getting it
when i generate rails g controller i got the same error. After that when do the following changes on Gemfile(in rails 4) everything went smooth.The changes i made was
gem 'execjs'
gem 'therubyracer', "0.11.4"
After that i can able to run the server and able to do all basic operations on the application.
If you are currently writing the application, than the answer is to use System.currentTimeMillis or System.nanoTime serve the purpose as pointed by people above.
But if you have already written the code, and you don't want to change it its better to use Spring's method interceptors. So for instance your service is :
public class MyService {
public void doSomething() {
for (int i = 1; i < 10000; i++) {
System.out.println("i=" + i);
}
}
}
To avoid changing the service, you can write your own method interceptor:
public class ServiceMethodInterceptor implements MethodInterceptor {
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
long startTime = System.currentTimeMillis();
Object result = methodInvocation.proceed();
long duration = System.currentTimeMillis() - startTime;
Method method = methodInvocation.getMethod();
String methodName = method.getDeclaringClass().getName() + "." + method.getName();
System.out.println("Method '" + methodName + "' took " + duration + " milliseconds to run");
return null;
}
}
Also there are open source APIs available for Java, e.g. BTrace. or Netbeans profiler as suggested above by @bakkal and @Saikikos. Thanks.
If you are applying to the way Project Cleanup and your project still error.
You can go to tab Build Phases and then Find Check Pods Manifest.lock
and remove the script.
Then type command to remove folder Pods
like that rm -rf Pods
and then you need to remove Podfile.lock by command rm Podfile.lock
Probably, base on a situation you can remove file your_project_name.xcworkspace
Finally, you need the command to install Pod pod install --repo-update
.
Hopefully, this solution comes up with you. Happy coding :)
Java compiler imports 3 packages by default.
1. The package without name
2. The java.lang package(That's why you can declare String, Integer, System classes without import)
3. The current package (current file's package)
That's why you don't need to declare import statement for the java.lang
package.
To dismiss or cancel AlertDialog.Builder
dialog.setNegativeButton("?????", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
you call dismiss() on the dialog interface
In Rails 2, I would have written:
validates_uniqueness_of :zipcode, :scope => :recorded_at
In Rails 3:
validates :zipcode, :uniqueness => {:scope => :recorded_at}
For multiple attributes:
validates :zipcode, :uniqueness => {:scope => [:recorded_at, :something_else]}
If want to remove the word from only the start of the string, then you could do:
string[string.startswith(prefix) and len(prefix):]
Where string is your string variable and prefix is the prefix you want to remove from your string variable.
For example:
>>> papa = "papa is a good man. papa is the best."
>>> prefix = 'papa'
>>> papa[papa.startswith(prefix) and len(prefix):]
' is a good man. papa is the best.'
If the input happens to be in a bootstrap modal dialog, the answer is different. Copying from How to Set focus to first text input in a bootstrap modal after shown this is what is required:
$('#myModal').on('shown.bs.modal', function () {
$('#textareaID').focus();
})
They're still types, so I always use the same naming conventions I use for classes.
I definitely would frown on putting "Class" or "Enum" in a name. If you have both a FruitClass
and a FruitEnum
then something else is wrong and you need more descriptive names. I'm trying to think about the kind of code that would lead to needing both, and it seems like there should be a Fruit
base class with subtypes instead of an enum. (That's just my own speculation though, you may have a different situation than what I'm imagining.)
The best reference that I can find for naming constants comes from the Variables tutorial:
If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. The names gearRatio and currentGear are prime examples of this convention. If your variable stores a constant value, such as static final int NUM_GEARS = 6, the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere.
Upgrade to version 1.6 of FPDF.
Try this code
import re
re.sub(r'[^\x00-\x7F]+','','paste your string here').decode('utf-8','ignore').strip()
#import modules
import os
_CURRENT_DIR = '.'
def rec_tree_traverse(curr_dir, indent):
"recurcive function to traverse the directory"
#print "[traverse_tree]"
try :
dfList = [os.path.join(curr_dir, f_or_d) for f_or_d in os.listdir(curr_dir)]
except:
print "wrong path name/directory name"
return
for file_or_dir in dfList:
if os.path.isdir(file_or_dir):
#print "dir : ",
print indent, file_or_dir,"\\"
rec_tree_traverse(file_or_dir, indent*2)
if os.path.isfile(file_or_dir):
#print "file : ",
print indent, file_or_dir
#end if for loop
#end of traverse_tree()
def main():
base_dir = _CURRENT_DIR
rec_tree_traverse(base_dir," ")
raw_input("enter any key to exit....")
#end of main()
if __name__ == '__main__':
main()
Here are a few resources on commit frequency, commit messages, project structure, what to put under source control and other general guidelines:
These Stack Overflow questions also contain some useful information that may be of interest:
Regarding the basic Subversion concepts such as branching and tagging, I think this is very well explained in the Subversion book.
As you may realize after reading up a bit more on the subject, people's opinions on what's best practice in this area are often varying and sometimes conflicting. I think the best option for you is to read about what other people are doing and pick the guidelines and practices that you feel make most sense to you.
I don't think it's a good idea to adopt a practice if you do not understand the purpose of it or don't agree to the rationale behind it. So don't follow any advice blindly, but rather make up your own mind about what you think will work best for you. Also, experimenting with different ways of doing things is a good way to learn and find out how you best like to work. A good example of this is how you structure the repository. There is no right or wrong way to do it, and it's often hard to know which way you prefer until you have actually tried them in practice.
You can use the IPython.display.clear_output to clear the output as mentioned in cel's answer. I would add that for me the best solution was to use this combination of parameters to print without any "shakiness" of the notebook:
from IPython.display import clear_output
for i in range(10):
clear_output(wait=True)
print(i, flush=True)
This has been covered here quite well, but if you REALLY need even better performance than anything listed here, you can use this approach that uses strtok
.
$Names_Keys = [];
$Name = strtok(file_get_contents($file), "\n");
while ($Name !== false) {
$Names_Keys[$Name] = 0;
$Name = strtok("\n");
}
Note, this assumes your file is saved with \n
as the newline character (you can update that as need be), and it also stores the words/names/lines as the array keys instead of the values, so that you can use it as a lookup table, allowing the use of isset
(much, much faster), instead of in_array
.
Check out this great tutorial on favicons and browser support.
As others suggested, the problem is when windows.h
is included before WinSock2.h
. Because windows.h
includes winsock.h
. You can not use both WinSock2.h
and winsock.h
.
Solutions:
Include WinSock2.h
before windows.h
. In the case of precompiled headers, you should solve it there. In the case of simple project, it is easy. However in big projects (especially when writing portable code, without precompiled headers) it can be very hard, because when your header with WinSock2.h
is included, windows.h
can be already included from some other header/implementation file.
Define WIN32_LEAN_AND_MEAN
before windows.h
or project wide. But it will exclude many other stuff you may need and you should include it by your own.
Define _WINSOCKAPI_
before windows.h
or project wide. But when you include WinSock2.h
you get macro redefinition warning.
Use windows.h
instead of WinSock2.h
when winsock.h
is enough for your project (in most cases it is). This will probably result in longer compilation time but solves any errors/warnings.
you can try javascript
<A HREF="javascript:history.go(-1)">
refer JavaScript Back Button
EDIT
to display url of refer http://www.javascriptkit.com/javatutors/crossmenu2.shtml
and send the element a itself in onmouseover as follow
function showtext(thetext) {_x000D_
if (!document.getElementById)_x000D_
return_x000D_
textcontainerobj = document.getElementById("tabledescription")_x000D_
browserdetect = textcontainerobj.filters ? "ie" : typeof textcontainerobj.style.MozOpacity == "string" ? "mozilla" : ""_x000D_
instantset(baseopacity)_x000D_
document.getElementById("tabledescription").innerHTML = thetext.href_x000D_
highlighting = setInterval("gradualfade(textcontainerobj)", 50)_x000D_
}
_x000D_
<a href="http://www.javascriptkit.com" onMouseover="showtext(this)" onMouseout="hidetext()">JavaScript Kit</a>
_x000D_
check jsfiddle
Are you mixing C and C++? One issue that can occur is that the declarations in the .h
file for a .c
file need to be surrounded by:
#if defined(__cplusplus)
extern "C" { // Make sure we have C-declarations in C++ programs
#endif
and:
#if defined(__cplusplus)
}
#endif
Note: if unable / unwilling to modify the .h
file(s) in question, you can surround their inclusion with extern "C"
:
extern "C" {
#include <abc.h>
} //extern
if (DateTime.TryParse(datetoparser, out dateValue))
{
string formatedDate = dateValue.ToString("yyyy-MM-dd");
}
.success()
only gets called if your webserver responds with a 200 OK HTTP header - basically when everything is fine.
The callbacks attached to done() will be fired when the deferred is resolved. The callbacks attached to fail() will be fired when the deferred is rejected.
promise.done(doneCallback).fail(failCallback)
.done() has only one callback and it is the success callback
System.Windows.Forms.Clipboard.SetText
(Windows Forms) or System.Windows.Clipboard.SetText
(WPF)
Postgres allows:
UPDATE dummy
SET customer=subquery.customer,
address=subquery.address,
partn=subquery.partn
FROM (SELECT address_id, customer, address, partn
FROM /* big hairy SQL */ ...) AS subquery
WHERE dummy.address_id=subquery.address_id;
This syntax is not standard SQL, but it is much more convenient for this type of query than standard SQL. I believe Oracle (at least) accepts something similar.
sed -i.bak 's/\(aaa=\).*/\1"xxx"/g' your_file
The latest plugin is tidy2, which can be installed through Plugins>Plugin Manager>Show Plugin Manager.
I suggest editing config 1 and setting quote-marks: no, especially if you have script that makes use of quotes.
Also, tidying more than once can result in inserting ampersands the first time and then replacing the ampersands the second time. You may want to play with the config to get it to where you need it.
Use:
subA.tick_params(labelsize=6)
in my case, I had a line Class.forName("com.mysql.jdbc.Driver"); after removing this line code works fine if you have any line for loading "com.mysql.jdbc.Driver" remove it, it doesn't require any more
The answers abow didnt really work for me, i had a click event on the wrapper and ie 7,8,9,10 ignored the z-index, so my fix was giving the wrapper a background-color and it all of a sudden worked. Al though it was suppose to be transparent, so i defined the wrapper with the background-color white, and then opacity 0.01, and now it works. I also have the functions above, so it could be a combination.
I dont know why it works, im just happy it does.
This has been mentioned in other questions, but ctrl + [ is an equivalent to ESC on all keyboards.
If you want to return some value then wrap your statement in function
function my_function(){
return my_thing;
}
Problem is with the statement on the 1st line if you are trying to use PHP
var ask = confirm ('".$message."');
IF you are trying to use PHP you should use
var ask = confirm (<?php echo "'".$message."'" ?>); //now message with be the javascript string!!
You can use this but there remains a security issue
<script type="text/javascript">
function fnc1()
{
var a=window.location.href;
username="p";
password=1234;
window.open(a+'?username='+username+'&password='+password,"");
}
</script>
<input type="button" onclick="fnc1()" />
<input type="text" id="atext" />
Just add
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
to the .htaccess
file in the root of the website you are trying to connect with.
You need to add junit
library to the classpath of your project. There are several choices to achieve it depending on your development setup.
Command line: In the case of command line invocations, you will have to add junit.jar
to the classpath of your application with java -cp /path/to/junit.jar
. Take a look at the answers here.
Using eclipse: Eclipse distributions are bundled with this library and this is how you can use it for your project. Right click on the eclipse project and navigate:
Properties -> Java Build Path -> Libraries -> Add Library -> JUnit -> Junit 3/4
In the scenarios where you want to use a different version of the jar, instead of clicking on Add Library above you should click on Add External Jar and locate the library on the file system.
This little change help with this problem.
I have Solution with 3 project.
connectionString="metadata=res://*/Model.Project.csdl|res://*/Model.Project.ssdl|res://*/Model.Project.msl;
change to
connectionString="metadata=res://*/;
As stated above, many languages are available for developing in Android. Java, C, Scala, C++, several scripting languages etc. Thanks to Mono you are also able to develop using C# and the .Net framework. Here you have some speedcomparisions: http://www.youtube.com/watch?v=It8xPqkKxis
"ABCDEFG".chars.each do |char|
puts char
end
also
"ABCDEFG".each_char {|char| p char}
Ruby version >2.5.1
var consolidatedChildren =
from c in children
group c by new
{
c.School,
c.Friend,
c.FavoriteColor,
} into gcs
select new ConsolidatedChild()
{
School = gcs.Key.School,
Friend = gcs.Key.Friend,
FavoriteColor = gcs.Key.FavoriteColor,
Children = gcs.ToList(),
};
var consolidatedChildren =
children
.GroupBy(c => new
{
c.School,
c.Friend,
c.FavoriteColor,
})
.Select(gcs => new ConsolidatedChild()
{
School = gcs.Key.School,
Friend = gcs.Key.Friend,
FavoriteColor = gcs.Key.FavoriteColor,
Children = gcs.ToList(),
});
<form action="" method="post" name="register_form" id="register_form" enctype="multipart/form-data">
<div class="text-input">
<label>Gender: </label>
<input class="form-control" type="radio" name="gender" id="male" value="male" />
<label for="male">Male</label>
<input class="form-control" type="radio" name="gender" id="female" value="female" />
<label for="female">Female</label>
</div>
<div class="text-input" align="center">
<input type="submit" name="register" value="Submit" onclick="return radioValidation();" />
</div>
</form>
<script type="text/javascript">
function radioValidation(){
var gender = document.getElementsByName('gender');
var genValue = false;
for(var i=0; i<gender.length;i++){
if(gender[i].checked == true){
genValue = true;
}
}
if(!genValue){
alert("Please Choose the gender");
return false;
}
}
</script>
Source: http://chandreshrana.blogspot.in/2016/11/radio-button-validation-in-javascript.html
If you try to call requestFocus()
before layout is inflated, it will return false. This code runs after layout get inflated. You don't need 200 ms delay as mentioned above.
editText.post(Runnable {
if(editText.requestFocus()) {
val imm = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
imm?.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0)
}
})
An easier way to get the machine epsilon for a given float type is to use np.finfo()
:
print(np.finfo(float).eps)
# 2.22044604925e-16
print(np.finfo(np.float32).eps)
# 1.19209e-07
You can download image without blocking UI with using NSURLSessionDataTask.
+(void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock
{
NSURLSessionDataTask* _sessionTask = [[NSURLSession sharedSession] dataTaskWithRequest:[NSURLRequest requestWithURL:url]
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error != nil)
{
if ([error code] == NSURLErrorAppTransportSecurityRequiresSecureConnection)
{
completionBlock(NO,nil);
}
}
else
{
[[NSOperationQueue mainQueue] addOperationWithBlock: ^{
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *image = [[UIImage alloc] initWithData:data];
completionBlock(YES,image);
});
}];
}
}];
[_sessionTask resume];
}
BinaryFormatter
may produce invalid output in some specific cases. For example it will omit unpaired surrogate characters. It may also have problems with values of interface types. Read this documentation page including community content.
If you find your error to be persistent you may want to consider using XML serializer like DataContractSerializer
or XmlSerializer
.
Regarding your query of
So when should interface with default methods be used and when should an abstract class be used? Are the abstract classes still useful in that scenario?
java documentation provides perfect answer.
Abstract Classes Compared to Interfaces:
Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation.
However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods.
With interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public. In addition, you can extend only one class, whether or not it is abstract, whereas you can implement any number of interfaces.
Use cases for each of them have been explained in below SE post:
What is the difference between an interface and abstract class?
Are the abstract classes still useful in that scenario?
Yes. They are still useful. They can contain non-static, non-final methods and attributes (protected, private in addition to public), which is not possible even with Java-8 interfaces.
Or create a function that creates an element including attributes from parameters
function elemCreate(elType){
var element = document.createElement(elType);
if (arguments.length>1){
var props = [].slice.call(arguments,1), key = props.shift();
while (key){
element.setAttribute(key,props.shift());
key = props.shift();
}
}
return element;
}
// usage
var img = elemCreate('img',
'width','100',
'height','100',
'src','http://example.com/something.jpeg');
FYI: height/width='100%'
would not work using attributes. For a height/width of 100% you need the elements style.height/style.width
-Filter only accepts a single string. -Include accepts multiple values, but qualifies the -Path argument. The trick is to append \*
to the end of the path, and then use -Include to select multiple extensions. BTW, quoting strings is unnecessary in cmdlet arguments unless they contain spaces or shell special characters.
Get-ChildItem $originalPath\* -Include *.gif, *.jpg, *.xls*, *.doc*, *.pdf*, *.wav*, .ppt*
Note that this will work regardless of whether $originalPath ends in a backslash, because multiple consecutive backslashes are interpreted as a single path separator. For example, try:
Get-ChildItem C:\\\\\Windows
Undeclared variable (without var
) are treated as properties of the global object. (Usually the window
object, unless you're in a with
block)
Variables declared with var
are normal local variables, and are not visible outside the function they're declared in. (Note that Javascript does not have block scope)
Update: ECMAScript 2015
let
was introduced in ECMAScript 2015 to have block scope.
Suppose there are 2 tables TableA and TableB with only 2 columns (Id, Data) and following data:
TableA:
+----+---------+
| Id | Data |
+----+---------+
| 1 | DataA11 |
| 1 | DataA12 |
| 1 | DataA13 |
| 2 | DataA21 |
| 3 | DataA31 |
+----+---------+
TableB:
+----+---------+
| Id | Data |
+----+---------+
| 1 | DataB11 |
| 2 | DataB21 |
| 2 | DataB22 |
| 2 | DataB23 |
| 4 | DataB41 |
+----+---------+
Inner Join on column Id
will return columns from both the tables and only the matching records:
.----.---------.----.---------.
| Id | Data | Id | Data |
:----+---------+----+---------:
| 1 | DataA11 | 1 | DataB11 |
:----+---------+----+---------:
| 1 | DataA12 | 1 | DataB11 |
:----+---------+----+---------:
| 1 | DataA13 | 1 | DataB11 |
:----+---------+----+---------:
| 2 | DataA21 | 2 | DataB21 |
:----+---------+----+---------:
| 2 | DataA21 | 2 | DataB22 |
:----+---------+----+---------:
| 2 | DataA21 | 2 | DataB23 |
'----'---------'----'---------'
Left Join (or Left Outer join) on column Id
will return columns from both the tables and matching records with records from left table (Null values from right table):
.----.---------.----.---------.
| Id | Data | Id | Data |
:----+---------+----+---------:
| 1 | DataA11 | 1 | DataB11 |
:----+---------+----+---------:
| 1 | DataA12 | 1 | DataB11 |
:----+---------+----+---------:
| 1 | DataA13 | 1 | DataB11 |
:----+---------+----+---------:
| 2 | DataA21 | 2 | DataB21 |
:----+---------+----+---------:
| 2 | DataA21 | 2 | DataB22 |
:----+---------+----+---------:
| 2 | DataA21 | 2 | DataB23 |
:----+---------+----+---------:
| 3 | DataA31 | | |
'----'---------'----'---------'
Right Join (or Right Outer join) on column Id
will return columns from both the tables and matching records with records from right table (Null values from left table):
+-----------------------------+
¦ Id ¦ Data ¦ Id ¦ Data ¦
+----+---------+----+---------¦
¦ 1 ¦ DataA11 ¦ 1 ¦ DataB11 ¦
¦ 1 ¦ DataA12 ¦ 1 ¦ DataB11 ¦
¦ 1 ¦ DataA13 ¦ 1 ¦ DataB11 ¦
¦ 2 ¦ DataA21 ¦ 2 ¦ DataB21 ¦
¦ 2 ¦ DataA21 ¦ 2 ¦ DataB22 ¦
¦ 2 ¦ DataA21 ¦ 2 ¦ DataB23 ¦
¦ ¦ ¦ 4 ¦ DataB41 ¦
+-----------------------------+
Full Outer Join on column Id
will return columns from both the tables and matching records with records from left table (Null values from right table) and records from right table (Null values from left table):
+-----------------------------+
¦ Id ¦ Data ¦ Id ¦ Data ¦
¦----+---------+----+---------¦
¦ - ¦ ¦ ¦ ¦
¦ 1 ¦ DataA11 ¦ 1 ¦ DataB11 ¦
¦ 1 ¦ DataA12 ¦ 1 ¦ DataB11 ¦
¦ 1 ¦ DataA13 ¦ 1 ¦ DataB11 ¦
¦ 2 ¦ DataA21 ¦ 2 ¦ DataB21 ¦
¦ 2 ¦ DataA21 ¦ 2 ¦ DataB22 ¦
¦ 2 ¦ DataA21 ¦ 2 ¦ DataB23 ¦
¦ 3 ¦ DataA31 ¦ ¦ ¦
¦ ¦ ¦ 4 ¦ DataB41 ¦
+-----------------------------+
Left Semi Join on column Id
will return columns only from left table and matching records only from left table:
+--------------+
¦ Id ¦ Data ¦
+----+---------¦
¦ 1 ¦ DataA11 ¦
¦ 1 ¦ DataA12 ¦
¦ 1 ¦ DataA13 ¦
¦ 2 ¦ DataA21 ¦
+--------------+
It returns English name of the month. 04 returns APRIL and so on.
String englishMonth (int month){
return Month.of(month);
}
Go to %ORACLE_HOME%\inventory\ContentsXML
folder and open
comps.xml
file
Look for <DEP_LIST> on ~second screen.
If following lines have
PLAT="NT_AMD64"
then this Oracle Home is 64 bit.PLAT="NT_X86"
then - 32 bit.