Try to execute the procedure like this,
var c refcursor;
execute pkg_name.get_user('14232', '15', 'TDWL', 'SA', 1, :c);
print c;
I use the consolidate function, like so:
element.transform.baseVal.consolidate()
The .e and .f values correspond to the x and y coordinates
string textboxID;
string da;
textboxID = "ctl00$MainContent$grd$ctl" + (grd.Columns.Count + j).ToString() + "$txtDyna" + (k).ToString();
textboxID= ctl00$MainContent$grd$ctl12$ctl00;
da = Request.Form(textboxID);
Use alter session set current_schema = <username>
, in your case as an execute immediate.
See Oracle's documentation for further information.
In your case, that would probably boil down to (untested)
DECLARE
CURSOR client_cur IS
SELECT distinct username
from all_users
where length(username) = 3;
-- client cursor
CURSOR emails_cur IS
SELECT id, name
FROM org;
BEGIN
FOR client IN client_cur LOOP
-- ****
execute immediate
'alter session set current_schema = ' || client.username;
-- ****
FOR email_rec in client_cur LOOP
dbms_output.put_line(
'Org id is ' || email_rec.id ||
' org nam ' || email_rec.name);
END LOOP;
END LOOP;
END;
/
OK, you should apply something like this to your dataset. Do not replace & save or you'll destroy your data! And, btw, you should (almost) never remove outliers from your data:
remove_outliers <- function(x, na.rm = TRUE, ...) {
qnt <- quantile(x, probs=c(.25, .75), na.rm = na.rm, ...)
H <- 1.5 * IQR(x, na.rm = na.rm)
y <- x
y[x < (qnt[1] - H)] <- NA
y[x > (qnt[2] + H)] <- NA
y
}
To see it in action:
set.seed(1)
x <- rnorm(100)
x <- c(-10, x, 10)
y <- remove_outliers(x)
## png()
par(mfrow = c(1, 2))
boxplot(x)
boxplot(y)
## dev.off()
And once again, you should never do this on your own, outliers are just meant to be! =)
EDIT: I added na.rm = TRUE
as default.
EDIT2: Removed quantile
function, added subscripting, hence made the function faster! =)
declare @T int
set @T = 10455836
--set @T = 421151
select (@T / 1000000) % 100 as hour,
(@T / 10000) % 100 as minute,
(@T / 100) % 100 as second,
(@T % 100) * 10 as millisecond
select dateadd(hour, (@T / 1000000) % 100,
dateadd(minute, (@T / 10000) % 100,
dateadd(second, (@T / 100) % 100,
dateadd(millisecond, (@T % 100) * 10, cast('00:00:00' as time(2))))))
Result:
hour minute second millisecond
----------- ----------- ----------- -----------
10 45 58 360
(1 row(s) affected)
----------------
10:45:58.36
(1 row(s) affected)
I had a similar error, My Class is
public class ServerInfo
{
public string Text { get; set; }
public string Value { get; set; }
public string PortNo { get; set; }
public override string ToString()
{
return Text;
}
}
But what I did, I casted my class to the SelectedItem property of the ComboBox. So, i'll have all of the class properties of the selected item.
// Code above
ServerInfo emailServer = (ServerInfo)cbServerName.SelectedItem;
mailClient.ServerName = emailServer.Value;
mailClient.ServerPort = emailServer.PortNo;
I hope this helps someone! Cheers!
Python 2
The error is caused because ElementTree did not expect to find non-ASCII strings set the XML when trying to write it out. You should use Unicode strings for non-ASCII instead. Unicode strings can be made either by using the u
prefix on strings, i.e. u'€'
or by decoding a string with mystr.decode('utf-8')
using the appropriate encoding.
The best practice is to decode all text data as it's read, rather than decoding mid-program. The io
module provides an open()
method which decodes text data to Unicode strings as it's read.
ElementTree will be much happier with Unicodes and will properly encode it correctly when using the ET.write()
method.
Also, for best compatibility and readability, ensure that ET encodes to UTF-8 during write()
and adds the relevant header.
Presuming your input file is UTF-8 encoded (0xC2
is common UTF-8 lead byte), putting everything together, and using the with
statement, your code should look like:
with io.open('myText.txt', "r", encoding='utf-8') as f:
data = f.read()
root = ET.Element("add")
doc = ET.SubElement(root, "doc")
field = ET.SubElement(doc, "field")
field.set("name", "text")
field.text = data
tree = ET.ElementTree(root)
tree.write("output.xml", encoding='utf-8', xml_declaration=True)
Output:
<?xml version='1.0' encoding='utf-8'?>
<add><doc><field name="text">data€</field></doc></add>
_ [$%-4009] * #,##0_ ;_ [$%-4009] * -#,##0_ ;_ [$%-4009] * "-"??_ ;_ @_
Keep it simple...
$intArray = array ();
$strArray = explode(',', $string);
foreach ($strArray as $value)
$intArray [] = intval ($value);
Why are you looking for other ways? Looping does the job without pain. If performance is your concern, you can go with json_decode ()
. People have posted how to use that, so I am not including it here.
Note: When using == operator instead of === , your string values are automatically converted into numbers (e.g. integer or double) if they form a valid number without quotes. For example:
$str = '1';
($str == 1) // true but
($str === 1) //false
Thus, == may solve your problem, is efficient, but will break if you use === in comparisons.
You can also use the void operator to obtain an undefined value:
if (input !== void 0) {
// do stuff
}
(And yes, as noted in another answer, this will throw an error if the variable was not declared, but this case can often be ruled out either by code inspection, or by code refactoring, e.g. using window.input !== void 0
for testing global variables or adding var input
.)
Just remove the JRE in Preferences>Java>Installed JRE and add the folder of your JDK. If you just add JDK but still leave JRE it won't work
As an alternative to using a trigger, you might like to consider creating a stored procedure to handle the INSERT
s that takes most of the columns as arguments and gets the CURRENT_TIMESTAMP
which it includes in the final INSERT
to the database. You could do the same for the CREATE
. You may also be able to set things up so that users cannot execute INSERT
and CREATE
statements other than via the stored procedures.
I have to admit that I haven't actually done this myself so I'm not at all sure of the details.
const int n = snprintf(NULL, 0, "%lu", ulong_value);
assert(n > 0);
char buf[n+1];
int c = snprintf(buf, n+1, "%lu", ulong_value);
assert(buf[n] == '\0');
assert(c == n);
Try this (ES5)
console.log($("#" + d));
ES6
console.log($(`#${d}`));
Try this:
<!DOCTYPE html>
<html>
<head>
<title>Convert JSON Data to HTML Table</title>
<style>
th, td, p, input {
font:14px Verdana;
}
tr{
align: right
}
table, th, td
{
border: solid 1px #DDD;
border-collapse: collapse;
padding: 2px 3px;
text-align: center;
}
th {
font-weight:bold;
}
</style>
</head>
<body>
<input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
<div id="showData"></div>
</body>
<script>
function CreateTableFromJSON() {
var obj = {[{"city":"AMBALA","cStatus":"Y"},
{"city":"ASANKHURD","cStatus":"Y"},
{"city":"ASSANDH","cStatus":"Y"}]}
var table = document.createElement('table');
var tr = table.insertRow(-1);
function iterate(obj,table,tr){
for(var props in obj){
if(obj.hasOwnProperty(props)){
if(typeof obj[props]=='object')
{
var trNext = table.insertRow(-1);
var tabCellHead = trNext.insertCell(-1);
var tabCell = trNext.insertCell(-1);
var table_in = document.createElement('table');
var tr_in;
var th = document.createElement("th");
th.innerHTML = props;
tabCellHead.appendChild(th);
tabCell.appendChild(table_in)
iterate(obj[props],table_in,tr_in);
}
else
{
if(tr === undefined)
{
tr = table.insertRow(-1);
}
var tabCell = tr.insertCell(-1);
console.log(props+' * '+obj[props]);
tabCell.innerHTML = obj[props];
}
}
}
}
iterate(obj,table,tr);
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
</script>
</html>
Simplified:
You could design a simple nine-patch png image and use it as the background of spinner. Using GIMP you can put both border and right triangle in image.
I prefer Consolas.
This will strip all commas from the text and left justify it.
for row in inputfile:
place = row['your_row_number_here'].strip(', ')
? ????? ??????
I had the same problem. I just cleaned and rebuilt the project and I was able to see the tests that were missing.
Initializer block is just like any bits of code; it's not "attached" to any field/method preceding it. To assign values to fields, you have to explicitly use the field as the lhs of an assignment statement.
private int lineCount; {
try{
lineCount = LineCounter.countLines(sFileName);
/*^^^^^^^*/
}
catch(IOException ex){
System.out.println (ex.toString());
System.out.println("Could not find file " + sFileName);
}
}
Also, your countLines
can be made simpler:
public static int countLines(String filename) throws IOException {
LineNumberReader reader = new LineNumberReader(new FileReader(filename));
while (reader.readLine() != null) {}
reader.close();
return reader.getLineNumber();
}
Based on my test, it looks like you can getLineNumber()
after close()
.
Use PE Explorer click here to know more and download
-> it works like pointer u don't have to use *
for( list<student>::iterator iter= data.begin(); iter != data.end(); iter++ )
cout<<iter->name; //'iter' not 'it'
@require
is NOT only processed when the script is first installed!
On my observations it is proccessed on the first execution time! So you can install a script via Greasemonkey's command for creating a brand-new script. The only thing you have to take care about is, that there is no page reload triggered, befor you add the @require
part. (and save the new script...)
I use the tail -f <file> | grep <pattern>
all the time.
It will wait till grep flushes, not till it finishes (I'm using Ubuntu).
What is the accessibility of the type support.ACTInterface
. The error suggests it is not public.
You cannot expose a public method signature where some of the parameter types of the signature are not public. It wouldn't be possible to call the method from outside since the caller couldn't construct the parameters required.
If you make support.ACTInterface
public that will remove this error. Alternatively reduce the accessibility of the form method if possible.
Try this:
<project>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.7</version>
<configuration>
...
<encoding>UTF-8</encoding>
...
</configuration>
</plugin>
</plugins>
...
</build>
...
</project>
This has been partially answered here: MySQL Like multiple values
I advise against
$search = explode( ' ', $search );
and input them directly into the SQL query as this makes prone to SQL inject via the search bar. You will have to escape the characters first in case they try something funny like: "--; DROP TABLE name;
$search = str_replace('"', "''", search );
But even that is not completely safe. You must try to use SQL prepared statements to be safer. Using the regular expression is much easier to build a function to prepare and create what you want.
function makeSQL_search_pattern($search) {
search_pattern = false;
//escape the special regex chars
$search = str_replace('"', "''", $search);
$search = str_replace('^', "\\^", $search);
$search = str_replace('$', "\\$", $search);
$search = str_replace('.', "\\.", $search);
$search = str_replace('[', "\\[", $search);
$search = str_replace(']', "\\]", $search);
$search = str_replace('|', "\\|", $search);
$search = str_replace('*', "\\*", $search);
$search = str_replace('+', "\\+", $search);
$search = str_replace('{', "\\{", $search);
$search = str_replace('}', "\\}", $search);
$search = explode(" ", $search);
for ($i = 0; $i < count($search); $i++) {
if ($i > 0 && $i < count($search) ) {
$search_pattern .= "|";
}
$search_pattern .= $search[$i];
}
return search_pattern;
}
$search_pattern = makeSQL_search_pattern($search);
$sql_query = "SELECT name FROM Products WHERE name REGEXP :search LIMIT 6"
$stmt = pdo->prepare($sql_query);
$stmt->bindParam(":search", $search_pattern, PDO::PARAM_STR);
$stmt->execute();
I have not tested this code, but this is what I would do in your case. I hope this helps.
You should have added muted
attribute inside your videoElement
for your code work as expected. Look bellow ..
<video id="IPcamerastream" muted="muted" autoplay src="videoplayback%20(1).mp4" width="960" height="540"></video>
Don' t forget to add a valid video link as source
Or you can use a for-each loop:
Collection<X> items = ...;
X last = null;
for (X x : items) last = x;
Local variables are non existent in the memory after the function termination.
However static
variables remain allocated in the memory throughout the life of the program irrespective of whatever function.
Additionally from your question, static
variables can be declared locally in class
or function scope and globally in namespace
or file scope. They are allocated the memory from beginning to end, it's just the initialization which happens sooner or later.
Don't take someones word for it, look at the dissassembly for both C and your language-of-choice in any performance critical part of your code. I think you can just look in the disassembly window at runtime in Visual Studio to see disassembled .Net. Should be possible if tricky for Java using windbg, though if you do it with .Net many of the issues would be the same.
I don't like to write in C if I don't need to, but I think many of the claims made in these answers that tout the speed of languages other than C can be put aside by simply disassembling the same routine in C and in your higher level language of choice, especially if lots of data is involved as is common in performance critical applications. Fortran may be an exception in its area of expertise, don't know. Is it higher level than C?
First time I did compared JITed code with native code resolved any and all questions whether .Net code could run comparably to C code. The extra level of abstraction and all the safety checks come with a significant cost. Same costs would probably apply to Java, but don't take my word for it, try it on something where performance is critical. (Anyone know enough about JITed Java to locate a compiled procedure in memory? It should certainly be possible)
If speed is what you need and extra dependencies are not a problem, you maybe find numba
quite useful (now it is pretty easy to install, on any platform). The classic ray_tracing
approach you proposed can be easily ported to numba
by using numba @jit
decorator and casting the polygon to a numpy array. The code should look like:
@jit(nopython=True)
def ray_tracing(x,y,poly):
n = len(poly)
inside = False
p2x = 0.0
p2y = 0.0
xints = 0.0
p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x,p1y = p2x,p2y
return inside
The first execution will take a little longer than any subsequent call:
%%time
polygon=np.array(polygon)
inside1 = [numba_ray_tracing_method(point[0], point[1], polygon) for
point in points]
CPU times: user 129 ms, sys: 4.08 ms, total: 133 ms
Wall time: 132 ms
Which, after compilation will decrease to:
CPU times: user 18.7 ms, sys: 320 µs, total: 19.1 ms
Wall time: 18.4 ms
If you need speed at the first call of the function you can then pre-compile the code in a module using pycc
. Store the function in a src.py like:
from numba import jit
from numba.pycc import CC
cc = CC('nbspatial')
@cc.export('ray_tracing', 'b1(f8, f8, f8[:,:])')
@jit(nopython=True)
def ray_tracing(x,y,poly):
n = len(poly)
inside = False
p2x = 0.0
p2y = 0.0
xints = 0.0
p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x,p1y = p2x,p2y
return inside
if __name__ == "__main__":
cc.compile()
Build it with python src.py
and run:
import nbspatial
import numpy as np
lenpoly = 100
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in
np.linspace(0,2*np.pi,lenpoly)[:-1]]
# random points set of points to test
N = 10000
# making a list instead of a generator to help debug
points = zip(np.random.random(N),np.random.random(N))
polygon = np.array(polygon)
%%time
result = [nbspatial.ray_tracing(point[0], point[1], polygon) for point in points]
CPU times: user 20.7 ms, sys: 64 µs, total: 20.8 ms
Wall time: 19.9 ms
In the numba code I used: 'b1(f8, f8, f8[:,:])'
In order to compile with nopython=True
, each var needs to be declared before the for loop
.
In the prebuild src code the line:
@cc.export('ray_tracing' , 'b1(f8, f8, f8[:,:])')
Is used to declare the function name and its I/O var types, a boolean output b1
and two floats f8
and a two-dimensional array of floats f8[:,:]
as input.
For my use case, I need to check if multiple points are inside a single polygon - In such a context, it is useful to take advantage of numba parallel capabilities to loop over a series of points. The example above can be changed to:
from numba import jit, njit
import numba
import numpy as np
@jit(nopython=True)
def pointinpolygon(x,y,poly):
n = len(poly)
inside = False
p2x = 0.0
p2y = 0.0
xints = 0.0
p1x,p1y = poly[0]
for i in numba.prange(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x,p1y = p2x,p2y
return inside
@njit(parallel=True)
def parallelpointinpolygon(points, polygon):
D = np.empty(len(points), dtype=numba.boolean)
for i in numba.prange(0, len(D)):
D[i] = pointinpolygon(points[i,0], points[i,1], polygon)
return D
Note: pre-compiling the above code will not enable the parallel capabilities of numba (parallel CPU target is not supported by pycc/AOT
compilation) see: https://github.com/numba/numba/issues/3336
Test:
import numpy as np
lenpoly = 100
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in np.linspace(0,2*np.pi,lenpoly)[:-1]]
polygon = np.array(polygon)
N = 10000
points = np.random.uniform(-1.5, 1.5, size=(N, 2))
For N=10000
on a 72 core machine, returns:
%%timeit
parallelpointinpolygon(points, polygon)
# 480 µs ± 8.19 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
0
instead of 1
(thanks @mehdi):for i in numba.prange(0, len(D))
Follow-up on the comparison made by @mehdi, I am adding a GPU-based method below. It uses the point_in_polygon
method, from the cuspatial
library:
import numpy as np
import cudf
import cuspatial
N = 100000002
lenpoly = 1000
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in
np.linspace(0,2*np.pi,lenpoly)]
polygon = np.array(polygon)
points = np.random.uniform(-1.5, 1.5, size=(N, 2))
x_pnt = points[:,0]
y_pnt = points[:,1]
x_poly =polygon[:,0]
y_poly = polygon[:,1]
result = cuspatial.point_in_polygon(
x_pnt,
y_pnt,
cudf.Series([0], index=['geom']),
cudf.Series([0], name='r_pos', dtype='int32'),
x_poly,
y_poly,
)
Following @Mehdi comparison. For N=100000002
and lenpoly=1000
- I got the following results:
time_parallelpointinpolygon: 161.54760098457336
time_mpltPath: 307.1664695739746
time_ray_tracing_numpy_numba: 353.07356882095337
time_is_inside_sm_parallel: 37.45389246940613
time_is_inside_postgis_parallel: 127.13793849945068
time_is_inside_rapids: 4.246025562286377
hardware specs:
Notes:
The cuspatial.point_in_poligon
method, is quite robust and powerful, it offers the ability to work with multiple and complex polygons (I guess at the expense of performance)
The numba
methods can also be 'ported' on the GPU - it will be interesting to see a comparison which includes a porting to cuda
of fastest method mentioned by @Mehdi (is_inside_sm
).
You can use jQuery methods .hasClass()
, .addClass()
, and .removeClass()
to manipulate which classes are applied to your elements. Just define different classes and add/remove them as necessary.
And if tools\android
works for you while .exe doesn't, it's probably the x64 java.
It started working when i completely uninstalled JDK with JRE (shows as separate option in windows uninstal control panel applet) and android sdk and reinstalled using x86 version.
Why does it worth the time, you may ask? Well, such an inconsistency obvoiusly means that amount of testing with x64 java is zero and so you can probably experience many other failures in the future.
I could get to your expected result just by doing this in mysql:
SELECT id, min(record_date), other_cols
FROM mytable
GROUP BY id
Does this work for you?
I know my solution is not very popular from the pythonic point of view, but I prefer to use the Java approach of one module->one class, with the module named as the class. I do understand the reason behind the python style, but I am not too fond of having a very large file containing a lot of classes. I find it difficult to browse, despite folding.
Another reason is version control: having a large file means that your commits tend to concentrate on that file. This can potentially lead to a higher quantity of conflicts to be resolved. You also loose the additional log information that your commit modifies specific files (therefore involving specific classes). Instead you see a modification to the module file, with only the commit comment to understand what modification has been done.
Summing up, if you prefer the python philosophy, go for the suggestions of the other posts. If you instead prefer the java-like philosophy, create a Nib.py containing class Nib.
For Excel 2010 it should be UTF-8. Instruction by MS :
http://msdn.microsoft.com/en-us/library/bb507946:
"The basic document structure of a SpreadsheetML document consists of the Sheets and Sheet elements, which reference the worksheets in the Workbook. A separate XML file is created for each Worksheet. For example, the SpreadsheetML for a workbook that has two worksheets name MySheet1 and MySheet2 is located in the Workbook.xml file and is shown in the following code example.
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<workbook xmlns=http://schemas.openxmlformats.org/spreadsheetml/2006/main xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheets>
<sheet name="MySheet1" sheetId="1" r:id="rId1" />
<sheet name="MySheet2" sheetId="2" r:id="rId2" />
</sheets>
</workbook>
The worksheet XML files contain one or more block level elements such as SheetData. sheetData represents the cell table and contains one or more Row elements. A row contains one or more Cell elements. Each cell contains a CellValue element that represents the value of the cell. For example, the SpreadsheetML for the first worksheet in a workbook, that only has the value 100 in cell A1, is located in the Sheet1.xml file and is shown in the following code example.
<?xml version="1.0" encoding="UTF-8" ?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheetData>
<row r="1">
<c r="A1">
<v>100</v>
</c>
</row>
</sheetData>
</worksheet>
"
Detection of cell encodings:
<textarea style="resize:none" name="name" cols="num" rows="num"></textarea>
Just an example
Can you try doing something like (to get the last entry):
linkedHashMap.entrySet().toArray()[linkedHashMap.size() -1];
Use "This is' it".replace("'", "\\'")
If u want to join two dataframes in pandas you can simply use available attributes like merge
or concatenate
.
For example if I have two dataframes df1
and df2
I can join them by:
newdataframe=merge(df1,df2,left_index=True,right_index=True)
I don't believe the expression is sensical as it is.
Elvis means "if truthy, use the value, else use this other thing."
Your "other thing" is a closure, and the value is status != null
, neither of which would seem to be what you want. If status
is null, Elvis says true
. If it's not, you get an extra layer of closure.
Why can't you just use:
(it.description == desc) && ((status == null) || (it.status == status))
Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find
calls, just use an intermediate variable.
its simple as possible by using this util method
/*
* param@ imageView is your image you want to bordered it
*/
public static Bitmap generateBorders(ImageView imageView){
Bitmap mbitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
Bitmap imageRounded = Bitmap.createBitmap(mbitmap.getWidth(), mbitmap.getHeight(), mbitmap.getConfig());
Canvas canvas = new Canvas(imageRounded);
Paint mpaint = new Paint();
mpaint.setAntiAlias(true);
mpaint.setShader(new BitmapShader(mbitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
canvas.drawRoundRect((new RectF(0, 0, mbitmap.getWidth(), mbitmap.getHeight())), 100, 100, mpaint);// Round Image Corner 100 100 100 100
return imageRounded;
}
then set your image view bitmap with returned value have fun
It also works without jQuery if you do the following changes:
Add type="button"
to the edit button in order not to trigger submission of the form.
Change the name of your function from change()
to anything else.
Don't use hidden="hidden"
, use CSS instead: style="display: none;"
.
The following code works for me:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="STYLESHEET" type="text/css" href="dba_style/buttons.css" />
<title>Untitled Document</title>
</head>
<script type="text/javascript">
function do_change(){
document.getElementById("save").style.display = "block";
document.getElementById("change").style.display = "block";
document.getElementById("cancel").style.display = "block";
}
</script>
<body>
<form name="form1" method="post" action="">
<div class="buttons">
<button type="button" class="regular" name="edit" id="edit" onclick="do_change(); return false;">
<img src="dba_images/textfield_key.png" alt=""/>
Edit
</button>
<button type="submit" class="positive" name="save" id="save" style="display:none;">
<img src="dba_images/apply2.png" alt=""/>
Save
</button>
<button class="regular" name="change" id="change" style="display:none;">
<img src="dba_images/textfield_key.png" alt=""/>
change
</button>
<button class="negative" name="cancel" id="cancel" style="display:none;">
<img src="dba_images/cross.png" alt=""/>
Cancel
</button>
</div>
</form>
</body>
</html>
The NVARCHAR2
stores variable-length character data. When you
create a table with the NVARCHAR2
column, the maximum size is always
in character length semantics, which is also the default and only
length semantics for the NVARCHAR2
data type.
The NVARCHAR2
data type uses AL16UTF16
character set which encodes Unicode data in the UTF-16
encoding. The AL16UTF16
use 2 bytes
to store a character. In addition, the maximum byte length of an NVARCHAR2
depends on the configured national character set.
VARCHAR2
The maximum size of VARCHAR2
can be in either bytes or characters. Its column only can store characters in the default character
set while the NVARCHAR2
can store virtually any characters. A single character may require up to 4 bytes
.
By defining the field as:
VARCHAR2(10 CHAR)
you tell Oracle it can use enough space to store 10
characters, no matter how many bytes it takes to store each one. A single character may require up to 4 bytes
.NVARCHAR2(10)
you tell Oracle it can store 10 characters with 2 bytes
per characterIn Summary:
VARCHAR2(10 CHAR)
can store maximum of 10 characters
and maximum of 40 bytes
(depends on the configured national character set).
NVARCHAR2(10)
can store maximum of 10 characters
and maximum of 20 bytes
(depends on the configured national character set).
Note: Character set can be UTF-8
, UTF-16
,....
Please have a look at this tutorial for more detail.
Have a good day!
The change
event not firing on deselection is the desired behaviour. You should run a selector over the entire radio group rather than just the single radio button. And your radio group should have the same name (with different values)
Consider the following code:
$('input[name="job[video_need]"]').on('change', function () {
var value;
if ($(this).val() == 'none') {
value = 'hide';
} else {
value = 'show';
}
$('#video-script-collapse').collapse(value);
});
I have same use case as yours i.e. to show an input box when a particular radio button is selected. If the event was fired on de-selection as well, I would get 2 events each time.
For what it's worth.
```{r eval=FALSE}
The document will display the code by default but will prevent the code block from being executed, and thus will also not display any results.
I found the possible way to write.
Server Side -
app.get('/main', function(req, res) {
var name = 'hello';
res.render(__dirname + "/views/layouts/main.html", {name:name});
});
Client side (main.html) -
<h1><%= name %></h1>
Seems to be a typo error in that package of gcc. The solution:
mv /usr/include/c++/4.x/i486-linux-gnu /usr/include/c++/4.x/i686-linux-gnu/64
This one works fine for me :
theme.applyStyle(R.style.AppTheme, true)
Usage:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//The call goes right after super.onCreate() and before setContentView()
theme.applyStyle(R.style.AppTheme, true)
setContentView(layoutId)
onViewCreated(savedInstanceState)
}
you can also try to parse the data and then check if you got object:
var testIfJson = JSON.parse(data);
if (typeOf testIfJson == "object")
{
//Json
}
else
{
//Not Json
}
Using Hadley Wickham's purrr package this is quite simple. Use split
to split the passed data_frame
into groups, then use map
to apply the summary
function to each group.
library(purrr)
df %>% split(.$group) %>% map(summary)
To get this in a ListFragment:
getListView().setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
getListView().setStackFromBottom(true);`
Added this answer because if someone do a google search for same problem with ListFragment he just finds this..
Regards
Context envContext = (Context)initContext.lookup("java:comp/env");
not:Context envContext = (Context)initContext.lookup("java:/comp/env");
Add this to your header file #include and then in the end add this line : getch();
Hi I fix this on one vps service, restarting it, other way is if you have a console from your service o any other way to run a command in your remote machine the only command you must run is restart the ssh daemon and enjoy!! :P
/etc/init.d/ssh restart
First Navigate the Path of php.ini
sudo vi /etc/php/7.2/fpm/php.ini
then, next change
upload_max_filesize = 999M
post_max_size = 999M
then ESC-->:wq
Now Lastly Paste this command,
sudo systemctl restart php7.2-fpm.service
you are done.
fun rotateArrow(view: View): Boolean {
return if (view.rotation == 0F) {
view.animate().setDuration(200).rotation(180F)
true
} else {
view.animate().setDuration(200).rotation(0F)
false
}
}
iOS8 answered these questions.
- (instancetype)initWithEffect:(UIVisualEffect *)effect
or Swift:
init(effect effect: UIVisualEffect)
I eventually figured out an easy way to do it:
https://``t.co/tQM43ftXyM
). Copy this URL and paste it in a new browser tab.https://twitter.com/UserName/status/828267001496784896/video/1
This is the link to the Twitter Card containing the native video. Pasting this link in a new tweet or DM will include the native video in it!
You can use a script like this to dump all the versions of a file to separate files:
e.g.
git_dump_all_versions_of_a_file.sh path/to/somefile.txt
Get the script here as an answer to another similar question
In servers, you may like to send RST
instead of FIN
when disconnecting misbehaving clients. That skips FIN-WAIT
followed by TIME-WAIT
socket states in the server, which prevents from depleting server resources, and, hence, protects from this kind of denial-of-service attack.
The WHERE
clause is misplaced, it has to follow the table references and JOIN operations.
Something like this:
FROM tartikel p1
JOIN tartikelpict p2
ON p1.kArtikel = p2.kArtikel
AND p2.nNr = 1
WHERE p1.dErstellt >= DATE(NOW()) - INTERVAL 7 DAY
ORDER BY p1.kArtikel DESC
EDIT (three plus years later)
The above essentially answers the question "I tried to add a WHERE clause to my query and now the query is returning an error, how do I fix it?"
As to a question about writing a condition that checks a date range of "last 7 days"...
That really depends on interpreting the specification, what the datatype of the column in the table is (DATE or DATETIME) and what data is available... what should be returned.
To summarize: the general approach is to identify a "start" for the date/datetime range, and "end" of that range, and reference those in a query. Let's consider something easier... all rows for "yesterday".
If our column is DATE type. Before we incorporate an expression into a query, we can test it in a simple SELECT
SELECT DATE(NOW()) + INTERVAL -1 DAY
and verify the result returned is what we expect. Then we can use that same expression in a WHERE clause, comparing it to a DATE column like this:
WHERE datecol = DATE(NOW()) + INTERVAL -1 DAY
For a DATETIME or TIMESTAMP column, we can use >=
and <
inequality comparisons to specify a range
WHERE datetimecol >= DATE(NOW()) + INTERVAL -1 DAY
AND datetimecol < DATE(NOW()) + INTERVAL 0 DAY
For "last 7 days" we need to know if that mean from this point right now, back 7 days ... e.g. the last 7*24 hours , including the time component in the comparison, ...
WHERE datetimecol >= NOW() + INTERVAL -7 DAY
AND datetimecol < NOW() + INTERVAL 0 DAY
the last seven complete days, not including today
WHERE datetimecol >= DATE(NOW()) + INTERVAL -7 DAY
AND datetimecol < DATE(NOW()) + INTERVAL 0 DAY
or past six complete days plus so far today ...
WHERE datetimecol >= DATE(NOW()) + INTERVAL -6 DAY
AND datetimecol < NOW() + INTERVAL 0 DAY
I recommend testing the expressions on the right side in a SELECT statement, we can use a user-defined variable in place of NOW() for testing, not being tied to what NOW() returns so we can test borders, across week/month/year boundaries, and so on.
SET @clock = '2017-11-17 11:47:47' ;
SELECT DATE(@clock)
, DATE(@clock) + INTERVAL -7 DAY
, @clock + INTERVAL -6 DAY
Once we have expressions that return values that work for "start" and "end" for our particular use case, what we mean by "last 7 days", we can use those expressions in range comparisons in the WHERE clause.
(Some developers prefer to use the DATE_ADD
and DATE_SUB
functions in place of the + INTERVAL val DAY/HOUR/MINUTE/MONTH/YEAR
syntax.
And MySQL provides some convenient functions for working with DATE, DATETIME and TIMESTAMP datatypes... DATE, LAST_DAY,
Some developers prefer to calculate the start and end in other code, and supply string literals in the SQL query, such that the query submitted to the database is
WHERE datetimecol >= '2017-11-10 00:00'
AND datetimecol < '2017-11-17 00:00'
And that approach works too. (My preference would be to explicitly cast those string literals into DATETIME, either with CAST, CONVERT or just the + INTERVAL trick...
WHERE datetimecol >= '2017-11-10 00:00' + INTERVAL 0 SECOND
AND datetimecol < '2017-11-17 00:00' + INTERVAL 0 SECOND
The above all assumes we are storing "dates" in appropriate DATE, DATETIME and/or TIMESTAMP datatypes, and not storing them as strings in variety of formats e.g. 'dd/mm/yyyy'
, m/d/yyyy
, julian dates, or in sporadically non-canonical formats, or as a number of seconds since the beginning of the epoch, this answer would need to be much longer.
Guys i have was facing this issue for an entire day at my work, just now solved by just copy pasting the MSBuild.exe file in C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\MSBuild\Current\Bin to C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\MSBuild\15.0\Bin.
I tried all the suggested methods in this thread none worked. If anyone happened to face this issue straight away use npm install --global --production windows-build-tools --vs2019 or --vs2017 . and copy paste the exe file.
The .egg
file is a distribution format for Python packages. It’s just an alternative to a source code distribution or Windows exe
. But note that for pure Python
, the .egg
file is completely cross-platform.
The .egg
file itself is essentially a .zip
file. If you change the extension to “zip
”, you can see that it will have folders inside the archive.
Also, if you have an .egg
file, you can install it as a package using easy_install
Example:
To create an .egg
file for a directory say mymath
which itself may have several python scripts, do the following step:
# setup.py
from setuptools import setup, find_packages
setup(
name = "mymath",
version = "0.1",
packages = find_packages()
)
Then, from the terminal do:
$ python setup.py bdist_egg
This will generate lot of outputs, but when it’s completed you’ll see that you have three new folders: build, dist, and mymath.egg-info. The only folder that we care about is the dist folder where you'll find your .egg
file, mymath-0.1-py3.5.egg
with your default python (installation) version number(mine here: 3.5)
Source: Python library blog
Because in C++, the final executable code does not carry any symbol information, it's more or less pure machine code.
Thus, you need a way to describe the interface of a piece of code, that is separate from the code itself. This description is in the header file.
If you set the AllowsTransparency
property on the Window
(even without setting any transparency values) the border disappears and you can only resize via the grip.
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="640" Height="480"
WindowStyle="None"
AllowsTransparency="True"
ResizeMode="CanResizeWithGrip">
<!-- Content -->
</Window>
Result looks like:
Try this approach:
SELECT TOP @offset a.*
FROM (select top @limit b.*, COUNT(*) OVER() totalrows
from TABLENAME b order by id asc) a
ORDER BY id desc;
You should only need to unbind the service in onDestroy()
. Then, The warning will go.
See here.
As the Activity doc tries to explain, there are three main bind/unbind groupings you will use: onCreate() and onDestroy(), onStart() and onStop(), and onResume() and onPause().
You are allow to use php_value to change php setting in .htaccess file. Same like how php.ini did.
Example:
php_value date.timezone Asia/Kuala_Lumpur
For other php setting, please read http://www.php.net/manual/en/ini.list.php
https://socket.io/docs/client-api/#socket-send-args-ack
socket.send
// Sends a message event
socket.emit(eventName[, ...args][, ack])
// you can custom eventName
You could also override the Math.round function to do the rounding correct and add a parameter for decimals and use it like: Math.round(Number, Decimals). Keep in mind that this overrides the built in component Math.round and giving it another property then it original is.
var round = Math.round;
Math.round = function (value, decimals) {
decimals = decimals || 0;
return Number(round(value + 'e' + decimals) + 'e-' + decimals);
}
Then you can simply use it like this:
Math.round(1.005, 2);
just a matter of taste but if you prefer accessing the variable or function directly like this:
<div id="playlist-icon" back-img="playlist.icon">
instead of interpolating like this:
<div id="playlist-icon" back-img="{{playlist.icon}}">
then you can define the directive a bit differently with scope.$watch
which will do $parse
on the
attribute
angular.module('myApp', [])
.directive('bgImage', function(){
return function(scope, element, attrs) {
scope.$watch(attrs.bgImage, function(value) {
element.css({
'background-image': 'url(' + value +')',
'background-size' : 'cover'
});
});
};
})
there is more background on this here: AngularJS : Difference between the $observe and $watch methods
if you wanna remove attributes for all files in all folders on whole flash drive do this:
attrib -r -s -h /S /D
this command will remove attrubutes for all files folders and subfolders:
-read only -system file -is hidden -Processes matching files and all subfolders. -Processes folders as well
Since performance.navigation
is now deprecated, you can try this:
var perfEntries = performance.getEntriesByType("navigation");
if (perfEntries[0].type === "back_forward") {
location.reload(true);
}
As from iOS 13 your app also needs Core Location access in order to use the CNCopyCurrentNetworkInfo
function unless it configured the current network or has VPN configurations:
So this is what you need (see apple documentation):
- Link the CoreLocation.framework
library
- Add location-services
as a UIRequiredDeviceCapabilities
Key/Value in Info.plist
- Add a NSLocationWhenInUseUsageDescription
Key/Value in Info.plist describing why your app requires Core Location
- Add the "Access WiFi Information" entitlement for your app
Now as an Objective-C example, first check if location access has been accepted before reading the network info using CNCopyCurrentNetworkInfo
:
- (void)fetchSSIDInfo {
NSString *ssid = NSLocalizedString(@"not_found", nil);
if (@available(iOS 13.0, *)) {
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
NSLog(@"User has explicitly denied authorization for this application, or location services are disabled in Settings.");
} else {
CLLocationManager* cllocation = [[CLLocationManager alloc] init];
if(![CLLocationManager locationServicesEnabled] || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined){
[cllocation requestWhenInUseAuthorization];
usleep(500);
return [self fetchSSIDInfo];
}
}
}
NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
id info = nil;
for (NSString *ifnam in ifs) {
info = (__bridge_transfer id)CNCopyCurrentNetworkInfo(
(__bridge CFStringRef)ifnam);
NSDictionary *infoDict = (NSDictionary *)info;
for (NSString *key in infoDict.allKeys) {
if ([key isEqualToString:@"SSID"]) {
ssid = [infoDict objectForKey:key];
}
}
}
...
...
}
The general answer to your question is that it depends. And you get to decide by specifying what your "Content-Type" is in the HTTP headers.
A value of "application/x-www-form-urlencoded" means that your POST body will need to be URL encoded just like a GET parameter string. A value of "multipart/form-data" means that you'll be using content delimiters and NOT url encoding the content.
This answer has a much more thorough explanation if you'd like more information.
For an answer specific to the PHP libraries you're using (CURL), you should read the documentation here.
Here's the relevant information:
CURLOPT_POST
TRUE to do a regular HTTP POST. This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.
CURLOPT_POSTFIELDS
The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. This parameter can either be passed as a urlencoded string like 'para1=val1¶2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. As of PHP 5.2.0, value must be an array if files are passed to this option with the @ prefix.
This is the perfect job for the query selector...
var Set1=document.querySelectorAll('input[type=button]'); // by type
var Set2=document.querySelectorAll('input[name=goButton]'); // by name
var Set3=document.querySelectorAll('input[value=Go]'); // by value
You can then loop through these collections to operate on elements found.
Error is that you are using 'ID' in lower case like 'checkbox1' but when you loop json object its return in upper case. So you need to replace checkbox1 to CHECKBOX1.
In my case :-
var response = jQuery.parseJSON(response);
$.each(response, function(key, value) {
$.each(value, function(key, value){
$('#'+key).val(value);
});
});
Before
<input type="text" name="abc" id="abc" value="">
I am getting the same error but when i replace the id in html code its work fine.
After
<input type="text" name="abc" id="ABC" value="">
After iOS 10 you have to define and provide a usage description of all the system’s privacy-sensitive data accessed by your app in Info.plist as below:
Calendar
Key : Privacy - Calendars Usage Description
Value : $(PRODUCT_NAME) calendar events
Reminder :
Key : Privacy - Reminders Usage Description
Value : $(PRODUCT_NAME) reminder use
Contact :
Key : Privacy - Contacts Usage Description
Value : $(PRODUCT_NAME) contact use
Photo :
Key : Privacy - Photo Library Usage Description
Value : $(PRODUCT_NAME) photo use
Bluetooth Sharing :
Key : Privacy - Bluetooth Peripheral Usage Description
Value : $(PRODUCT_NAME) Bluetooth Peripheral use
Microphone :
Key : Privacy - Microphone Usage Description
Value : $(PRODUCT_NAME) microphone use
Camera :
Key : Privacy - Camera Usage Description
Value : $(PRODUCT_NAME) camera use
Location :
Key : Privacy - Location Always Usage Description
Value : $(PRODUCT_NAME) location use
Key : Privacy - Location When In Use Usage Description
Value : $(PRODUCT_NAME) location use
Heath :
Key : Privacy - Health Share Usage Description
Value : $(PRODUCT_NAME) heath share use
Key : Privacy - Health Update Usage Description
Value : $(PRODUCT_NAME) heath update use
HomeKit :
Key : Privacy - HomeKit Usage Description
Value : $(PRODUCT_NAME) home kit use
Media Library :
Key : Privacy - Media Library Usage Description
Value : $(PRODUCT_NAME) media library use
Motion :
Key : Privacy - Motion Usage Description
Value : $(PRODUCT_NAME) motion use
Speech Recognition :
Key : Privacy - Speech Recognition Usage Description
Value : $(PRODUCT_NAME) speech use
SiriKit :
Key : Privacy - Siri Usage Description
Value : $(PRODUCT_NAME) siri use
TV Provider :
Key : Privacy - TV Provider Usage Description
Value : $(PRODUCT_NAME) tvProvider use
You can get detailed information in this link.
Some firewalls do that if a connection is idle for x number of minutes. Some ISPs set their routers to do that for various reasons as well.
In this day and age, you'll need to gracefully handle (re-establish as needed) that condition.
num_rows on your COUNT() query will literally ALWAYS be 1. It is an aggregate function without a GROUP BY clause, so all rows are grouped together into one. If you want the value of the count, you should give it an identifier SELECT COUNT(*) as myCount ...
, then use your normal method of accessing a result (the first, only result) and get it's 'myCount' property.
According to official documentation, you can set or remove the "executable" flag on any tracked file using update-index
sub-command.
To set the flag, use following command:
git update-index --chmod=+x path/to/file
To remove it, use:
git update-index --chmod=-x path/to/file
Under the hood
While this looks like the regular unix files permission system, actually it is not. Git maintains a special "mode" for each file in its internal storage:
100644
for regular files100755
for executable onesYou can visualize it using ls-file
subcommand, with --stage
option:
$ git ls-files --stage
100644 aee89ef43dc3b0ec6a7c6228f742377692b50484 0 .gitignore
100755 0ac339497485f7cc80d988561807906b2fd56172 0 my_executable_script.sh
By default, when you add a file to a repository, Git will try to honor its filesystem attributes and set the correct filemode accordingly. You can disable this by setting core.fileMode
option to false:
git config core.fileMode false
Troubleshooting
If at some point the Git filemode is not set but the file has correct filesystem flag, try to remove mode and set it again:
git update-index --chmod=-x path/to/file
git update-index --chmod=+x path/to/file
Bonus
Starting with Git 2.9, you can stage a file AND set the flag in one command:
git add --chmod=+x path/to/file
Try:
123-(?:(apple|banana|)-|)456
That will match apple
, banana
, or a blank string, and following it there will be a 0 or 1 hyphens. I was wrong about not having a need for a capturing group. Silly me.
I'm trying Ion_Auth and appreciate it, btw...
SimpleLoginSecure Makes authentication simple and secure.
This is an old thread but just in case anyone comes across it like I did. pi.FileName needs to be set to the file name (and possibly full path to file ) of the executable you want to use to open your file. The below code works for me to open a video file with VLC.
var path = files[currentIndex].fileName;
var pi = new ProcessStartInfo(path)
{
Arguments = Path.GetFileName(path),
UseShellExecute = true,
WorkingDirectory = Path.GetDirectoryName(path),
FileName = "C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe",
Verb = "OPEN"
};
Process.Start(pi)
Tigran's answer works but will use windows' default application to open your file, so using ProcessStartInfo may be useful if you want to open the file with an application that is not the default.
Since today I know it: the best thing for text extraction from PDFs is TET, the text extraction toolkit. TET is part of the PDFlib.com family of products.
PDFlib.com is Thomas Merz's company. In case you don't recognize his name: Thomas Merz is the author of the "PostScript and PDF Bible".
TET's first incarnation is a library. That one can probably do everything Budda006 wanted, including positional information about every element on the page. Oh, and it can also extract images. It recombines images which are fragmented into pieces.
pdflib.com also offers another incarnation of this technology, the TET plugin for Acrobat. And the third incarnation is the PDFlib TET iFilter. This is a standalone tool for user desktops. Both these are free (as in beer) to use for private, non-commercial purposes.
And it's really powerful. Way better than Adobe's own text extraction. It extracted text for me where other tools (including Adobe's) do spit out garbage only.
I just tested the desktop standalone tool, and what they say on their webpage is true. It has a very good commandline. Some of my "problematic" PDF test files the tool handled to my full satisfaction.
This thing will from now on be my recommendation for every sophisticated and challenging PDF text extraction requirements.
TET is simply awesome. It detects tables. Inside tables, it identifies cells spanning multiple columns. It identifies table rows and contents of each table cell separately. It deals very well with hyphenations: it removes hyphens and restores complete words. It supports non-ASCII languages (including CJK, Arabic and Hebrew). When encountering ligatures, it restores the original characters...
Give it a try.
I had same issue. Resolved by firstly setting :
imageView.setMinHeight(0);
imageView.setMinimumHeight(0);
And then :
imageView.getLayoutParams().height= ViewGroup.LayoutParams.MATCH_PARENT;
setMinHeight is defined by ImageView, while setMinimumHeight is defined by View. According to the docs, the greater of the two values is used, so both must be set.
today is 29th of January, +1 month means 29th of Fabruary, but because February consists of 28 days this year, it overlaps to the next day which is March 1st
instead try
strtotime('next month')
Either that as suggested by Lasse V. Karlsen, or set up a loop in your service that will wait for a debugger to attach. The simplest is
while (!Debugger.IsAttached)
{
Thread.Sleep(1000);
}
... continue with code
That way you can start the service and inside Visual Studio you choose "Attach to Process..." and attach to your service which then will resume normal exution.
Since Git 2.26.0, you can use --show-scope
option:
git config --list --show-scope
Example output:
system rebase.autosquash=true
system credential.helper=helper-selector
global core.editor='code.cmd' --wait -n
global merge.tool=kdiff3
local core.symlinks=false
local core.ignorecase=true
It can be combined with
--local
for project config, --global
for user config, --system
for all users' config--show-origin
to show the exact config file locationI'm also having the same issue with a very latest Tomcat server (7.0.40). It goes non-responsive once for a couple of days.
To see open connections, you may use:
sudo netstat -tonp | grep jsvc | grep --regexp="127.0.0.1:443" --regexp="127.0.0.1:80" | grep CLOSE_WAIT
As mentioned in this post, you may use /proc/sys/net/ipv4/tcp_keepalive_time
to view the values. The value seems to be in seconds and defaults to 7200 (i.e. 2 hours).
To change them, you need to edit /etc/sysctl.conf
.
Open/create `/etc/sysctl.conf`
Add `net.ipv4.tcp_keepalive_time = 120` and save the file
Invoke `sysctl -p /etc/sysctl.conf`
Verify using `cat /proc/sys/net/ipv4/tcp_keepalive_time`
Copy Azure database data to local database: Now you can use the SQL Server Management Studio to do this as below:
"Next" / "Next" / "Finish"
An enhancement of the hacky idea by Nick Craver to put custom HTML in a jquery dialog title:
var newtitle= '<b>HTML TITLE</b>';
$(".selectorUsedToCreateTheDialog").parent().find("span.ui-dialog-title").html(newtitle);
Consider the alternative:
<properties>
<javac.src.version>1.8</javac.src.version>
<javac.target.version>1.8</javac.target.version>
</properties>
It should be the same thing of maven.compiler.source/maven.compiler.target
but the above solution works for me, otherwise the second one gets the parent specification (I have a matrioska of .pom)
private String getMyPhoneNumber(){
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager)
getSystemService(Context.TELEPHONY_SERVICE);
return mTelephonyMgr.getLine1Number();
}
private String getMy10DigitPhoneNumber(){
String s = getMyPhoneNumber();
return s.substring(2);
}
From what I tested:
Session.Abandon(); // Does nothing
Session.Clear(); // Removes the data contained in the session
Example:
001: Session["test"] = "test";
002: Session.Abandon();
003: Print(Session["test"]); // Outputs: "test"
Session.Abandon does only set a boolean flag in the session-object to true. The calling web-server may react to that or not, but there is NO immediate action caused by ASP. (I checked that myself with the .net-Reflector)
In fact, you can continue working with the old session, by hitting the browser's back button once, and continue browsing across the website normally.
So, to conclude this: Use Session.Clear() and save frustration.
Remark: I've tested this behaviour on the ASP.net development server. The actual IIS may behave differently.
You can iterate through a std::map
object. Each iterator will point to a std::pair<const T,S>
where T
and S
are the same types you specified on your map
.
Here this would be:
for (std::map<int, MyClass>::iterator it = Map.begin(); it != Map.end(); ++it)
{
it->second.Method();
}
If you still want to use std::for_each
, pass a function that takes a std::pair<const int, MyClass>&
as an argument instead.
Example:
void CallMyMethod(std::pair<const int, MyClass>& pair) // could be a class static method as well
{
pair.second.Method();
}
And pass it to std::for_each
:
std::for_each(Map.begin(), Map.end(), CallMyMethod);
The function returns a static 2D array
const int N = 6;
int (*(MakeGridOfCounts)())[N] {
static int cGrid[N][N] = {{0, }, {0, }, {0, }, {0, }, {0, }, {0, }};
return cGrid;
}
int main() {
int (*arr)[N];
arr = MakeGridOfCounts();
}
You need to make the array static since it will be having a block scope, when the function call ends, the array will be created and destroyed. Static scope variables last till the end of program.
When calling a function that is declared with throws
in Swift, you must annotate the function call site with try
or try!
. For example, given a throwing function:
func willOnlyThrowIfTrue(value: Bool) throws {
if value { throw someError }
}
this function can be called like:
func foo(value: Bool) throws {
try willOnlyThrowIfTrue(value)
}
Here we annotate the call with try
, which calls out to the reader that this function may throw an exception, and any following lines of code might not be executed. We also have to annotate this function with throws
, because this function could throw an exception (i.e., when willOnlyThrowIfTrue()
throws, then foo
will automatically rethrow the exception upwards.
If you want to call a function that is declared as possibly throwing, but which you know will not throw in your case because you're giving it correct input, you can use try!
.
func bar() {
try! willOnlyThrowIfTrue(false)
}
This way, when you guarantee that code won't throw, you don't have to put in extra boilerplate code to disable exception propagation.
try!
is enforced at runtime: if you use try!
and the function does end up throwing, then your program's execution will be terminated with a runtime error.
Most exception handling code should look like the above: either you simply propagate exceptions upward when they occur, or you set up conditions such that otherwise possible exceptions are ruled out. Any clean up of other resources in your code should occur via object destruction (i.e. deinit()
), or sometimes via defer
ed code.
func baz(value: Bool) throws {
var filePath = NSBundle.mainBundle().pathForResource("theFile", ofType:"txt")
var data = NSData(contentsOfFile:filePath)
try willOnlyThrowIfTrue(value)
// data and filePath automatically cleaned up, even when an exception occurs.
}
If for whatever reason you have clean up code that needs to run but isn't in a deinit()
function, you can use defer
.
func qux(value: Bool) throws {
defer {
print("this code runs when the function exits, even when it exits by an exception")
}
try willOnlyThrowIfTrue(value)
}
Most code that deals with exceptions simply has them propagate upward to callers, doing cleanup on the way via deinit()
or defer
. This is because most code doesn't know what to do with errors; it knows what went wrong, but it doesn't have enough information about what some higher level code is trying to do in order to know what to do about the error. It doesn't know if presenting a dialog to the user is appropriate, or if it should retry, or if something else is appropriate.
Higher level code, however, should know exactly what to do in the event of any error. So exceptions allow specific errors to bubble up from where they initially occur to the where they can be handled.
Handling exceptions is done via catch
statements.
func quux(value: Bool) {
do {
try willOnlyThrowIfTrue(value)
} catch {
// handle error
}
}
You can have multiple catch statements, each catching a different kind of exception.
do {
try someFunctionThatThowsDifferentExceptions()
} catch MyErrorType.errorA {
// handle errorA
} catch MyErrorType.errorB {
// handle errorB
} catch {
// handle other errors
}
For more details on best practices with exceptions, see http://exceptionsafecode.com/. It's specifically aimed at C++, but after examining the Swift exception model, I believe the basics apply to Swift as well.
For details on the Swift syntax and error handling model, see the book The Swift Programming Language (Swift 2 Prerelease).
This one works fine for me with apis
import requests
data={'Id':id ,'name': name}
r = requests.post( url = 'https://apiurllink', data = data)
function foo(data)
{
// do stuff with JSON
}
var script = document.createElement('script');
script.src = '//example.com/path/to/jsonp?callback=foo'
document.getElementsByTagName('head')[0].appendChild(script);
// or document.head.appendChild(script) in modern browsers
just logic I can suggest take two arrays.
one is Char array
and another is int array.
convert ur input string to char array,get the position of char from char and int array.
dont expect source code here
To follow up on the comment by suhendri to Rory McCrossan answer. Here is an Action delegate example:
In child add:
public Action UpdateProgress; // In place of event handler declaration
// declare an Action delegate
.
.
.
private LoadData() {
this.UpdateProgress(); // call to Action delegate - MyMethod in
// parent
}
In parent add:
// The 3 lines in the parent becomes:
ChildClass child = new ChildClass();
child.UpdateProgress = this.MyMethod; // assigns MyMethod to child delegate
@( condition ? "true" : "false" )
Copied in my answer here from a similar question: Simple two-way encryption for C#.
Based on multiple answers and comments.
Code:
/// <summary>
/// Simple encryption/decryption using a random initialization vector
/// and prepending it to the crypto text.
/// </summary>
/// <remarks>Based on multiple answers in https://stackoverflow.com/questions/165808/simple-two-way-encryption-for-c-sharp </remarks>
public class SimpleAes : IDisposable
{
/// <summary>
/// Initialization vector length in bytes.
/// </summary>
private const int IvBytes = 16;
/// <summary>
/// Must be exactly 16, 24 or 32 characters long.
/// </summary>
private static readonly byte[] Key = Convert.FromBase64String("FILL ME WITH 16, 24 OR 32 CHARS");
private readonly UTF8Encoding _encoder;
private readonly ICryptoTransform _encryptor;
private readonly RijndaelManaged _rijndael;
public SimpleAes()
{
_rijndael = new RijndaelManaged {Key = Key};
_rijndael.GenerateIV();
_encryptor = _rijndael.CreateEncryptor();
_encoder = new UTF8Encoding();
}
public string Decrypt(string encrypted)
{
return _encoder.GetString(Decrypt(Convert.FromBase64String(encrypted)));
}
public void Dispose()
{
_rijndael.Dispose();
_encryptor.Dispose();
}
public string Encrypt(string unencrypted)
{
return Convert.ToBase64String(Encrypt(_encoder.GetBytes(unencrypted)));
}
private byte[] Decrypt(byte[] buffer)
{
// IV is prepended to cryptotext
byte[] iv = buffer.Take(IvBytes).ToArray();
using (ICryptoTransform decryptor = _rijndael.CreateDecryptor(_rijndael.Key, iv))
{
return decryptor.TransformFinalBlock(buffer, IvBytes, buffer.Length - IvBytes);
}
}
private byte[] Encrypt(byte[] buffer)
{
// Prepend cryptotext with IV
byte[] inputBuffer = _rijndael.IV.Concat(buffer).ToArray();
return _encryptor.TransformFinalBlock(inputBuffer, IvBytes, buffer.Length);
}
}
textarea {
border: 0;
overflow: auto; }
less CSS ^ you can't align the text to the bottom unfortunately.
You can do this using jQuery's .bind()
method. Check out the jsFiddle.
Html
<input id="myTextBox" type="text"/>
jQuery
$("#myTextBox").bind("change paste keyup", function() {
alert($(this).val());
});
You are trying to read the set value before Angular is done assigning.
Demo:
var testController = function ($scope, $timeout) {
console.log('test');
$timeout(function(){
console.log($scope.testInput);
},1000);
}
Ideally you should use $watch
as suggested by @Beterraba to get rid of the timer:
var testController = function ($scope) {
console.log('test');
$scope.$watch("testInput", function(){
console.log($scope.testInput);
});
}
If there is anyone like me who is experiencing this issue using Vue.js,
simply adding .prevent will do the trick: @click.prevent="someAction"
Unless there's a way to retrieve the old index of the elements after they've been shuffled, I'd do it one of two ways:
A) Make another list multi_shuffler = [0, 1, 2, ... , file.size()] and shuffle it. Loop over it to get the order for your shuffled file/image lists.
ArrayList newFileList = new ArrayList(); ArrayList newImgList = new ArrayList(); for ( i=0; i
or B) Make a StringWrapper class to hold the file/image names and combine the two lists you've already got into one: ArrayList combinedList;
call the request function from anywhere without having to use catch().
First, while handling most errors in one place is a good Idea, it's not that easy with requests. Some errors (e.g. 400 validation errors like: "username taken" or "invalid email") should be passed on.
So we now use a Promise based function:
const baseRequest = async (method: string, url: string, data: ?{}) =>
new Promise<{ data: any }>((resolve, reject) => {
const requestConfig: any = {
method,
data,
timeout: 10000,
url,
headers: {},
};
try {
const response = await axios(requestConfig);
// Request Succeeded!
resolve(response);
} catch (error) {
// Request Failed!
if (error.response) {
// Request made and server responded
reject(response);
} else if (error.request) {
// The request was made but no response was received
reject(response);
} else {
// Something happened in setting up the request that triggered an Error
reject(response);
}
}
};
you can then use the request like
try {
response = await baseRequest('GET', 'https://myApi.com/path/to/endpoint')
} catch (error) {
// either handle errors or don't
}
Interesting that Firefox will stop further processing of JavaScript after the relocate function. Chrome and IE will continue to display any other alerts and then reload the page. Try it:
<script type="text/javascript">
alert('foo');
window.location.reload(true);
alert('bar');
window.location.reload(true);
alert('foobar');
window.location.reload(true);
</script>
<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>
That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em'
as the measurement, you may want to use other units, like 'px'
.
EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:
In your HTML page, containing the <p>
tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:
<head>
<style type="text/css">
p { margin-left:5em; /* Or another measurement unit, like px */ }
</style>
</head>
<body>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>
So above, all <p>
elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:
<head>
<style type="text/css">
.container p { margin-left:5em; /* Or another measurement unit, like px */ }
</style>
</head>
<body>
<div class="container">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</div>
<p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>
In the example above, only the <p>
element inside the div, whose class name is 'container', will have the styles applied - and not the <p>
element outside the container.
In addition to the above, you can collect your styles together and remove the style element from the <head>
tag, replacing it with a <link>
tag, which points to an external CSS file. This external file is where you'd now put your <p>
tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.
As a addition to this, 'the project type is not supported by this installation' can occur if you're trying to open a project on a computer which does not contain the framework version that is targeted.
In my case I was trying to open a class library which was created on a machine with VS2012 and had defaulted the targeted framework to 4.5.
Since I knew this library wasn't using any 4.5 bits, I resolved the issue by editing the .csproj file from <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
to <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
(or whatever is appropriate for your project) and the library opened.
For OSX users:
Run the following command to install Memcached:
brew install memcached
The slicing problem in C++ arises from the value semantics of its objects, which remained mostly due to compatibility with C structs. You need to use explicit reference or pointer syntax to achieve "normal" object behavior found in most other languages that do objects, i.e., objects are always passed around by reference.
The short answers is that you slice the object by assigning a derived object to a base object by value, i.e. the remaining object is only a part of the derived object. In order to preserve value semantics, slicing is a reasonable behavior and has its relatively rare uses, which doesn't exist in most other languages. Some people consider it a feature of C++, while many considered it one of the quirks/misfeatures of C++.
As mentioned in the excellent answer by janoside, you need to construct the JSON string and set it as a StringEntity
.
To construct the JSON string, you can use any library or method you are comfortable with. Jackson library is one easy example:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
ObjectMapper mapper = new ObjectMapper();
ObjectNode node = mapper.createObjectNode();
node.put("name", "value"); // repeat as needed
String JSON_STRING = node.toString();
postMethod.setEntity(new StringEntity(JSON_STRING, ContentType.APPLICATION_JSON));
From the documentation:
__file__
is the pathname of the file from which the module was loaded, if it was loaded from a file. The__file__
attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.
From the mailing list thread linked by @kindall in a comment to the question:
I haven't tried to repro this particular example, but the reason is that we don't want to have to call getpwd() on every import nor do we want to have some kind of in-process variable to cache the current directory. (getpwd() is relatively slow and can sometimes fail outright, and trying to cache it has a certain risk of being wrong.)
What we do instead, is code in site.py that walks over the elements of sys.path and turns them into absolute paths. However this code runs before '' is inserted in the front of sys.path, so that the initial value of sys.path is ''.
For the rest of this, consider sys.path
not to include ''
.
So, if you are outside the part of sys.path
that contains the module, you'll get an absolute path. If you are inside the part of sys.path
that contains the module, you'll get a relative path.
If you load a module in the current directory, and the current directory isn't in sys.path
, you'll get an absolute path.
If you load a module in the current directory, and the current directory is in sys.path
, you'll get a relative path.
strcpy example:
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[]="Sample string" ;
char str2[40] ;
strcpy (str2,str1) ;
printf ("str1: %s\n",str1) ;
return 0 ;
}
Output: str1: Sample string
Your case:
A simple =
operator should do the job.
string str1="Sample string" ;
string str2 = str1 ;
Haven't you heard about the Comparable
interface being implemented by String
? If no, try to use
"abcda".compareTo("abcza")
And it will output a good root for a solution to your problem.
No need to use .each
. click
already binds to all div
occurrences.
$('div').click(function(e) {
..
});
Note: use hard binding such as .click
to make sure dynamically loaded elements don't get bound.
In case of not having the yaml file:
kubectl get pod PODNAME -n NAMESPACE -o yaml | kubectl replace --force -f -
@HostListener
is a decorator for the callback/event handler method, so remove the ;
at the end of this line:
@HostListener('click', ['$event.target']);
Here's a working plunker that I generated by copying the code from the API docs, but I put the onClick()
method on the same line for clarity:
import {Component, HostListener, Directive} from 'angular2/core';
@Directive({selector: 'button[counting]'})
class CountClicks {
numberOfClicks = 0;
@HostListener('click', ['$event.target']) onClick(btn) {
console.log("button", btn, "number of clicks:", this.numberOfClicks++);
}
}
@Component({
selector: 'my-app',
template: `<button counting>Increment</button>`,
directives: [CountClicks]
})
export class AppComponent {
constructor() { console.clear(); }
}
Host binding can also be used to listen to global events:
To listen to global events, a target must be added to the event name. The target can be window, document or body (reference)
@HostListener('document:keyup', ['$event'])
handleKeyboardEvent(kbdEvent: KeyboardEvent) { ... }
Über
is the German word for above
or over
(it's actually cognate with the English over
).
Hence, in this context, an uber-jar is an "over-jar", one level up from a simple JAR (a), defined as one that contains both your package and all its dependencies in one single JAR file. The name can be thought to come from the same stable as ultrageek, superman, hyperspace, and metadata, which all have similar meanings of "beyond the normal".
The advantage is that you can distribute your uber-jar and not care at all whether or not dependencies are installed at the destination, as your uber-jar actually has no dependencies.
All the dependencies of your own stuff within the uber-jar are also within that uber-jar. As are all dependencies of those dependencies. And so on.
(a) I probably shouldn't have to explain what a JAR is to a Java developer but I'll include it for completeness. It's a Java archive, basically a single file that typically contains a number of Java class files along with associated metadata and resources.
You can use Process.GetProcesses()
to get the currently running processes, then Process.Kill()
to kill a process.
Not just int's. But you can't define the value in the class declaration. If you have:
class classname
{
public:
static int const N;
}
in the .h file then you must have:
int const classname::N = 10;
in the .cpp file.
If I use the following query,
INSERT INTO xx_BLOB(ID,IMAGE)
VALUES(1,LOAD_FILE('E:/Images/xxx.png'));
Error: no such function: LOAD_FILE
In my case I wanted to load the same form each time I click, I didn't want the changes I've made on the file stays. It may not relevant to this post exactly, but this could be a potential solution on the client side without setting config for require. Instead of sending the contents directly, you can make a copy of the required file and keep the actual file intact.
LoadFile(filePath){
const file = require(filePath);
const result = angular.copy(file);
return result;
}
plt.subplots()
is a function that returns a tuple containing a figure and axes object(s). Thus when using fig, ax = plt.subplots()
you unpack this tuple into the variables fig
and ax
. Having fig
is useful if you want to change figure-level attributes or save the figure as an image file later (e.g. with fig.savefig('yourfilename.png')
). You certainly don't have to use the returned figure object but many people do use it later so it's common to see. Also, all axes objects (the objects that have plotting methods), have a parent figure object anyway, thus:
fig, ax = plt.subplots()
is more concise than this:
fig = plt.figure()
ax = fig.add_subplot(111)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$( document ).ready(function() {
$this = $('h1');
$this.css('color','#3498db');
$this.css('text-align','center');
$this.css('border','1px solid #ededed');
});
</script>
</head>
<body>
<h1>Title</h1>
</body>
</html>
You need not to worry about begin and end transaction. You have already apply @Transactional annotation, which internally open transaction when your method starts and ends when your method ends. So only required this is to persist your object in database.
@Transactional(readOnly = false, isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
public String persist(Details details){
details.getUsername();
details.getPassword();
Query query = em.createNativeQuery("db.details.find(username= "+details.getUsername()+"& password= "+details.getPassword());
em.persist(details);
System.out.println("Sucessful!");
return "persist";
}
EDIT : The problem seems to be with your configuration file. If you are using JPA then your configuration file should have below configuration
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" />
<bean id="jpaAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:database="ORACLE" p:showSql="true" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:persistenceUnitName="YourProjectPU"
p:persistenceXmlLocation="classpath*:persistence.xml"
p:dataSource-ref="dataSource" p:jpaVendorAdapter-ref="jpaAdapter">
<property name="loadTimeWeaver">
<bean
class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
<property name="persistenceProvider" ref="interceptorPersistenceProvider" />
</bean>
Try this:
Use back-ticks for NAME
CREATE TABLE `teachers` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`addr` varchar(255) NOT NULL,
`phone` int(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
From http://en.wikipedia.org/wiki/Printf_format_string
use 0 instead of spaces to pad a field when the width option is specified. For example, printf("%2d", 3)
results in " 3", while printf("%02d", 3)
results in "03".
You need to install all necessary packages with Android SDK Manager:
Android SDK Tools
Android SDK Platform-tools
Android SDK Build-tools
SDK Platform
ARM\Intel System Image
Android Support Repository
Android Support Library
This situation happens because you haven't installed/start service of ASP.net.
Use below command in windows 7,8,10.
%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i
You don't set PYTHONPATH
, you add entries to sys.path
. It's a list of directories that should be searched for Python packages, so you can just append your directories to that list.
sys.path.append('/path/to/whatever')
In fact, sys.path
is initialized by splitting the value of PYTHONPATH
on the path separator character (:
on Linux-like systems, ;
on Windows).
You can also add directories using site.addsitedir
, and that method will also take into account .pth
files existing within the directories you pass. (That would not be the case with directories you specify in PYTHONPATH
.)
To get the lines that contain the texts 8768
, 9875
or 2353
, use:
^.*(8768|9875|2353).*$
What it means:
^ from the beginning of the line
.* get any character except \n (0 or more times)
(8768|9875|2353) if the line contains the string '8768' OR '9875' OR '2353'
.* and get any character except \n (0 or more times)
$ until the end of the line
If you do want the literal *
char, you'd have to escape it:
^.*(\*8768|\*9875|\*2353).*$
$Group
is an object, but you will actually need to check if $Group.samaccountname.StartsWith("string")
.
Change $Group.StartsWith("S_G_")
to $Group.samaccountname.StartsWith("S_G_")
.
#!/usr/bin/python
str = raw_input("Enter a string ")
print "String entered above is %s" %str
strlist = [x for x in str ]
print "Strlist is %s" %strlist
strrev = list(reversed(strlist))
print "Strrev is %s" %strrev
if strlist == strrev :
print "String is palindrome"
else :
print "String is not palindrome"
You are getting arithmetic overflow. this means you are trying to make a conversion impossible to be made. This error is thrown when you try to make a conversion and the destiny data type is not enough to convert the origin data. For example:
If you try to convert 100.52 to decimal(4,2) you will get this error. The number 100.52 requires 5 positions and 2 of them are decimal.
Try to change the decimal precision to something like 16,2 or higher. Try with few records first then use it to all your select.
For Mac users:
Alongside the following: nvm, iterm2, zsh
I found using the .bashrc
rather than .profile
or .bash_profile
caused far less issues.
Simply by adding the latter to my .zshrc
file:
source $HOME/.bashrc
I think this a nice recursive solution with ES6 syntax:
const chunk = function(array, size) {_x000D_
if (!array.length) {_x000D_
return [];_x000D_
}_x000D_
const head = array.slice(0, size);_x000D_
const tail = array.slice(size);_x000D_
_x000D_
return [head, ...chunk(tail, size)];_x000D_
};_x000D_
_x000D_
console.log(chunk([1,2,3], 2));
_x000D_
if you are using django use forloop.counter
instead of loop.counter
<ul>
{% for user in userlist %}
<li>
{{ user }} {{forloop.counter}}
</li>
{% if forloop.counter == 1 %}
This is the First user
{% endif %}
{% endfor %}
</ul>
Add following codesnippet in your cofig file
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
Yeah, I just made the same 'noob' error and found this thread. I had in fact added the class to the solution and not to the project. So it looked like this:
Just adding this in the hope to be of help to someone.
Stan0 intial idea is not a good idea. There can be multiple files with the same name. Very error prone implementation. Stan0's second idea is the correct way.
When you first upload the file to google drive store its id (in SharedPreferences is probably easiest) for later use
ie.
file= mDrive.files().insert(body).execute(); //initial insert of file to google drive
whereverYouWantToStoreIt= file.getId(); //now you have the guaranteed unique id
//of the file just inserted. Store it and use it
//whenever you need to fetch this file
There is a library for this BarCode PHP. You just need to include a few files:
require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');
You can generate many types of barcodes, namely 1D or 2D. Add the required library:
require_once('class/BCGcode39.barcode.php');
Generate the colours:
// The arguments are R, G, and B for color.
$colorFront = new BCGColor(0, 0, 0);
$colorBack = new BCGColor(255, 255, 255);
After you have added all the codes, you will get this way:
Example
Since several have asked for an example here is what I was able to do to get it done
require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');
require_once('class/BCGcode128.barcode.php');
header('Content-Type: image/png');
$color_white = new BCGColor(255, 255, 255);
$code = new BCGcode128();
$code->parse('HELLO');
$drawing = new BCGDrawing('', $color_white);
$drawing->setBarcode($code);
$drawing->draw();
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);
If you want to actually create the image file so you can save it then change
$drawing = new BCGDrawing('', $color_white);
to
$drawing = new BCGDrawing('image.png', $color_white);
dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))
na.omit(dat)
x1 x2
1 1 100
3 3 300
5 5 500
You can put an <a>
element inside the <div>
and set it to display: block
and height: 100%
.
There is the RowIndex
property for the CurrentCell
property for the DataGridView.
datagridview.CurrentCell.RowIndex
Handle the SelectionChanged
event and find the index of the selected row as above.
I have tried this for my case and it'll work fine.
var multiplied_value = parseFloat(given_quantity*given_price).toFixed(3);
Sample output:
9.007
The exit()
and quit()
built in functions do just what you want. No import of sys needed.
Alternatively, you can raise SystemExit
, but you need to be careful not to catch it anywhere (which shouldn't happen as long as you specify the type of exception in all your try.. blocks).
Just simply right A
{{ date('h:i A', strtotime($varname->created_at))}}
More recent and much cleaner: use event.key
. No more arbitrary number codes!
input.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Backspace" || key === "Delete") {
return false;
}
});
No ... on all Windows platforms DWORD is 32 bits. LONGLONG or LONG64 is used for 64 bit types.
Using the Perl API you can get it this way: first you send a message to the bot from Telegram, then issue a getUpdates and the chat id must be there:
#!/usr/bin/perl
use Data::Dumper;
use WWW::Telegram::BotAPI;
my $TOKEN = 'blablabla';
my $api = WWW::Telegram::BotAPI->new (
token => $TOKEN
) or die "I can't connect";
my $out = $api->api_request ('getUpdates');
warn Dumper($out);
my $chat_id = $out->{result}->[0]->{message}->{chat}->{id};
print "chat_id=$chat_id\n";
The id should be in chat_id but it may depend of the result, so I also added a dump of the whole result.
You can install the Perl API from https://github.com/Robertof/perl-www-telegram-botapi. It depends on your system but I installed easily running this on my Linux server:
$ sudo cpan WWW::Telegram::BotAPI
Hope this helps
Try This :
document.getElementById(<element_ID>).readOnly=true;
Here's another reason: All the header paths seemed fine, but we still had an error in the precompiled (.pch) file trying to read a pod header
(i.e. #import <CocoaLumberjack/CocoaLumberjack.h>).
Looking at the raw build output, I finally noticed that the error was breaking our Watch OS Extension Target, not the main target we were building, because we were also importing the .pch precompiled header file into the Watch OS targets, and it was failing there. Make sure your accompanying Watch OS target settings don't try to import the .pch file (especially if you set that import from the master target setting, like I did!)
These are equivalent
char buf[10] = "";
char buf[10] = {0};
char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
These are equivalent
char buf[10] = " ";
char buf[10] = {' '};
char buf[10] = {' ', 0, 0, 0, 0, 0, 0, 0, 0, 0};
These are equivalent
char buf[10] = "a";
char buf[10] = {'a'};
char buf[10] = {'a', 0, 0, 0, 0, 0, 0, 0, 0, 0};
pattern="[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}"
This is pattern to enter the date for textbox in HTML5.
The first one[0-9]{1,2} will take only decimal number minimum 1 and maximum 2.
And other similarly.
Just download and install "Samsung Kies" from this link. and everything would work as required.
Before installing, uninstall the drivers you have installed for your device.
Update:
Two possible solutions:
for Arabic, I used Encoding.GetEncoding(1256)
. it is working good.
I was experiencing this problem on Samsung devices (fine on others). like zyamys suggested in his/her comment, I added the manifest.permission line but in addition to rather than instead of the original line, so:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.Manifest.permission.READ_PHONE_STATE" />
I'm targeting API 22, so don't need to explicitly ask for permissions.
By far my favourite all purpose shortcut is Ctrl+Shift+A
It does a search as you type through all the commands in intellij. Not only that but when you find the command you want it also displays the corresponding shortcut key next to it!
Maybe it is really late answer but if you want to navigate another page with param you can,
[routerLink]="['/user', user.id, 'details']"
also you shouldn't forget about routing config like ,
[path: 'user/:id/details', component:userComponent, pathMatch: 'full']
Dissenting voice here: after 5 years of rspec I don't like let
very much.
It becomes difficult to reason about setup when some things that have been declared in setup are not actually affecting state, while others are.
Eventually, out of frustration someone just changes let
to let!
(same thing without lazy evaluation) in order to get their spec working. If this works out for them, a new habit is born: when a new spec is added to an older suite and it doesn't work, the first thing the writer tries is to add bangs to random let
calls.
Pretty soon all the performance benefits are gone.
I would rather teach Ruby to my team than the tricks of rspec. Instance variables or method calls are useful everywhere in this project and others, let
syntax will only be useful in rspec.
let()
is good for expensive dependencies that we don't want to create over and over.
It also pairs well with subject
, allowing you to dry up repeated calls to multi-argument methods
Expensive dependencies repeated in many times, and methods with big signatures are both points where we could make the code better:
In all these cases, I can address the symptom of difficult tests with a soothing balm of rspec magic, or I can try address the cause. I feel like I spent way too much of the last few years on the former and now I want some better code.
To answer the original question: I would prefer not to, but I do still use let
. I mostly use it to fit in with the style of the rest of the team (it seems like most Rails programmers in the world are now deep into their rspec magic so that is very often). Sometimes I use it when I'm adding a test to some code that I don't have control of, or don't have time to refactor to a better abstraction: i.e. when the only option is the painkiller.
The .encode
method gets applied to a Unicode string to make a byte-string; but you're calling it on a byte-string instead... the wrong way 'round! Look at the codecs
module in the standard library and codecs.open
in particular for better general solutions for reading UTF-8 encoded text files. However, for the csv
module in particular, you need to pass in utf-8 data, and that's what you're already getting, so your code can be much simpler:
import csv
def unicode_csv_reader(utf8_data, dialect=csv.excel, **kwargs):
csv_reader = csv.reader(utf8_data, dialect=dialect, **kwargs)
for row in csv_reader:
yield [unicode(cell, 'utf-8') for cell in row]
filename = 'da.csv'
reader = unicode_csv_reader(open(filename))
for field1, field2, field3 in reader:
print field1, field2, field3
PS: if it turns out that your input data is NOT in utf-8, but e.g. in ISO-8859-1, then you do need a "transcoding" (if you're keen on using utf-8 at the csv
module level), of the form line.decode('whateverweirdcodec').encode('utf-8')
-- but probably you can just use the name of your existing encoding in the yield
line in my code above, instead of 'utf-8'
, as csv
is actually going to be just fine with ISO-8859-* encoded bytestrings.
In your User
model, add the following line in the User
class:
public $timestamps = true;
Now, whenever you save or update a user, Laravel will automatically update the created_at
and updated_at
fields.
Update:
If you want to set the created at manually you should use the date format Y-m-d H:i:s
. The problem is that the format you have used is not the same as Laravel uses for the created_at
field.
Update: Nov 2018 Laravel 5.6
"message": "Access level to App\\Note::$timestamps must be public",
Make sure you have the proper access level as well. Laravel 5.6 is public
.
Copy the image then paste it to drawables in the resource folder of you project in android studio.Make sure the name of your image is not too long and does not have any spacial characters.Then click SRC(source) under properties and look for your image click on it then it will automatically get imported to you image view on you emulator.
df[['fips', 'row']] = df['row'].str.split(' ', n=1, expand=True)
Here is a good example of base64 encoding byte arrays. It gets more complicated when you throw unicode characters in the mix to send things like PDF documents. After encoding a byte array the encoded string can be used as a JSON property value.
Apache commons offers good utilities:
byte[] bytes = getByteArr();
String base64String = Base64.encodeBase64String(bytes);
byte[] backToBytes = Base64.decodeBase64(base64String);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding
Java server side example:
public String getUnsecureContentBase64(String url)
throws ClientProtocolException, IOException {
//getUnsecureContent will generate some byte[]
byte[] result = getUnsecureContent(url);
// use apache org.apache.commons.codec.binary.Base64
// if you're sending back as a http request result you may have to
// org.apache.commons.httpclient.util.URIUtil.encodeQuery
return Base64.encodeBase64String(result);
}
JavaScript decode:
//decode URL encoding if encoded before returning result
var uriEncodedString = decodeURIComponent(response);
var byteArr = base64DecToArr(uriEncodedString);
//from mozilla
function b64ToUint6 (nChr) {
return nChr > 64 && nChr < 91 ?
nChr - 65
: nChr > 96 && nChr < 123 ?
nChr - 71
: nChr > 47 && nChr < 58 ?
nChr + 4
: nChr === 43 ?
62
: nChr === 47 ?
63
:
0;
}
function base64DecToArr (sBase64, nBlocksSize) {
var
sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length,
nOutLen = nBlocksSize ? Math.ceil((nInLen * 3 + 1 >> 2) / nBlocksSize) * nBlocksSize : nInLen * 3 + 1 >> 2, taBytes = new Uint8Array(nOutLen);
for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) {
nMod4 = nInIdx & 3;
nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4;
if (nMod4 === 3 || nInLen - nInIdx === 1) {
for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) {
taBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255;
}
nUint24 = 0;
}
}
return taBytes;
}
The file format would permit up to 255-character worksheet names, but if the Excel UI doesn't want you exceeding 31 characters, don't try to go beyond 31. App's full of weird undocumented limits and quirks, and feeding it files that are within spec but not within the range of things the testers would have tested usually causes REALLY strange behavior. (Personal favorite example: using the Excel 4.0 bytecode for an if() function, in a file with an Excel 97-style stringtable, disabled the toolbar button for bold in Excel 97.)
ddlutils is my best choice:http://db.apache.org/ddlutils/api/org/apache/ddlutils/platform/SqlBuilder.html
here is create example(groovy):
Platform platform = PlatformFactory.createNewPlatformInstance("oracle");//db2,...
//create schema
def db = new Database();
def t = new Table(name:"t1",description:"XXX");
def col1 = new Column(primaryKey:true,name:"id",type:"bigint",required:true);
t.addColumn(col1);
t.addColumn(new Column(name:"c2",type:"DECIMAL",size:"8,2"));
t.addColumn( new Column(name:"c3",type:"varchar"));
t.addColumn(new Column(name:"c4",type:"TIMESTAMP",description:"date"));
db.addTable(t);
println platform.getCreateModelSql(db, false, false)
//you can read Table Object from platform.readModelFromDatabase(....)
def sqlbuilder = platform.getSqlBuilder();
println "insert:"+sqlbuilder.getInsertSql(t,["id":1,c2:3],false);
println "update:"+sqlbuilder.getUpdateSql(t,["id":1,c2:3],false);
println "delete:"+sqlbuilder.getDeleteSql(t,["id":1,c2:3],false);
//http://db.apache.org/ddlutils/database-support.html
from learnyounode:
var http = require('http')
var bl = require('bl')
http.get(process.argv[2], function (response) {
response.pipe(bl(function (err, data) {
if (err)
return console.error(err)
data = data.toString()
console.log(data)
}))
})
Put this in main.py:
#!/usr/bin/python
import yoursubfile
Put this in yoursubfile.py
#!/usr/bin/python
print("hello")
Run it:
python main.py
It prints:
hello
Thus main.py
runs yoursubfile.py
There are 8 ways to answer this question, A more canonical answer is here: How to import other Python files?
MacPorts and Homebrew provide a coreutils package containing greadlink
(GNU readlink). Credit to Michael Kallweitt post in mackb.com.
brew install coreutils
greadlink -f file.txt
I'm using macOS Sierra (v10.12.1) Xcode v8.1 Swift 3.0.1 and here's what worked for me in ViewController.swift:
//
// ViewController.swift
// UIWebViewExample
//
// Created by Scott Maretick on 1/2/17.
// Copyright © 2017 Scott Maretick. All rights reserved.
//
import UIKit
import WebKit
class ViewController: UIViewController {
//added this code
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Your webView code goes here
let url = URL(string: "https://www.google.com")
if UIApplication.shared.canOpenURL(url!) {
UIApplication.shared.open(url!, options: [:], completionHandler: nil)
//If you want handle the completion block than
UIApplication.shared.open(url!, options: [:], completionHandler: { (success) in
print("Open url : \(success)")
})
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
};
Let me throw out some example code that I got from http://www3.ntu.edu.sg/home/ehchua/programming/java/DateTimeCalendar.html Then you can play around with different options until you understand it.
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTest {
public static void main(String[] args) {
Date now = new Date();
//This is just Date's toString method and doesn't involve SimpleDateFormat
System.out.println("toString(): " + now); // dow mon dd hh:mm:ss zzz yyyy
//Shows "Mon Oct 08 08:17:06 EDT 2012"
SimpleDateFormat dateFormatter = new SimpleDateFormat("E, y-M-d 'at' h:m:s a z");
System.out.println("Format 1: " + dateFormatter.format(now));
// Shows "Mon, 2012-10-8 at 8:17:6 AM EDT"
dateFormatter = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
System.out.println("Format 2: " + dateFormatter.format(now));
// Shows "Mon 2012.10.08 at 08:17:06 AM EDT"
dateFormatter = new SimpleDateFormat("EEEE, MMMM d, yyyy");
System.out.println("Format 3: " + dateFormatter.format(now));
// Shows "Monday, October 8, 2012"
// SimpleDateFormat can be used to control the date/time display format:
// E (day of week): 3E or fewer (in text xxx), >3E (in full text)
// M (month): M (in number), MM (in number with leading zero)
// 3M: (in text xxx), >3M: (in full text full)
// h (hour): h, hh (with leading zero)
// m (minute)
// s (second)
// a (AM/PM)
// H (hour in 0 to 23)
// z (time zone)
// (there may be more listed under the API - I didn't check)
}
}
Good luck!
Simplest is to use bisect and check one position back to see if the item is there:
def binary_search(a,x,lo=0,hi=-1):
i = bisect(a,x,lo,hi)
if i == 0:
return -1
elif a[i-1] == x:
return i-1
else:
return -1
Thanks to @IanRoberts, I had to use the normalize-space function on my nodes to check if they were empty.
<xsl:if test="((node/ABC!='') and (normalize-space(node/DEF)='') and (normalize-space(node/GHI)=''))">
This worked perfectly fine.
</xsl:if>
After you edited your question it's cler you're using ASP.NET. Things are pretty different there (because in that case a roundtrip to server is pretty discouraged). You can do same things with JavaScript (but to handle globalization with toUpperCase()
may be a pain) or you can use CSS classes (relying on browsers implementation). Simply declare this CSS rule:
.upper-case
{
text-transform: uppercase
}
And add upper-case class to your text-box:
<asp:TextBox ID="TextBox1" CssClass="upper-case" runat="server"/>
but it capitalize characters after pressing Enter key.
It depends where you put that code. If you put it in, for example, TextChanged
event it'll make upper case as you type.
You have a property that do exactly what you need: CharacterCasing
:
TextBox1.CharacterCasing = CharacterCasing.Upper;
It works more or less but it doesn't handle locales very well. For example in German language ß is SS when converted in upper case (Institut für Deutsche Sprache) and this property doesn't handle that.
You may mimic CharacterCasing
property adding this code in KeyPress
event handler:
e.KeyChar = Char.ToUpper(e.KeyChar);
Unfortunately .NET framework doesn't handle this properly and upper case of sharp s character is returned unchanged. An upper case version of ß exists and it's ? and it may create some confusion, for example a word containing "ss" and another word containing "ß" can't be distinguished if you convert in upper case using "SS"). Don't forget that:
However, in 2010 the use of the capital sharp s became mandatory in official documentation when writing geographical names in all-caps.
There isn't much you can do unless you add proper code for support this (and others) subtle bugs in .NET localization. Best advice I can give you is to use a custom dictionary per each culture you need to support.
Finally don't forget that this transformation may be confusing for your users: in Turkey, for example, there are two different versions of i upper case letter.
If text processing is important in your application you can solve many issues using specialized DLLs for each locale you support like Word Processors do.
What I usually do is to do not use standard .NET functions for strings when I have to deal with culture specific issues (I keep them only for text in invariant culture). I create a Unicode class with static methods for everything I need (character counting, conversions, comparison) and many specialized derived classes for each supported language. At run-time that static methods will user current thread culture name to pick proper implementation from a dictionary and to delegate work to that. A skeleton may be something like this:
abstract class Unicode
{
public static string ToUpper(string text)
{
return GetConcreteClass().ToUpperCore(text);
}
protected virtual string ToUpperCore(string text)
{
// Default implementation, overridden in derived classes if needed
return text.ToUpper();
}
private Dictionary<string, Unicode> _implementations;
private Unicode GetConcreteClass()
{
string cultureName = Thread.Current.CurrentCulture.Name;
// Check if concrete class has been loaded and put in dictionary
...
return _implementations[cultureName];
}
}
I'll then have an implementation specific for German language:
sealed class German : Unicode
{
protected override string ToUpperCore(string text)
{
// Very naive implementation, just to provide an example
return text.ToUpper().Replace("ß", "?");
}
}
True implementation may be pretty more complicate (not all OSes supports upper case ?) but take as a proof of concept. See also this post for other details about Unicode issues on .NET.
Do not include the '.exe' in your file path.
For example:
from selenium import webdriver
driver = webdriver.Chrome(executable_path='path/to/folder/chromedriver')
From IEEE floating-point exceptions in C++ :
This page will answer the following questions.
- My program just printed out 1.#IND or 1.#INF (on Windows) or nan or inf (on Linux). What happened?
- How can I tell if a number is really a number and not a NaN or an infinity?
- How can I find out more details at runtime about kinds of NaNs and infinities?
- Do you have any sample code to show how this works?
- Where can I learn more?
These questions have to do with floating point exceptions. If you get some strange non-numeric output where you're expecting a number, you've either exceeded the finite limits of floating point arithmetic or you've asked for some result that is undefined. To keep things simple, I'll stick to working with the double floating point type. Similar remarks hold for float types.
Debugging 1.#IND, 1.#INF, nan, and inf
If your operation would generate a larger positive number than could be stored in a double, the operation will return 1.#INF on Windows or inf on Linux. Similarly your code will return -1.#INF or -inf if the result would be a negative number too large to store in a double. Dividing a positive number by zero produces a positive infinity and dividing a negative number by zero produces a negative infinity. Example code at the end of this page will demonstrate some operations that produce infinities.
Some operations don't make mathematical sense, such as taking the square root of a negative number. (Yes, this operation makes sense in the context of complex numbers, but a double represents a real number and so there is no double to represent the result.) The same is true for logarithms of negative numbers. Both sqrt(-1.0) and log(-1.0) would return a NaN, the generic term for a "number" that is "not a number". Windows displays a NaN as -1.#IND ("IND" for "indeterminate") while Linux displays nan. Other operations that would return a NaN include 0/0, 0*8, and 8/8. See the sample code below for examples.
In short, if you get 1.#INF or inf, look for overflow or division by zero. If you get 1.#IND or nan, look for illegal operations. Maybe you simply have a bug. If it's more subtle and you have something that is difficult to compute, see Avoiding Overflow, Underflow, and Loss of Precision. That article gives tricks for computing results that have intermediate steps overflow if computed directly.
Similar to Pablo's answer above, but a shade cleaner :
str[1..-1]
Will return the array from 1 to the last character.
'Hello World'[1..-1]
=> "ello World"
ActionResult is an abstract class that can have several subtypes.
ViewResult - Renders a specifed view to the response stream
PartialViewResult - Renders a specifed partial view to the response stream
EmptyResult - An empty response is returned
RedirectResult - Performs an HTTP redirection to a specifed URL
RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
JsonResult - Serializes a given ViewData object to JSON format
JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
ContentResult - Writes content to the response stream without requiring a view
FileContentResult - Returns a file to the client
FileStreamResult - Returns a file to the client, which is provided by a Stream
FilePathResult - Returns a file to the client
This will give you some control over the clicking, and looks tidy
<script>
var timeOut = 0;
function onClick(but)
{
//code
clearTimeout(timeOut);
timeOut = setTimeout(function (){onClick(but)},1000);
}
</script>
<button onclick="onClick(this)">Start clicking</button>
Modern ES6 way (async/await)
const toBase64 = file => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
async function Main() {
const file = document.querySelector('#myfile').files[0];
console.log(await toBase64(file));
}
Main();
UPD:
If you want to catch errors
async function Main() {
const file = document.querySelector('#myfile').files[0];
const result = await toBase64(file).catch(e => Error(e));
if(result instanceof Error) {
console.log('Error: ', result.message);
return;
}
//...
}
You can use
$window.scrollTo(x, y);
where x
is the pixel along the horizontal axis and y
is the pixel along the vertical axis.
Scroll to top
$window.scrollTo(0, 0);
Focus on element
$window.scrollTo(0, angular.element('put here your element').offsetTop);
Update:
Also you can use $anchorScroll
I have a similar problem, I tested adding code and found some interesting results. With this code I add, I can deduce that depending on the "provider" to use, the firm can be different? (because the data included in the encryption is not always equal in all providers).
Conclusion.- Signature Decipher= ???(trash) + DigestInfo (if we know the value of "trash", the digital signatures will be equal)
Input data: This is the message being signed
Digest: 62b0a9ef15461c82766fb5bdaae9edbe4ac2e067
DigestInfo: 3021300906052b0e03021a0500041462b0a9ef15461c82766fb5bdaae9edbe4ac2e067
Signature Decipher: 1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff003021300906052b0e03021a0500041462b0a9ef15461c82766fb5bdaae9edbe4ac2e067
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.bouncycastle.asn1.x509.DigestInfo;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
public class prueba {
/**
* @param args
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws SignatureException
* @throws NoSuchPaddingException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*///
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
// TODO Auto-generated method stub
KeyPair keyPair = KeyPairGenerator.getInstance("RSA","BC").generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey puKey = keyPair.getPublic();
String plaintext = "This is the message being signed";
// Hacer la firma
Signature instance = Signature.getInstance("SHA1withRSA","BC");
instance.initSign(privateKey);
instance.update((plaintext).getBytes());
byte[] signature = instance.sign();
// En dos partes primero hago un Hash
MessageDigest digest = MessageDigest.getInstance("SHA1", "BC");
byte[] hash = digest.digest((plaintext).getBytes());
// El digest es identico a openssl dgst -sha1 texto.txt
//MessageDigest sha1 = MessageDigest.getInstance("SHA1","BC");
//byte[] digest = sha1.digest((plaintext).getBytes());
AlgorithmIdentifier digestAlgorithm = new AlgorithmIdentifier(new
DERObjectIdentifier("1.3.14.3.2.26"), null);
// create the digest info
DigestInfo di = new DigestInfo(digestAlgorithm, hash);
byte[] digestInfo = di.getDEREncoded();
//Luego cifro el hash
Cipher cipher = Cipher.getInstance("RSA","BC");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] cipherText = cipher.doFinal(digestInfo);
//byte[] cipherText = cipher.doFinal(digest2);
Cipher cipher2 = Cipher.getInstance("RSA","BC");
cipher2.init(Cipher.DECRYPT_MODE, puKey);
byte[] cipherText2 = cipher2.doFinal(signature);
System.out.println("Input data: " + plaintext);
System.out.println("Digest: " + bytes2String(hash));
System.out.println("Signature: " + bytes2String(signature));
System.out.println("Signature2: " + bytes2String(cipherText));
System.out.println("DigestInfo: " + bytes2String(digestInfo));
System.out.println("Signature Decipher: " + bytes2String(cipherText2));
}
Client validation issues can occur because of MVC bug (even in MVC 5) in jquery.validate.unobtrusive.min.js which does not accept date/datetime format in any way. Unfortunately you have to solve it manually.
My finally working solution:
$(function () {
$.validator.methods.date = function (value, element) {
return this.optional(element) || moment(value, "DD.MM.YYYY", true).isValid();
}
});
You have to include before:
@Scripts.Render("~/Scripts/jquery-3.1.1.js")
@Scripts.Render("~/Scripts/jquery.validate.min.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
@Scripts.Render("~/Scripts/moment.js")
You can install moment.js using:
Install-Package Moment.js
I'm surprised that none of the answers reference Object.assign since that's the technique I use whenever I think about "composition" in JavaScript.
And it works as expected in TypeScript:
interface IExisting {
userName: string
}
interface INewStuff {
email: string
}
const existingObject: IExisting = {
userName: "jsmith"
}
const objectWithAllProps: IExisting & INewStuff = Object.assign({}, existingObject, {
email: "[email protected]"
})
console.log(objectWithAllProps.email); // [email protected]
Advantages
any
type at all&
when declaring the type of objectWithAllProps
), which clearly communicates that we're composing a new type on-the-fly (i.e. dynamically)Things to be aware of
existingObject
stays untouched and therefore doesn't have an email
property. For most functional-style programmers, that's a good thing since the result is the only new change).Using Newtonsoft.Json makes it really easier:
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string json = JsonConvert.SerializeObject(product);
Documentation: Serializing and Deserializing JSON
I won't make such a big deal from this question.
It's not like choosing your new wife or car.
I'd never run any of these on a production server, so, to run just some quick tests any of them are equally good.
You can write an object to a file using writeObject
in ObjectOutputStream
Your calculation is correct for DATE
types, but if your values are timestamps, you should probably use EXTRACT
(or DATE_PART) to be sure to get only the difference in full days;
EXTRACT(DAY FROM MAX(joindate)-MIN(joindate)) AS DateDifference
An SQLfiddle to test with. Note the timestamp difference being 1 second less than 2 full days.
Usually you hear Task is a higher level concept than thread... and that's what this phrase means:
You can't use Abort/ThreadAbortedException, you should support
cancel event in your "business code" periodically testing token.IsCancellationRequested
flag (also avoid long or timeoutless connections e.g. to db, otherwise you will never get a chance to test this flag). By the similar reason Thread.Sleep(delay)
call should be replaced with Task.Delay(delay, token)
call (passing token inside to have possibility to interrupt delay).
There are no thread's Suspend
and Resume
methods functionality with tasks. Instance of task can't be reused either.
But you get two new tools:
a) continuations
// continuation with ContinueWhenAll - execute the delegate, when ALL
// tasks[] had been finished; other option is ContinueWhenAny
Task.Factory.ContinueWhenAll(
tasks,
() => {
int answer = tasks[0].Result + tasks[1].Result;
Console.WriteLine("The answer is {0}", answer);
}
);
b) nested/child tasks
//StartNew - starts task immediately, parent ends whith child
var parent = Task.Factory.StartNew
(() => {
var child = Task.Factory.StartNew(() =>
{
//...
});
},
TaskCreationOptions.AttachedToParent
);
So system thread is completely hidden from task, but still task's code is executed in the concrete system thread. System threads are resources for tasks and ofcourse there is still thread pool under the hood of task's parallel execution. There can be different strategies how thread get new tasks to execute. Another shared resource TaskScheduler cares about it. Some problems that TaskScheduler solves 1) prefer to execute task and its conitnuation in the same thread minimizing switching cost - aka inline execution) 2) prefer execute tasks in an order they were started - aka PreferFairness 3) more effective distribution of tasks between inactive threads depending on "prior knowledge of tasks activity" - aka Work Stealing. Important: in general "async" is not same as "parallel". Playing with TaskScheduler options you can setup async tasks be executed in one thread synchronously. To express parallel code execution higher abstractions (than Tasks) could be used: Parallel.ForEach
, PLINQ
, Dataflow
.
Tasks are integrated with C# async/await features aka Promise Model, e.g there requestButton.Clicked += async (o, e) => ProcessResponce(await client.RequestAsync(e.ResourceName));
the execution of client.RequestAsync
will not block UI thread. Important: under the hood Clicked
delegate call is absolutely regular (all threading is done by compiler).
That is enough to make a choice. If you need to support Cancel functionality of calling legacy API that tends to hang (e.g. timeoutless connection) and for this case supports Thread.Abort(), or if you are creating multithread background calculations and want to optimize switching between threads using Suspend/Resume, that means to manage parallel execution manually - stay with Thread. Otherwise go to Tasks because of they will give you easy manipulate on groups of them, are integrated into the language and make developers more productive - Task Parallel Library (TPL) .
I needed this for SQL Server. Here it is:
UPDATE user_account
SET student_education_facility_id = cnt.education_facility_id
from (
SELECT user_account_id,education_facility_id
FROM user_account
WHERE user_type = 'ROLE_TEACHER'
) as cnt
WHERE user_account.user_type = 'ROLE_STUDENT' and cnt.user_account_id = user_account.teacher_id
I think it works with other RDBMSes (please confirm). I like the syntax because it's extensible.
The format I needed was this actually:
UPDATE table1
SET f1 = cnt.computed_column
from (
SELECT id,computed_column --can be any complex subquery
FROM table1
) as cnt
WHERE cnt.id = table1.id
Update 2019
Why not use an input-group?
<div class="input-group col-md-4">
<input class="form-control py-2" type="search" value="search" id="example-search-input">
<span class="input-group-append">
<button class="btn btn-outline-secondary" type="button">
<i class="fa fa-search"></i>
</button>
</span>
</div>
And, you can make it appear inside the input using the border utils...
<div class="input-group col-md-4">
<input class="form-control py-2 border-right-0 border" type="search" value="search" id="example-search-input">
<span class="input-group-append">
<button class="btn btn-outline-secondary border-left-0 border" type="button">
<i class="fa fa-search"></i>
</button>
</span>
</div>
Or, using a input-group-text
w/o the gray background so the icon appears inside the input...
<div class="input-group">
<input class="form-control py-2 border-right-0 border" type="search" value="search" id="example-search-input">
<span class="input-group-append">
<div class="input-group-text bg-transparent"><i class="fa fa-search"></i></div>
</span>
</div>
Alternately, you can use the grid (row
>col-
) with no gutter spacing:
<div class="row no-gutters">
<div class="col">
<input class="form-control border-secondary border-right-0 rounded-0" type="search" value="search" id="example-search-input4">
</div>
<div class="col-auto">
<button class="btn btn-outline-secondary border-left-0 rounded-0 rounded-right" type="button">
<i class="fa fa-search"></i>
</button>
</div>
</div>
Or, prepend the icon like this...
<div class="input-group">
<span class="input-group-prepend">
<div class="input-group-text bg-transparent border-right-0">
<i class="fa fa-search"></i>
</div>
</span>
<input class="form-control py-2 border-left-0 border" type="search" value="..." id="example-search-input" />
<span class="input-group-append">
<button class="btn btn-outline-secondary border-left-0 border" type="button">
Search
</button>
</span>
</div>
Demo of all Bootstrap 4 icon input options
I've created a static "startup" file and added the code to force the DLL to be copied to the bin folder in it as a way to separate this 'configuration'.
[DbConfigurationType(typeof(DbContextConfiguration))]
public static class Startup
{
}
public class DbContextConfiguration : DbConfiguration
{
public DbContextConfiguration()
{
// This is needed to force the EntityFramework.SqlServer DLL to be copied to the bin folder
SetProviderServices(SqlProviderServices.ProviderInvariantName, SqlProviderServices.Instance);
}
}
Just in case there is someone out there who's a bit new like me, double check that you are spelling your header folders correctly.
For example:
<#include "Component/BoxComponent.h"
This will result in the error. Instead, it needs to be:
<#include "Components/BoxComponent.h"