TV Sony Bravia KLV-32T550A Below mention config works greatly You should add the following into the /boot/config.txt to force the output to HDMI and set the
resolution 82 1920x1080 60Hz 1080p
hdmi_ignore_edid=0xa5000080
hdmi_force_hotplug=1
hdmi_boost=7
hdmi_group=2
hdmi_mode=82
hdmi_drive=1
Take a look at this: Entity Framework don't create database
I would try giving the database a different name. Sometimes you can run into problems with SQL Express when trying to create a database with the same name a second time. There is a way to fix this using SQL Server Management Studio but it's generally easier to just use a different database name.
Edit This answer was accepted because it confirms the bug and the workaround used by OP (renaming database could help). I totally agree that renaming the database is not really an acceptable way, and does not totally solve the issue. Unfortunatly I didn't check the other ways to really solve it in SSMS.
Two nitpicks. (1) Best not to use string literals for column alias - that is deprecated. (2) Just use style 120 to get the same value.
CASE
WHEN CreatedDate = '19000101' THEN ''
WHEN CreatedDate = '18000101' THEN ''
ELSE Convert(varchar(19), CreatedDate, 120)
END AS [Created Date]
If you want all the bars to get the same color (fill
), you can easily add it inside geom_bar
.
ggplot(data=df, aes(x=c1+c2/2, y=c3)) +
geom_bar(stat="identity", width=c2, fill = "#FF6666")
Add fill = the_name_of_your_var
inside aes
to change the colors depending of the variable :
c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2)
Use scale_fill_manual()
if you want to manually the change of colors.
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2) +
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))
And this is if copying a single property to another list is needed:
targetList.AddRange(sourceList.Select(i => i.NeededProperty));
The mostly used StringUtils class is the Apache Commons Lang StringUtils (org.apache.commons.lang3.StringUtils). To use this class you first have to download the Apache Commons Lang3 package then you have to add it to your project libraries.
You can go to this link to get more details: http://examples.javacodegeeks.com/core-java/apache/commons/lang3/stringutils/org-apache-commons-lang3-stringutils-example/
If you want to remove the namespace you may also want to remove the version, to save you searching I've added that functionality so the below code will do both.
I've also wrapped it in a generic method as I'm creating very large xml files which are too large to serialize in memory so I've broken my output file down and serialize it in smaller "chunks":
public static string XmlSerialize<T>(T entity) where T : class
{
// removes version
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
XmlSerializer xsSubmit = new XmlSerializer(typeof(T));
using (StringWriter sw = new StringWriter())
using (XmlWriter writer = XmlWriter.Create(sw, settings))
{
// removes namespace
var xmlns = new XmlSerializerNamespaces();
xmlns.Add(string.Empty, string.Empty);
xsSubmit.Serialize(writer, entity, xmlns);
return sw.ToString(); // Your XML
}
}
Just execute
sudo npm i --save
That's all
Specifying a non-static position, e.g., position: absolute/relative
on a node means that it will be used as the reference for absolutely positioned elements within it http://jsfiddle.net/E5eEk/1/
See https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning#Positioning_contexts
We can change the positioning context — which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's ancestors.
#outer {_x000D_
min-width: 2000px; _x000D_
min-height: 1000px; _x000D_
background: #3e3e3e; _x000D_
position:relative_x000D_
}_x000D_
_x000D_
#inner {_x000D_
left: 1%; _x000D_
top: 45px; _x000D_
width: 50%; _x000D_
height: auto; _x000D_
position: absolute; _x000D_
z-index: 1;_x000D_
}_x000D_
_x000D_
#inner-inner {_x000D_
background: #efffef;_x000D_
position: absolute; _x000D_
height: 400px; _x000D_
right: 0px; _x000D_
left: 0px;_x000D_
}
_x000D_
<div id="outer">_x000D_
<div id="inner">_x000D_
<div id="inner-inner"></div>_x000D_
</div>_x000D_
</div>
_x000D_
the default encoding of a HTTP POST is ISO-8859-1.
else you have to look at the Content-Type header that will then look like
Content-Type: application/x-www-form-urlencoded ; charset=UTF-8
You can maybe declare your form with
<form enctype="application/x-www-form-urlencoded;charset=UTF-8">
or
<form accept-charset="UTF-8">
to force the encoding.
Some references :
Yes, it is possible.
try:
...
except FirstException:
handle_first_one()
except SecondException:
handle_second_one()
except (ThirdException, FourthException, FifthException) as e:
handle_either_of_3rd_4th_or_5th()
except Exception:
handle_all_other_exceptions()
See: http://docs.python.org/tutorial/errors.html
The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)
res/drawable/day_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@drawable/dayselectionunselected"
android:state_checked="false"/>
<item android:drawable="@drawable/daysselectionselected"
android:state_checked="true"/>
<item android:drawable="@drawable/dayselectionunselected"/>
</selector>
res/layout/my_layout.xml
<CheckBox
android:id="@+id/check"
android:layout_width="39dp"
android:layout_height="39dp"
android:background="@drawable/day_selector"
android:button="@null"
android:gravity="center"
android:text="S"
android:textColor="@color/black"
android:textSize="12sp" />
If you want to do some high-powered debugging, you can subscribe to every change of the state and pause the app to see what's going on in detail as follows.
store.jsstore.subscribe( () => {
console.log('state\n', store.getState());
debugger;
});
Place that in the file where you do createStore
.
To copy the state
object from the console to the clipboard, follow these steps:
Right-click an object in Chrome's console and select Store as Global Variable from the context menu. It will return something like temp1 as the variable name.
Chrome also has a copy()
method, so copy(temp1)
in the console should copy that object to your clipboard.
https://stackoverflow.com/a/25140576
https://scottwhittaker.net/chrome-devtools/2016/02/29/chrome-devtools-copy-object.html
You can view the object in a json viewer like this one: http://jsonviewer.stack.hu/
You can compare two json objects here: http://www.jsondiff.com/
You can use the below code to submit the form using JavaScript:
document.getElementById('FormID').submit();
If you're in quircks mode (thanks @Niet the Dark Absol):
document.body.scrollTop = document.documentElement.scrollTop = 0;
If you're in strict mode:
document.documentElement.scrollTop = 0;
No need for jQuery here.
I guess you can install it via Parallel or in any other Virtual machine with windows in it
Use Location Listener Method
@Override
public void onLocationChanged(Location loc) {
Double lat = loc.getLatitude();
Double lng = loc.getLongitude();
}
If Visual Studio is NOT your thing, and instead you are using VS Code, then this link will guide you thru the installer to get C++ running on your Windows.
You only needs to complete the Pre-Requisites part. https://code.visualstudio.com/docs/cpp/config-msvc/#_prerequisites
This is similar with other answers, but this link will probably age better than some of the responses here.
PS: don't forget to run pip install --upgrade setuptools
Took some searching and reading to find a method that suited my situation, on form submit, run ajax to a remote php script, on success/failure inform user, on complete clear the form.
I had some default values, all other methods involved .val('') thereby not resetting but clearing the form.
I got this too work by adding a reset button to the form, which had an id of myform
:
$("#myform > input[type=reset]").trigger('click');
This for me had the correct outcome on resetting the form, oh and dont forget the
event.preventDefault();
to stop the form submitting in browser, like I did :).
Regards
Jacko
Here's an example using the format()
function:
>>> "{:.2E}".format(Decimal('40800000000.00000000000000'))
'4.08E+10'
Instead of format, you can also use f-strings:
>>> f"{Decimal('40800000000.00000000000000'):.2E}"
'4.08E+10'
I wrote an updated version of Kees C. Bakker's answer:
const hasVerticalScroll = (node) => {
if (!node) {
if (window.innerHeight) {
return document.body.offsetHeight > window.innerHeight
}
return (document.documentElement.scrollHeight > document.documentElement.offsetHeight)
|| (document.body.scrollHeight > document.body.offsetHeight)
}
return node.scrollHeight > node.offsetHeight
}
if (hasVerticalScroll(document.querySelector('body'))) {
this.props.handleDisableDownScrollerButton()
}
The function returns true or false depending whether the page has a vertical scrollbar or not.
For example:
const hasVScroll = hasVerticalScroll(document.querySelector('body'))
if (hasVScroll) {
console.log('HAS SCROLL', hasVScroll)
}
Sometimes the page extends on scroll to buttom (for example in social networks), to scroll down to the end (ultimate buttom of the page) I use this script:
var scrollInterval = setInterval(function() {
document.documentElement.scrollTop = document.documentElement.scrollHeight;
}, 50);
And if you are in browser's javascript console, it might be useful to be able to stop the scrolling, so add:
var stopScroll = function() { clearInterval(scrollInterval); };
And then use stopScroll();
.
If you need to scroll to particular element, use:
var element = document.querySelector(".element-selector");
element.scrollIntoView();
Or universal script for autoscrolling to specific element (or stop page scrolling interval):
var notChangedStepsCount = 0;
var scrollInterval = setInterval(function() {
var element = document.querySelector(".element-selector");
if (element) {
// element found
clearInterval(scrollInterval);
element.scrollIntoView();
} else if((document.documentElement.scrollTop + window.innerHeight) != document.documentElement.scrollHeight) {
// no element -> scrolling
notChangedStepsCount = 0;
document.documentElement.scrollTop = document.documentElement.scrollHeight;
} else if (notChangedStepsCount > 20) {
// no more space to scroll
clearInterval(scrollInterval);
} else {
// waiting for possible extension (autoload) of the page
notChangedStepsCount++;
}
}, 50);
TLDR; Pandas groupby.agg
has a new, easier syntax for specifying (1) aggregations on multiple columns, and (2) multiple aggregations on a column. So, to do this for pandas >= 0.25, use
df.groupby('dummy').agg(Mean=('returns', 'mean'), Sum=('returns', 'sum'))
Mean Sum
dummy
1 0.036901 0.369012
OR
df.groupby('dummy')['returns'].agg(Mean='mean', Sum='sum')
Mean Sum
dummy
1 0.036901 0.369012
Pandas has changed the behavior of GroupBy.agg
in favour of a more intuitive syntax for specifying named aggregations. See the 0.25 docs section on Enhancements as well as relevant GitHub issues GH18366 and GH26512.
From the documentation,
To support column-specific aggregation with control over the output column names, pandas accepts the special syntax in
GroupBy.agg()
, known as “named aggregation”, where
- The keywords are the output column names
- The values are tuples whose first element is the column to select and the second element is the aggregation to apply to that column. Pandas provides the pandas.NamedAgg namedtuple with the fields ['column', 'aggfunc'] to make it clearer what the arguments are. As usual, the aggregation can be a callable or a string alias.
You can now pass a tuple via keyword arguments. The tuples follow the format of (<colName>, <aggFunc>)
.
import pandas as pd
pd.__version__
# '0.25.0.dev0+840.g989f912ee'
# Setup
df = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
'height': [9.1, 6.0, 9.5, 34.0],
'weight': [7.9, 7.5, 9.9, 198.0]
})
df.groupby('kind').agg(
max_height=('height', 'max'), min_weight=('weight', 'min'),)
max_height min_weight
kind
cat 9.5 7.9
dog 34.0 7.5
Alternatively, you can use pd.NamedAgg
(essentially a namedtuple) which makes things more explicit.
df.groupby('kind').agg(
max_height=pd.NamedAgg(column='height', aggfunc='max'),
min_weight=pd.NamedAgg(column='weight', aggfunc='min')
)
max_height min_weight
kind
cat 9.5 7.9
dog 34.0 7.5
It is even simpler for Series, just pass the aggfunc to a keyword argument.
df.groupby('kind')['height'].agg(max_height='max', min_height='min')
max_height min_height
kind
cat 9.5 9.1
dog 34.0 6.0
Lastly, if your column names aren't valid python identifiers, use a dictionary with unpacking:
df.groupby('kind')['height'].agg(**{'max height': 'max', ...})
In more recent versions of pandas leading upto 0.24, if using a dictionary for specifying column names for the aggregation output, you will get a FutureWarning
:
df.groupby('dummy').agg({'returns': {'Mean': 'mean', 'Sum': 'sum'}})
# FutureWarning: using a dict with renaming is deprecated and will be removed
# in a future version
Using a dictionary for renaming columns is deprecated in v0.20. On more recent versions of pandas, this can be specified more simply by passing a list of tuples. If specifying the functions this way, all functions for that column need to be specified as tuples of (name, function) pairs.
df.groupby("dummy").agg({'returns': [('op1', 'sum'), ('op2', 'mean')]})
returns
op1 op2
dummy
1 0.328953 0.032895
Or,
df.groupby("dummy")['returns'].agg([('op1', 'sum'), ('op2', 'mean')])
op1 op2
dummy
1 0.328953 0.032895
In the manifest file change to this:
android:theme="@style/Theme.AppCompat.Light.NoActionBar" >
You need to use ECHO
. Also, put the quotes around the entire file path if it contains spaces.
One other note, use >
to overwrite a file if it exists or create if it does not exist. Use >>
to append to an existing file or create if it does not exist.
Overwrite the file with a blank line:
ECHO.>"C:\My folder\Myfile.log"
Append a blank line to a file:
ECHO.>>"C:\My folder\Myfile.log"
Append text to a file:
ECHO Some text>>"C:\My folder\Myfile.log"
Append a variable to a file:
ECHO %MY_VARIABLE%>>"C:\My folder\Myfile.log"
You could throw the enum value and string into an STL map. Then you could use it like so.
return myStringMap[Enum::Apple];
Using JavaScript and jQuery:
<script src="js/jquery.js"></script>
...
<video id="vid" width="1280" height="720" src="v/myvideo01.mp4" controls autoplay></video>
...
function chVid(vid) {
$("#vid").attr("src",vid);
}
...
<div onclick="chVid('v/myvideo02.mp4')">See my video #2!</div>
A simple answer would be : No, it doesn't
Explanation : According to the definition of unique constraints (SQL-92)
A unique constraint is satisfied if and only if no two rows in a table have the same non-null values in the unique columns
This statement can have two interpretations as :
NULL
and NULL
is not allowedNULL
and NULL
is fine, but StackOverflow
and StackOverflow
is not allowedSince MySQL follows second interpretation, multiple NULL
values are allowed in UNIQUE
constraint column. Second, if you would try to understand the concept of NULL
in SQL, you will find that two NULL
values can be compared at all since NULL
in SQL refers to unavailable or unassigned value (you can't compare nothing with nothing). Now, if you are not allowing multiple NULL
values in UNIQUE
constraint column, you are contracting the meaning of NULL
in SQL. I would summarise my answer by saying :
MySQL supports UNIQUE constraint but not on the cost of ignoring NULL values
The default schema for the user could be changed with the following query and avoids changing the property every time a table is to be created.
USE [DBName]
GO
ALTER USER [YourUserName] WITH DEFAULT_SCHEMA = [YourSchema]
GO
Let's go to the source -- 2.6.32, for example. The message is printed by show_signal_msg() function in arch/x86/mm/fault.c if the show_unhandled_signals sysctl is set.
"error" is not an errno nor a signal number, it's a "page fault error code" -- see definition of enum x86_pf_error_code.
"[7fa44d2f8000+f6f000]" is starting address and size of virtual memory area where offending object was mapped at the time of crash. Value of "ip" should fit in this region. With this info in hand, it should be easy to find offending code in gdb.
I my case (run from Windows 10)
1) Rename the file myDockerFile.Dockerfile
to Dockerfile
(without file extension).
Then run from outside the folder this command:
docker build .\Docker-LocalNifi\
This is working for me and for my colleagues at work, hope that will also work for you
A way that i do this on intellij is setting an environment variable on the command like so:
In this case i am setting the profile to test
$(document).ready(function(){ _x000D_
$("#btn_clone").click(function(){ _x000D_
$("#a_clone").clone().appendTo("#b_clone"); _x000D_
}); _x000D_
});
_x000D_
.container{_x000D_
padding: 15px;_x000D_
border: 12px solid #23384E;_x000D_
background: #28BAA2;_x000D_
margin-top: 10px;_x000D_
}
_x000D_
<!DOCTYPE html> _x000D_
<html> _x000D_
<head> _x000D_
<title>jQuery Clone Method</title> _x000D_
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> _x000D_
_x000D_
_x000D_
</head> _x000D_
<body> _x000D_
<div class="container">_x000D_
<p id="a_clone"><b> This is simple example of clone method.</b></p> _x000D_
<p id="b_clone"><b>Note:</b>Click The Below button Click Me</p> _x000D_
<button id="btn_clone">Click Me!</button> _x000D_
</div> _x000D_
</body> _x000D_
</html>
_x000D_
Well, why don't you store the current selected value, and when the selected item is changed you will have the old value stored? (and you can update it again as you wish)
About using Tuple in Converter, it would be better to use 'object' instead of 'string', so that it works for all types of objects without limitation of 'string' object.
public class YourConverter : IMultiValueConverter
{
public object Convert(object[] values, ...)
{
Tuple<object, object> tuple = new Tuple<object, object>(values[0], values[1]);
return tuple;
}
}
Then execution logic in Command could be like this
public void OnExecute(object parameter)
{
var param = (Tuple<object, object>) parameter;
// e.g. for two TextBox object
var txtZip = (System.Windows.Controls.TextBox)param.Item1;
var txtCity = (System.Windows.Controls.TextBox)param.Item2;
}
and multi-bind with converter to create the parameters (with two TextBox objects)
<Button Content="Zip/City paste" Command="{Binding PasteClick}" >
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource YourConvert}">
<Binding ElementName="txtZip"/>
<Binding ElementName="txtCity"/>
</MultiBinding>
</Button.CommandParameter>
</Button>
You could simply have the function "remove itself"
?function Once(){
console.log("run");
Once = undefined;
}
Once(); // run
Once(); // Uncaught TypeError: undefined is not a function
But this may not be the best answer if you don't want to be swallowing errors.
You could also do this:
function Once(){
console.log("run");
Once = function(){};
}
Once(); // run
Once(); // nothing happens
I need it to work like smart pointer, if there no elements from type A it can be executed, if there is one or more A elements the function can't be executed.
function Conditional(){
if (!<no elements from type A>) return;
// do stuff
}
If you just want to clobber all of the instances of a substring out of a string without using regex you can using:
var replacestring = "A B B C D"
const oldstring = "B";
const newstring = "E";
while (replacestring.indexOf(oldstring) > -1) {
replacestring = replacestring.replace(oldstring, newstring);
}
//result: "A E E C D"
I don't think you can. You could use number_format() if you're coding in PHP. And other programing languages have a function for formatting numbers too.
empty()
needs to access the value by reference (in order to check whether that reference points to something that exists), and PHP before 5.5 didn't support references to temporary values returned from functions.
However, the real problem you have is that you use empty()
at all, mistakenly believing that "empty" value is any different from "false".
Empty is just an alias for !isset($thing) || !$thing
. When the thing you're checking always exists (in PHP results of function calls always exist), the empty()
function is nothing but a negation operator.
PHP doesn't have concept of emptyness. Values that evaluate to false are empty, values that evaluate to true are non-empty. It's the same thing. This code:
$x = something();
if (empty($x)) …
and this:
$x = something();
if (!$x) …
has always the same result, in all cases, for all datatypes (because $x
is defined empty()
is redundant).
Return value from the method always exists (even if you don't have return
statement, return value exists and contains null
). Therefore:
if (!empty($r->getError()))
is logically equivalent to:
if ($r->getError())
I had the very same issue. The answer is that you are doing it right already. It is the problem of MS Excel. Try opening the file with another editor and you will notice that your encoding was successful already. To make MS Excel happy, move from UTF-8 to UTF-16. This should work:
class UnicodeWriter:
def __init__(self, f, dialect=csv.excel_tab, encoding="utf-16", **kwds):
# Redirect output to a queue
self.queue = StringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
# Force BOM
if encoding=="utf-16":
import codecs
f.write(codecs.BOM_UTF16)
self.encoding = encoding
def writerow(self, row):
# Modified from original: now using unicode(s) to deal with e.g. ints
self.writer.writerow([unicode(s).encode("utf-8") for s in row])
# Fetch UTF-8 output from the queue ...
data = self.queue.getvalue()
data = data.decode("utf-8")
# ... and reencode it into the target encoding
data = data.encode(self.encoding)
# strip BOM
if self.encoding == "utf-16":
data = data[2:]
# write to the target stream
self.stream.write(data)
# empty queue
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
I use Apache Derby for pretty much all of my embedded database needs. You can also use Sun's Java DB that is based on Derby but the latest version of Derby is much newer. It supports a lot of options that commercial, native databases support but is much smaller and easier to embed. I've had some database tables with more than a million records with no issues.
I used to use HSQLDB and Hypersonic about 3 years ago. It has some major performance issues at the time and I switch to Derby from it because of those issues. Derby has been solid even when it was in incubator at Apache.
This
url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+"¶m2="+lon);
must work. For whatever strange reason1, you need ?
before the first parameter and &
before the following ones.
Using a compound parameter like
url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+"_"+lon);
would work, too, but is surely not nice. You can't use a space there as it's prohibited in an URL, but you could encode it as %20
or +
(but this is even worse style).
1 Stating that ?
separates the path and the parameters and that &
separates parameters from each other does not explain anything about the reason. Some RFC says "use ? there and & there", but I can't see why they didn't choose the same character.
If your data has a regular structure you can read a file in line by line and populate your favorite container. For example:
Let's say your data has 3 variables: x, y, i.
A file contains n of these data, each variable on its own line (3 lines per record). Here are two records:
384
198
0
255
444
2
Here's how you read your file data into a list. (Reading from text, so cast accordingly.)
data = []
try:
with open(dataFilename, "r") as file:
# read data until end of file
x = file.readline()
while x != "":
x = int(x.strip()) # remove \n, cast as int
y = file.readline()
y = int(y.strip())
i = file.readline()
i = int(i.strip())
data.append([x,y,i])
x = file.readline()
except FileNotFoundError as e:
print("File not found:", e)
return(data)
You can use the click
event and call your function or move your logic into the handler:
$("#bfCaptchaEntry").click(function(){ myFunction(); });
You can use the click
event and set your function as the handler:
$("#bfCaptchaEntry").click(myFunction);
.click()
Bind an event handler to the "click" JavaScript event, or trigger that event on an element.
You can use the on
event bound to "click"
and call your function or move your logic into the handler:
$("#bfCaptchaEntry").on("click", function(){ myFunction(); });
You can use the on
event bound to "click"
and set your function as the handler:
$("#bfCaptchaEntry").on("click", myFunction);
.on()
Attach an event handler function for one or more events to the selected elements.
I've found the following method to be the most reliable when dealing with edge cases that trip up offsetTop/offsetLeft.
function getPosition(element) {
var clientRect = element.getBoundingClientRect();
return {left: clientRect.left + document.body.scrollLeft,
top: clientRect.top + document.body.scrollTop};
}
It's because you're trying to assign an object by reference. Remove the ampersand and your script should work as intended.
As of October 2016, Google has added a file upload question type in native Google Forms, no Google Apps Script needed. See documentation.
Use the .date
method:
In [11]: t = pd.Timestamp('2013-12-25 00:00:00')
In [12]: t.date()
Out[12]: datetime.date(2013, 12, 25)
In [13]: t.date() == datetime.date(2013, 12, 25)
Out[13]: True
To compare against a DatetimeIndex (i.e. an array of Timestamps), you'll want to do it the other way around:
In [21]: pd.Timestamp(datetime.date(2013, 12, 25))
Out[21]: Timestamp('2013-12-25 00:00:00')
In [22]: ts = pd.DatetimeIndex([t])
In [23]: ts == pd.Timestamp(datetime.date(2013, 12, 25))
Out[23]: array([ True], dtype=bool)
UPDATE
I also tried this, but to no avail:
$(document).ready(function() {
$('body :not(.wr-dropdown)').bind("click", function(e) {
$('.test').focus();
})
$('.wr-dropdown').on('change', function(e) {
if ($(".wr-dropdow option[value='/search']")) {
setTimeout(function(e) {
$('body :not(.wr-dropdown)').trigger("click");
},3000)
}
});
});
I am confused as to why you say this isn't working because your JSFiddle is working just fine, but here is my suggestion anyway...
Try this line of code in your SetTimeOut function on your click event:
document.myInput.focus();
myInput correlates to the name attribute of the input tag.
<input name="myInput">
And use this code to blur the field:
document.activeElement.blur();
Your '/0'
should be '\0'
.. you got the slash reversed/leaning the wrong way. Your while
should look like:
while (*(forward++)!='\0')
though the != '\0'
part of your expression is optional here since the loop will continue as long as it evaluates to non-zero (null is considered zero and will terminate the loop).
All "special" characters (i.e., escape sequences for non-printable characters) use a backward slash, such as tab '\t'
, or newline '\n'
, and the same for null '\0'
so it's easy to remember.
better solution is to use pool - ill handle this for you.
const pool = mysql.createPool({_x000D_
host: 'localhost',_x000D_
user: '--',_x000D_
database: '---',_x000D_
password: '----'_x000D_
});_x000D_
_x000D_
// ... later_x000D_
pool.query('select 1 + 1', (err, rows) => { /* */ });
_x000D_
You can not do it as a member function, because the implicit this
parameter is the left hand side of the <<
-operator. (Hence, you would need to add it as a member function to the ostream
-class. Not good :)
Could you do it as a free function without friend
ing it? That's what I prefer, because it makes it clear that this is an integration with ostream
, and not a core functionality of your class.
In jQuery 3 and perhaps earlier versions, the following simpler config also works for individual requests:
$.ajax(
'https://foo.bar.com,
{
dataType: 'json',
xhrFields: {
withCredentials: true
},
success: successFunc
}
);
The full error I was getting in Firefox Dev Tools -> Network tab (in the Security tab for an individual request) was:
An error occurred during a connection to foo.bar.com.SSL peer was unable to negotiate an acceptable set of security parameters.Error code: SSL_ERROR_HANDSHAKE_FAILURE_ALERT
The right way to import a module located on a parent folder, when you don't have a standard package structure, is:
import os, sys
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(CURRENT_DIR))
(you can merge the last two lines but this way is easier to understand).
This solution is cross-platform and is general enough to need not modify in other circumstances.
Try typing which tensorboard
in your terminal. It should exist if you installed with pip
as mentioned in the tensorboard README (although the documentation doesn't tell you that you can now launch tensorboard without doing anything else).
You need to give it a log directory. If you are in the directory where you saved your graph, you can launch it from your terminal with something like:
tensorboard --logdir .
or more generally:
tensorboard --logdir /path/to/log/directory
for any log directory.
Then open your favorite web browser and type in localhost:6006
to connect.
That should get you started. As for logging anything useful in your training process, you need to use the TensorFlow Summary API. You can also use the TensorBoard
callback in Keras.
Having learned of this feature only just now while reading your question, I can only speculate. This seems to provide several advantages over a file-level static variable:
I'd be interested in learning if anyone has used anonymous namespaces in real code.
I tried to avoid too much custom CSS and after reading some other examples I merged the ideas there and got this solution:
<div class="form-group has-feedback has-clear">
<input type="text" class="form-control" ng-model="ctrl.searchService.searchTerm" ng-change="ctrl.search()" placeholder="Suche"/>
<a class="glyphicon glyphicon-remove-sign form-control-feedback form-control-clear" ng-click="ctrl.clearSearch()" style="pointer-events: auto; text-decoration: none;cursor: pointer;"></a>
</div>
As I don't use bootstrap's JavaScript, just the CSS together with Angular, I don't need the classes has-clear and form-control-clear, and I implemented the clear function in my AngularJS controller. With bootstrap's JavaScript this might be possible without own JavaScript.
The foreach loops work just fine, but you can also simply
print_r($_POST);
Or for pretty printing in a browser:
echo "<pre>";
print_r($_POST);
echo "</pre>";
MD2 was widely recognized as insecure and thus disabled in Java in version JDK 6u17 (see release notes http://www.oracle.com/technetwork/java/javase/6u17-141447.html, "Disable MD2 in certificate chain validation"), as well as JDK 7, as per the configuration you pointed out in java.security
.
Verisign was using a Class 3 root certificate with the md2WithRSAEncryption
signature algorithm (serial 70:ba:e4:1d:10:d9:29:34:b6:38:ca:7b:03:cc:ba:bf
), but deprecated it and replaced it with another certificate with the same key and name, but signed with algorithm sha1WithRSAEncryption
. However, some servers are still sending the old MD2 signed certificate during the SSL handshake (ironically, I ran into this problem with a server run by Verisign!).
You can verify that this is the case by getting the certificate chain from the server and examining it:
openssl s_client -showcerts -connect <server>:<port>
Recent versions of the JDK (e.g. 6u21 and all released versions of 7) should resolve this issue by automatically removing certs with the same issuer and public key as a trusted anchor (in cacerts by default).
Check if you have a custom trust manager implementing the older X509TrustManager
interface. JDK 7+ is supposed to be compatible with this interface, however based on my investigation when the trust manager implements X509TrustManager
rather than the newer X509ExtendedTrustManager
(docs), the JDK uses its own wrapper (AbstractTrustManagerWrapper
) and somehow bypasses the internal fix for this issue.
The solution is to:
use the default trust manager, or
modify your custom trust manager to extend X509ExtendedTrustManager
directly (a simple change).
If you are looking for a self-invoking transition then you should use CSS 3 Animations. They aren't supported either, but this is exactly the kind of thing they were made for.
#test p {
margin-top: 25px;
font-size: 21px;
text-align: center;
-webkit-animation: fadein 2s; /* Safari, Chrome and Opera > 12.1 */
-moz-animation: fadein 2s; /* Firefox < 16 */
-ms-animation: fadein 2s; /* Internet Explorer */
-o-animation: fadein 2s; /* Opera < 12.1 */
animation: fadein 2s;
}
@keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
/* Firefox < 16 */
@-moz-keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
/* Safari, Chrome and Opera > 12.1 */
@-webkit-keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
/* Internet Explorer */
@-ms-keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
/* Opera < 12.1 */
@-o-keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
All modern browsers and Internet Explorer 10 (and later): http://caniuse.com/#feat=css-animation
Alternatively, you can use jQuery (or plain JavaScript; see the third code block) to change the class on load:
$("#test p").addClass("load");?
#test p {
opacity: 0;
font-size: 21px;
margin-top: 25px;
text-align: center;
-webkit-transition: opacity 2s ease-in;
-moz-transition: opacity 2s ease-in;
-ms-transition: opacity 2s ease-in;
-o-transition: opacity 2s ease-in;
transition: opacity 2s ease-in;
}
#test p.load {
opacity: 1;
}
document.getElementById("test").children[0].className += " load";
All modern browsers and Internet Explorer 10 (and later): http://caniuse.com/#feat=css-transitions
Or, you can use the method that .Mail uses:
$("#test p").delay(1000).animate({ opacity: 1 }, 700);?
#test p {
opacity: 0;
font-size: 21px;
margin-top: 25px;
text-align: center;
}
jQuery 1.x: All modern browsers and Internet Explorer 6 (and later): http://jquery.com/browser-support/
jQuery 2.x: All modern browsers and Internet Explorer 9 (and later): http://jquery.com/browser-support/
This method is the most cross-compatible as the target browser does not need to support CSS 3 transitions or animations.
Full option searchable select box
This also supports Control buttons keyboards such as ArrowDown
ArrowUp
and Enter
keys
function filterFunction(that, event) {_x000D_
let container, input, filter, li, input_val;_x000D_
container = $(that).closest(".searchable");_x000D_
input_val = container.find("input").val().toUpperCase();_x000D_
_x000D_
if (["ArrowDown", "ArrowUp", "Enter"].indexOf(event.key) != -1) {_x000D_
keyControl(event, container)_x000D_
} else {_x000D_
li = container.find("ul li");_x000D_
li.each(function (i, obj) {_x000D_
if ($(this).text().toUpperCase().indexOf(input_val) > -1) {_x000D_
$(this).show();_x000D_
} else {_x000D_
$(this).hide();_x000D_
}_x000D_
});_x000D_
_x000D_
container.find("ul li").removeClass("selected");_x000D_
setTimeout(function () {_x000D_
container.find("ul li:visible").first().addClass("selected");_x000D_
}, 100)_x000D_
}_x000D_
}_x000D_
_x000D_
function keyControl(e, container) {_x000D_
if (e.key == "ArrowDown") {_x000D_
_x000D_
if (container.find("ul li").hasClass("selected")) {_x000D_
if (container.find("ul li:visible").index(container.find("ul li.selected")) + 1 < container.find("ul li:visible").length) {_x000D_
container.find("ul li.selected").removeClass("selected").nextAll().not('[style*="display: none"]').first().addClass("selected");_x000D_
}_x000D_
_x000D_
} else {_x000D_
container.find("ul li:first-child").addClass("selected");_x000D_
}_x000D_
_x000D_
} else if (e.key == "ArrowUp") {_x000D_
_x000D_
if (container.find("ul li:visible").index(container.find("ul li.selected")) > 0) {_x000D_
container.find("ul li.selected").removeClass("selected").prevAll().not('[style*="display: none"]').first().addClass("selected");_x000D_
}_x000D_
} else if (e.key == "Enter") {_x000D_
container.find("input").val(container.find("ul li.selected").text()).blur();_x000D_
onSelect(container.find("ul li.selected").text())_x000D_
}_x000D_
_x000D_
container.find("ul li.selected")[0].scrollIntoView({_x000D_
behavior: "smooth",_x000D_
});_x000D_
}_x000D_
_x000D_
function onSelect(val) {_x000D_
alert(val)_x000D_
}_x000D_
_x000D_
$(".searchable input").focus(function () {_x000D_
$(this).closest(".searchable").find("ul").show();_x000D_
$(this).closest(".searchable").find("ul li").show();_x000D_
});_x000D_
$(".searchable input").blur(function () {_x000D_
let that = this;_x000D_
setTimeout(function () {_x000D_
$(that).closest(".searchable").find("ul").hide();_x000D_
}, 300);_x000D_
});_x000D_
_x000D_
$(document).on('click', '.searchable ul li', function () {_x000D_
$(this).closest(".searchable").find("input").val($(this).text()).blur();_x000D_
onSelect($(this).text())_x000D_
});_x000D_
_x000D_
$(".searchable ul li").hover(function () {_x000D_
$(this).closest(".searchable").find("ul li.selected").removeClass("selected");_x000D_
$(this).addClass("selected");_x000D_
});
_x000D_
div.searchable {_x000D_
width: 300px;_x000D_
float: left;_x000D_
margin: 0 15px;_x000D_
}_x000D_
_x000D_
.searchable input {_x000D_
width: 100%;_x000D_
height: 50px;_x000D_
font-size: 18px;_x000D_
padding: 10px;_x000D_
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */_x000D_
-moz-box-sizing: border-box; /* Firefox, other Gecko */_x000D_
box-sizing: border-box; /* Opera/IE 8+ */_x000D_
display: block;_x000D_
font-weight: 400;_x000D_
line-height: 1.6;_x000D_
color: #495057;_x000D_
background-color: #fff;_x000D_
background-clip: padding-box;_x000D_
border: 1px solid #ced4da;_x000D_
border-radius: .25rem;_x000D_
transition: border-color .15s ease-in-out, box-shadow .15s ease-in-out;_x000D_
background: url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'%3E%3Cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3E%3C/svg%3E") no-repeat right .75rem center/8px 10px;_x000D_
}_x000D_
_x000D_
.searchable ul {_x000D_
display: none;_x000D_
list-style-type: none;_x000D_
background-color: #fff;_x000D_
border-radius: 0 0 5px 5px;_x000D_
border: 1px solid #add8e6;_x000D_
border-top: none;_x000D_
max-height: 180px;_x000D_
margin: 0;_x000D_
overflow-y: scroll;_x000D_
overflow-x: hidden;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
.searchable ul li {_x000D_
padding: 7px 9px;_x000D_
border-bottom: 1px solid #e1e1e1;_x000D_
cursor: pointer;_x000D_
color: #6e6e6e;_x000D_
}_x000D_
_x000D_
.searchable ul li.selected {_x000D_
background-color: #e8e8e8;_x000D_
color: #333;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="searchable">_x000D_
<input type="text" placeholder="search countries" onkeyup="filterFunction(this,event)">_x000D_
<ul>_x000D_
<li>Algeria</li>_x000D_
<li>Bulgaria</li>_x000D_
<li>Canada</li>_x000D_
<li>Egypt</li>_x000D_
<li>Fiji</li>_x000D_
<li>India</li>_x000D_
<li>Japan</li>_x000D_
<li>Iran (Islamic Republic of)</li>_x000D_
<li>Lao People's Democratic Republic</li>_x000D_
<li>Micronesia (Federated States of)</li>_x000D_
<li>Nicaragua</li>_x000D_
<li>Senegal</li>_x000D_
<li>Tajikistan</li>_x000D_
<li>Yemen</li>_x000D_
</ul>_x000D_
</div>
_x000D_
Since GDB 7.5 you can use these native Convenience Functions:
$_memeq(buf1, buf2, length)
$_regex(str, regex)
$_streq(str1, str2)
$_strlen(str)
Seems quite less problematic than having to execute a "foreign" strcmp()
on the process' stack each time the breakpoint is hit. This is especially true for debugging multithreaded processes.
Note your GDB needs to be compiled with Python support, which is not an issue with current linux distros. To be sure, you can check it by running
show configuration
inside GDB and searching for--with-python
. This little oneliner does the trick, too:$ gdb -n -quiet -batch -ex 'show configuration' | grep 'with-python' --with-python=/usr (relocatable)
For your demo case, the usage would be
break <where> if $_streq(x, "hello")
or, if your breakpoint already exists and you just want to add the condition to it
condition <breakpoint number> $_streq(x, "hello")
$_streq
only matches the whole string, so if you want something more cunning you should use $_regex
, which supports the Python regular expression syntax.
Execute following command:
set PATH="C:\Program Files (x86)\Java\jre7"
(whichever JRE
exists in case of 64bit).
Because your Java Path is not set so you can just do this at command line and then execute the keytool
import command.
I would try to avoid changing the xticklabels
if possible, otherwise it can get very confusing if you for example overplot your histogram with additional data.
Defining the range of your grid is probably the best and with imshow
it can be done by adding the extent
keyword. This way the axes gets adjusted automatically. If you want to change the labels i would use set_xticks
with perhaps some formatter. Altering the labels directly should be the last resort.
fig, ax = plt.subplots(figsize=(6,6))
ax.imshow(hist, cmap=plt.cm.Reds, interpolation='none', extent=[80,120,32,0])
ax.set_aspect(2) # you may also use am.imshow(..., aspect="auto") to restore the aspect ratio
I use inline if's
($_POST['category'] == $data['id'] ? 'selected="selected"' : false)
This XPath:
count(//Property[long = '11007'])
returns the same value as:
count(//Property/long[text() = '11007'])
...except that the first counts Property
nodes that match the criterion and the second counts long
child nodes that match the criterion.
As per your comment and reading your question a couple of times, I believe that you want to find uniqueness based on a combination of criteria. Therefore, in actuality, I think you are actually checking multiple conditions. The following would work as well:
count(//Property[@Name = 'Alive'][long = '11007'])
because it means the same thing as:
count(//Property[@Name = 'Alive' and long = '11007'])
Of course, you would substitute the values for parameters in your template. The above code only illustrates the point.
EDIT (after question edit)
You were quite right about the XML being horrible. In fact, this is a downright CodingHorror candidate! I had to keep recounting to keep track of the "Property" node I was on presently. I feel your pain!
Here you go:
count(/root/ac/Properties/Property[Properties/Property/Properties/Property/long = $parPropId])
Note that I have removed all the other checks (for ID and Value). They appear not to be required since you are able to arrive at the relevant node using the hierarchy in the XML. Also, you already mentioned that the check for uniqueness is based only on the contents of the long
element.
I solve this problem by mixing the solutions above.
sink("/Users/my/myTest.dat")
writeLines(unlist(lapply(k, paste, collapse=" ")))
sink()
I think it works well
Use this technique to increase the speed of inserting records in Entity Framework. Here I use a simple stored procedure to insert the records. And to execute this stored procedure I use .FromSql() method of Entity Framework which executes Raw SQL.
CREATE PROCEDURE TestProc
@FirstParam VARCHAR(50),
@SecondParam VARCHAR(50)
AS
Insert into SomeTable(Name, Address) values(@FirstParam, @SecondParam)
GO
Next, loop through all your 4000 records and add the Entity Framework code which executes the stored
procedure onces every 100th loop.
For this I create a string query to execute this procedure, keep on appending to it every sets of record.
Then check it the loop is running in the multiples of 100 and in that case execute it using .FromSql()
.
So for 4000 records I only have to execute the procedure for only 4000/100 = 40 times.
string execQuery = "";
var context = new MyContext();
for (int i = 0; i < 4000; i++)
{
execQuery += "EXEC TestProc @FirstParam = 'First'" + i + "'', @SecondParam = 'Second'" + i + "''";
if (i % 100 == 0)
{
context.Student.FromSql(execQuery);
execQuery = "";
}
}
After trying every answer I could find here and online, I was still getting errors for some missing headers. When trying to compile pyRFR, I was getting errors about stdexcept
not being found, which apparently was not installed in /usr/include
with the other headers. However, I found where it was hiding in Mojave and added this to the end of my ~/.bash_profile
file:
export CPATH=/Library/Developer/CommandLineTools/usr/include/c++/v1
Having done that, I can now compile pyRFR and other C/C++ programs. According to echo | gcc -E -Wp,-v -
, gcc was looking in the old location for these headers (without the /c++/v1
), but not the new location, so adding that to CFLAGS fixed it.
Here's a simple method I've used on Windows 7 through Windows 10. Basically, I simply use the "IF EXIST" command to check for the Windows\System32\WDI\LogFiles folder. The WDI folder exists on every install of Windows from at least 7 onward, and it requires admin privileges to access. The WDI folder always has a LogFiles folder inside it. So, running "IF EXIST" on the WDI\LogFiles folder will return true if run as admin, and false if not run as admin. This can be used in a batch file to check privilege level, and branch to whichever commands you desire based on that result.
Here's a brief snippet of example code:
IF EXIST %SYSTEMROOT%\SYSTEM32\WDI\LOGFILES GOTO GOTADMIN
(Commands for running with normal privileges)
:GOTADMIN
(Commands for running with admin privileges)
Keep in mind that this method assumes the default security permissions have not been modified on the WDI folder (which is unlikely to happen in most situations, but please see caveat #2 below). Even in that case, it's simply a matter of modifying the code to check for a different common file/folder that requires admin access (System32\config\SAM may be a good alternate candidate), or you could even create your own specifically for that purpose.
There are two caveats about this method though:
Disabling UAC will likely break it through the simple fact that everything would be run as admin anyway.
Attempting to open the WDI folder in Windows Explorer and then clicking "Continue" when prompted will add permanent access rights for that user account, thus breaking my method. If this happens, it can be fixed by removing the user account from the WDI folder security permissions. If for any reason the user MUST be able to access the WDI folder with Windows Explorer, then you'd have to modify the code to check a different folder (as mentioned above, creating your own specifically for this purpose may be a good choice).
So, admittedly my method isn't perfect since it can be broken, but it's a relatively quick method that's easy to implement, is equally compatible with all versions of Windows 7, 8 and 10, and provided I stay mindful of the mentioned caveats has been 100% effective for me.
If you want to pursue a "simple" solution, you might find this class I put together useful:
http://www.architectshack.com/TextFileEncodingDetector.ashx
It does the BOM detection automatically first, and then tries to differentiate between Unicode encodings without BOM, vs some other default encoding (generally Windows-1252, incorrectly labelled as Encoding.ASCII in .Net).
As noted above, a "heavier" solution involving NCharDet or MLang may be more appropriate, and as I note on the overview page of this class, the best is to provide some form of interactivity with the user if at all possible, because there simply is no 100% detection rate possible!
Snippet in case the site is offline:
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
namespace KlerksSoft
{
public static class TextFileEncodingDetector
{
/*
* Simple class to handle text file encoding woes (in a primarily English-speaking tech
* world).
*
* - This code is fully managed, no shady calls to MLang (the unmanaged codepage
* detection library originally developed for Internet Explorer).
*
* - This class does NOT try to detect arbitrary codepages/charsets, it really only
* aims to differentiate between some of the most common variants of Unicode
* encoding, and a "default" (western / ascii-based) encoding alternative provided
* by the caller.
*
* - As there is no "Reliable" way to distinguish between UTF-8 (without BOM) and
* Windows-1252 (in .Net, also incorrectly called "ASCII") encodings, we use a
* heuristic - so the more of the file we can sample the better the guess. If you
* are going to read the whole file into memory at some point, then best to pass
* in the whole byte byte array directly. Otherwise, decide how to trade off
* reliability against performance / memory usage.
*
* - The UTF-8 detection heuristic only works for western text, as it relies on
* the presence of UTF-8 encoded accented and other characters found in the upper
* ranges of the Latin-1 and (particularly) Windows-1252 codepages.
*
* - For more general detection routines, see existing projects / resources:
* - MLang - Microsoft library originally for IE6, available in Windows XP and later APIs now (I think?)
* - MLang .Net bindings: http://www.codeproject.com/KB/recipes/DetectEncoding.aspx
* - CharDet - Mozilla browser's detection routines
* - Ported to Java then .Net: http://www.conceptdevelopment.net/Localization/NCharDet/
* - Ported straight to .Net: http://code.google.com/p/chardetsharp/source/browse
*
* Copyright Tao Klerks, 2010-2012, [email protected]
* Licensed under the modified BSD license:
*
Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list
of conditions and the following disclaimer in the documentation and/or other materials
provided with the distribution.
- The name of the author may not be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
*
* CHANGELOG:
* - 2012-02-03:
* - Simpler methods, removing the silly "DefaultEncoding" parameter (with "??" operator, saves no typing)
* - More complete methods
* - Optionally return indication of whether BOM was found in "Detect" methods
* - Provide straight-to-string method for byte arrays (GetStringFromByteArray)
*/
const long _defaultHeuristicSampleSize = 0x10000; //completely arbitrary - inappropriate for high numbers of files / high speed requirements
public static Encoding DetectTextFileEncoding(string InputFilename)
{
using (FileStream textfileStream = File.OpenRead(InputFilename))
{
return DetectTextFileEncoding(textfileStream, _defaultHeuristicSampleSize);
}
}
public static Encoding DetectTextFileEncoding(FileStream InputFileStream, long HeuristicSampleSize)
{
bool uselessBool = false;
return DetectTextFileEncoding(InputFileStream, _defaultHeuristicSampleSize, out uselessBool);
}
public static Encoding DetectTextFileEncoding(FileStream InputFileStream, long HeuristicSampleSize, out bool HasBOM)
{
if (InputFileStream == null)
throw new ArgumentNullException("Must provide a valid Filestream!", "InputFileStream");
if (!InputFileStream.CanRead)
throw new ArgumentException("Provided file stream is not readable!", "InputFileStream");
if (!InputFileStream.CanSeek)
throw new ArgumentException("Provided file stream cannot seek!", "InputFileStream");
Encoding encodingFound = null;
long originalPos = InputFileStream.Position;
InputFileStream.Position = 0;
//First read only what we need for BOM detection
byte[] bomBytes = new byte[InputFileStream.Length > 4 ? 4 : InputFileStream.Length];
InputFileStream.Read(bomBytes, 0, bomBytes.Length);
encodingFound = DetectBOMBytes(bomBytes);
if (encodingFound != null)
{
InputFileStream.Position = originalPos;
HasBOM = true;
return encodingFound;
}
//BOM Detection failed, going for heuristics now.
// create sample byte array and populate it
byte[] sampleBytes = new byte[HeuristicSampleSize > InputFileStream.Length ? InputFileStream.Length : HeuristicSampleSize];
Array.Copy(bomBytes, sampleBytes, bomBytes.Length);
if (InputFileStream.Length > bomBytes.Length)
InputFileStream.Read(sampleBytes, bomBytes.Length, sampleBytes.Length - bomBytes.Length);
InputFileStream.Position = originalPos;
//test byte array content
encodingFound = DetectUnicodeInByteSampleByHeuristics(sampleBytes);
HasBOM = false;
return encodingFound;
}
public static Encoding DetectTextByteArrayEncoding(byte[] TextData)
{
bool uselessBool = false;
return DetectTextByteArrayEncoding(TextData, out uselessBool);
}
public static Encoding DetectTextByteArrayEncoding(byte[] TextData, out bool HasBOM)
{
if (TextData == null)
throw new ArgumentNullException("Must provide a valid text data byte array!", "TextData");
Encoding encodingFound = null;
encodingFound = DetectBOMBytes(TextData);
if (encodingFound != null)
{
HasBOM = true;
return encodingFound;
}
else
{
//test byte array content
encodingFound = DetectUnicodeInByteSampleByHeuristics(TextData);
HasBOM = false;
return encodingFound;
}
}
public static string GetStringFromByteArray(byte[] TextData, Encoding DefaultEncoding)
{
return GetStringFromByteArray(TextData, DefaultEncoding, _defaultHeuristicSampleSize);
}
public static string GetStringFromByteArray(byte[] TextData, Encoding DefaultEncoding, long MaxHeuristicSampleSize)
{
if (TextData == null)
throw new ArgumentNullException("Must provide a valid text data byte array!", "TextData");
Encoding encodingFound = null;
encodingFound = DetectBOMBytes(TextData);
if (encodingFound != null)
{
//For some reason, the default encodings don't detect/swallow their own preambles!!
return encodingFound.GetString(TextData, encodingFound.GetPreamble().Length, TextData.Length - encodingFound.GetPreamble().Length);
}
else
{
byte[] heuristicSample = null;
if (TextData.Length > MaxHeuristicSampleSize)
{
heuristicSample = new byte[MaxHeuristicSampleSize];
Array.Copy(TextData, heuristicSample, MaxHeuristicSampleSize);
}
else
{
heuristicSample = TextData;
}
encodingFound = DetectUnicodeInByteSampleByHeuristics(TextData) ?? DefaultEncoding;
return encodingFound.GetString(TextData);
}
}
public static Encoding DetectBOMBytes(byte[] BOMBytes)
{
if (BOMBytes == null)
throw new ArgumentNullException("Must provide a valid BOM byte array!", "BOMBytes");
if (BOMBytes.Length < 2)
return null;
if (BOMBytes[0] == 0xff
&& BOMBytes[1] == 0xfe
&& (BOMBytes.Length < 4
|| BOMBytes[2] != 0
|| BOMBytes[3] != 0
)
)
return Encoding.Unicode;
if (BOMBytes[0] == 0xfe
&& BOMBytes[1] == 0xff
)
return Encoding.BigEndianUnicode;
if (BOMBytes.Length < 3)
return null;
if (BOMBytes[0] == 0xef && BOMBytes[1] == 0xbb && BOMBytes[2] == 0xbf)
return Encoding.UTF8;
if (BOMBytes[0] == 0x2b && BOMBytes[1] == 0x2f && BOMBytes[2] == 0x76)
return Encoding.UTF7;
if (BOMBytes.Length < 4)
return null;
if (BOMBytes[0] == 0xff && BOMBytes[1] == 0xfe && BOMBytes[2] == 0 && BOMBytes[3] == 0)
return Encoding.UTF32;
if (BOMBytes[0] == 0 && BOMBytes[1] == 0 && BOMBytes[2] == 0xfe && BOMBytes[3] == 0xff)
return Encoding.GetEncoding(12001);
return null;
}
public static Encoding DetectUnicodeInByteSampleByHeuristics(byte[] SampleBytes)
{
long oddBinaryNullsInSample = 0;
long evenBinaryNullsInSample = 0;
long suspiciousUTF8SequenceCount = 0;
long suspiciousUTF8BytesTotal = 0;
long likelyUSASCIIBytesInSample = 0;
//Cycle through, keeping count of binary null positions, possible UTF-8
// sequences from upper ranges of Windows-1252, and probable US-ASCII
// character counts.
long currentPos = 0;
int skipUTF8Bytes = 0;
while (currentPos < SampleBytes.Length)
{
//binary null distribution
if (SampleBytes[currentPos] == 0)
{
if (currentPos % 2 == 0)
evenBinaryNullsInSample++;
else
oddBinaryNullsInSample++;
}
//likely US-ASCII characters
if (IsCommonUSASCIIByte(SampleBytes[currentPos]))
likelyUSASCIIBytesInSample++;
//suspicious sequences (look like UTF-8)
if (skipUTF8Bytes == 0)
{
int lengthFound = DetectSuspiciousUTF8SequenceLength(SampleBytes, currentPos);
if (lengthFound > 0)
{
suspiciousUTF8SequenceCount++;
suspiciousUTF8BytesTotal += lengthFound;
skipUTF8Bytes = lengthFound - 1;
}
}
else
{
skipUTF8Bytes--;
}
currentPos++;
}
//1: UTF-16 LE - in english / european environments, this is usually characterized by a
// high proportion of odd binary nulls (starting at 0), with (as this is text) a low
// proportion of even binary nulls.
// The thresholds here used (less than 20% nulls where you expect non-nulls, and more than
// 60% nulls where you do expect nulls) are completely arbitrary.
if (((evenBinaryNullsInSample * 2.0) / SampleBytes.Length) < 0.2
&& ((oddBinaryNullsInSample * 2.0) / SampleBytes.Length) > 0.6
)
return Encoding.Unicode;
//2: UTF-16 BE - in english / european environments, this is usually characterized by a
// high proportion of even binary nulls (starting at 0), with (as this is text) a low
// proportion of odd binary nulls.
// The thresholds here used (less than 20% nulls where you expect non-nulls, and more than
// 60% nulls where you do expect nulls) are completely arbitrary.
if (((oddBinaryNullsInSample * 2.0) / SampleBytes.Length) < 0.2
&& ((evenBinaryNullsInSample * 2.0) / SampleBytes.Length) > 0.6
)
return Encoding.BigEndianUnicode;
//3: UTF-8 - Martin Dürst outlines a method for detecting whether something CAN be UTF-8 content
// using regexp, in his w3c.org unicode FAQ entry:
// http://www.w3.org/International/questions/qa-forms-utf-8
// adapted here for C#.
string potentiallyMangledString = Encoding.ASCII.GetString(SampleBytes);
Regex UTF8Validator = new Regex(@"\A("
+ @"[\x09\x0A\x0D\x20-\x7E]"
+ @"|[\xC2-\xDF][\x80-\xBF]"
+ @"|\xE0[\xA0-\xBF][\x80-\xBF]"
+ @"|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}"
+ @"|\xED[\x80-\x9F][\x80-\xBF]"
+ @"|\xF0[\x90-\xBF][\x80-\xBF]{2}"
+ @"|[\xF1-\xF3][\x80-\xBF]{3}"
+ @"|\xF4[\x80-\x8F][\x80-\xBF]{2}"
+ @")*\z");
if (UTF8Validator.IsMatch(potentiallyMangledString))
{
//Unfortunately, just the fact that it CAN be UTF-8 doesn't tell you much about probabilities.
//If all the characters are in the 0-127 range, no harm done, most western charsets are same as UTF-8 in these ranges.
//If some of the characters were in the upper range (western accented characters), however, they would likely be mangled to 2-byte by the UTF-8 encoding process.
// So, we need to play stats.
// The "Random" likelihood of any pair of randomly generated characters being one
// of these "suspicious" character sequences is:
// 128 / (256 * 256) = 0.2%.
//
// In western text data, that is SIGNIFICANTLY reduced - most text data stays in the <127
// character range, so we assume that more than 1 in 500,000 of these character
// sequences indicates UTF-8. The number 500,000 is completely arbitrary - so sue me.
//
// We can only assume these character sequences will be rare if we ALSO assume that this
// IS in fact western text - in which case the bulk of the UTF-8 encoded data (that is
// not already suspicious sequences) should be plain US-ASCII bytes. This, I
// arbitrarily decided, should be 80% (a random distribution, eg binary data, would yield
// approx 40%, so the chances of hitting this threshold by accident in random data are
// VERY low).
if ((suspiciousUTF8SequenceCount * 500000.0 / SampleBytes.Length >= 1) //suspicious sequences
&& (
//all suspicious, so cannot evaluate proportion of US-Ascii
SampleBytes.Length - suspiciousUTF8BytesTotal == 0
||
likelyUSASCIIBytesInSample * 1.0 / (SampleBytes.Length - suspiciousUTF8BytesTotal) >= 0.8
)
)
return Encoding.UTF8;
}
return null;
}
private static bool IsCommonUSASCIIByte(byte testByte)
{
if (testByte == 0x0A //lf
|| testByte == 0x0D //cr
|| testByte == 0x09 //tab
|| (testByte >= 0x20 && testByte <= 0x2F) //common punctuation
|| (testByte >= 0x30 && testByte <= 0x39) //digits
|| (testByte >= 0x3A && testByte <= 0x40) //common punctuation
|| (testByte >= 0x41 && testByte <= 0x5A) //capital letters
|| (testByte >= 0x5B && testByte <= 0x60) //common punctuation
|| (testByte >= 0x61 && testByte <= 0x7A) //lowercase letters
|| (testByte >= 0x7B && testByte <= 0x7E) //common punctuation
)
return true;
else
return false;
}
private static int DetectSuspiciousUTF8SequenceLength(byte[] SampleBytes, long currentPos)
{
int lengthFound = 0;
if (SampleBytes.Length >= currentPos + 1
&& SampleBytes[currentPos] == 0xC2
)
{
if (SampleBytes[currentPos + 1] == 0x81
|| SampleBytes[currentPos + 1] == 0x8D
|| SampleBytes[currentPos + 1] == 0x8F
)
lengthFound = 2;
else if (SampleBytes[currentPos + 1] == 0x90
|| SampleBytes[currentPos + 1] == 0x9D
)
lengthFound = 2;
else if (SampleBytes[currentPos + 1] >= 0xA0
&& SampleBytes[currentPos + 1] <= 0xBF
)
lengthFound = 2;
}
else if (SampleBytes.Length >= currentPos + 1
&& SampleBytes[currentPos] == 0xC3
)
{
if (SampleBytes[currentPos + 1] >= 0x80
&& SampleBytes[currentPos + 1] <= 0xBF
)
lengthFound = 2;
}
else if (SampleBytes.Length >= currentPos + 1
&& SampleBytes[currentPos] == 0xC5
)
{
if (SampleBytes[currentPos + 1] == 0x92
|| SampleBytes[currentPos + 1] == 0x93
)
lengthFound = 2;
else if (SampleBytes[currentPos + 1] == 0xA0
|| SampleBytes[currentPos + 1] == 0xA1
)
lengthFound = 2;
else if (SampleBytes[currentPos + 1] == 0xB8
|| SampleBytes[currentPos + 1] == 0xBD
|| SampleBytes[currentPos + 1] == 0xBE
)
lengthFound = 2;
}
else if (SampleBytes.Length >= currentPos + 1
&& SampleBytes[currentPos] == 0xC6
)
{
if (SampleBytes[currentPos + 1] == 0x92)
lengthFound = 2;
}
else if (SampleBytes.Length >= currentPos + 1
&& SampleBytes[currentPos] == 0xCB
)
{
if (SampleBytes[currentPos + 1] == 0x86
|| SampleBytes[currentPos + 1] == 0x9C
)
lengthFound = 2;
}
else if (SampleBytes.Length >= currentPos + 2
&& SampleBytes[currentPos] == 0xE2
)
{
if (SampleBytes[currentPos + 1] == 0x80)
{
if (SampleBytes[currentPos + 2] == 0x93
|| SampleBytes[currentPos + 2] == 0x94
)
lengthFound = 3;
if (SampleBytes[currentPos + 2] == 0x98
|| SampleBytes[currentPos + 2] == 0x99
|| SampleBytes[currentPos + 2] == 0x9A
)
lengthFound = 3;
if (SampleBytes[currentPos + 2] == 0x9C
|| SampleBytes[currentPos + 2] == 0x9D
|| SampleBytes[currentPos + 2] == 0x9E
)
lengthFound = 3;
if (SampleBytes[currentPos + 2] == 0xA0
|| SampleBytes[currentPos + 2] == 0xA1
|| SampleBytes[currentPos + 2] == 0xA2
)
lengthFound = 3;
if (SampleBytes[currentPos + 2] == 0xA6)
lengthFound = 3;
if (SampleBytes[currentPos + 2] == 0xB0)
lengthFound = 3;
if (SampleBytes[currentPos + 2] == 0xB9
|| SampleBytes[currentPos + 2] == 0xBA
)
lengthFound = 3;
}
else if (SampleBytes[currentPos + 1] == 0x82
&& SampleBytes[currentPos + 2] == 0xAC
)
lengthFound = 3;
else if (SampleBytes[currentPos + 1] == 0x84
&& SampleBytes[currentPos + 2] == 0xA2
)
lengthFound = 3;
}
return lengthFound;
}
}
}
varunl's currently accepted answer
>>> l = [None] * 10
>>> l
[None, None, None, None, None, None, None, None, None, None]
Works well for non-reference types like numbers. Unfortunately if you want to create a list-of-lists you will run into referencing errors. Example in Python 2.7.6:
>>> a = [[]]*10
>>> a
[[], [], [], [], [], [], [], [], [], []]
>>> a[0].append(0)
>>> a
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]]
>>>
As you can see, each element is pointing to the same list object. To get around this, you can create a method that will initialize each position to a different object reference.
def init_list_of_objects(size):
list_of_objects = list()
for i in range(0,size):
list_of_objects.append( list() ) #different object reference each time
return list_of_objects
>>> a = init_list_of_objects(10)
>>> a
[[], [], [], [], [], [], [], [], [], []]
>>> a[0].append(0)
>>> a
[[0], [], [], [], [], [], [], [], [], []]
>>>
There is likely a default, built-in python way of doing this (instead of writing a function), but I'm not sure what it is. Would be happy to be corrected!
Edit: It's [ [] for _ in range(10)]
Example :
>>> [ [random.random() for _ in range(2) ] for _ in range(5)]
>>> [[0.7528051908943816, 0.4325669600055032], [0.510983236521753, 0.7789949902294716], [0.09475179523690558, 0.30216475640534635], [0.3996890132468158, 0.6374322093017013], [0.3374204010027543, 0.4514925173253973]]
While the GC compacts the small object heap as part of an optimization strategy to eliminate memory holes, the GC never compacts the large object heap for performance reasons**(the cost of compaction is too high for large objects (greater than 85KB in size))**. Hence if you are running a program that uses many large objects in an x86 system, you might encounter OutOfMemory exceptions. If you are running that program in an x64 system, you might have a fragmented heap.
You can use this one it's for YYYY-MM-DD. It checks if it's a valid date and that the value is not NULL. It returns TRUE
if everythings check out to be correct or FALSE
if anything is invalid. It doesn't get easier then this!
function validateDate(date) {
var matches = /^(\d{4})[-\/](\d{2})[-\/](\d{2})$/.exec(date);
if (matches == null) return false;
var d = matches[3];
var m = matches[2] - 1;
var y = matches[1] ;
var composedDate = new Date(y, m, d);
return composedDate.getDate() == d &&
composedDate.getMonth() == m &&
composedDate.getFullYear() == y;
}
Be aware that months need to be subtracted like this: var m = matches[2] - 1;
else the new Date()
instance won't be properly made.
Open a command prompt as an Administrator.
Enter slmgr /upk
and wait for this to complete. This will uninstall the current product key from Windows and put it into an unlicensed state.
Enter slmgr /cpky
and wait for this to complete. This will remove the product key from the registry if it's still there.
Enter slmgr /rearm
and wait for this to complete. This is to reset the Windows activation timers so the new users will be prompted to activate Windows when they put in the key.
This should put the system back to a pre-key state.
Hope this helps you out!
Put the DB back into Full mode, run the transaction log backup (not just a full backup) and then the shrink.
After it's shrunk, you can put the DB back into simple mode and it txn log will stay the same size.
A lot of the answers on this page only apply to a single cell, and OP asked for all the selected cells.
If all you want is the cell contents, and you don't care about references to the actual cells that are selected, you can just do this:
Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim SelectedThings As String = DataGridView1.GetClipboardContent().GetText().Replace(ChrW(9), ",")
TextBox1.Text = SelectedThings
End Sub
When Button1
is clicked, this will fill TextBox1
with the comma-separated values of the selected cells.
@selectField1 AS bit
@selectField2 AS bit
SELECT
CASE
WHEN @selectField1 THEN Field1
WHEN @selectField2 THEN Field2
ELSE someDefaultField
END
FROM Table
Is this what you're looking for?
Depending on the answer from KyungHun Jeon, but the appendChild expect a dom node, so add a index to jquery object to return the node:
document.body.appendChild(form[0])
If you happen to process the value with some string function before saving, make sure the function can properly handle multibyte characters. String functions that cannot do that and are, say, attempting to truncate might split one of the single multibyte characters in the middle, and that can cause such string error situations.
In PHP for instance, you would need to switch from substr
to mb_substr
.
My version is like this:
php on my server:
<?php
header('content-type: application/json; charset=utf-8');
$data = json_encode($_SERVER['REMOTE_ADDR']);
$callback = filter_input(INPUT_GET,
'callback',
FILTER_SANITIZE_STRING,
FILTER_FLAG_ENCODE_HIGH|FILTER_FLAG_ENCODE_LOW);
echo $callback . '(' . $data . ');';
?>
jQuery on the page:
var self = this;
$.ajax({
url: this.url + "getip.php",
data: null,
type: 'GET',
crossDomain: true,
dataType: 'jsonp'
}).done( function( json ) {
self.ip = json;
});
It works cross domain. It could use a status check. Working on that.
In details you can apply the following logic.
If Bit Pattern is 33602 in Integer
1000 0011 0100 0010
and you need to Roll over with 2 right shifs then: first make a copy of bit pattern and then left shift it: Length - RightShift i.e. length is 16 right shift value is 2 16 - 2 = 14
After 14 times left shifting you get.
1000 0000 0000 0000
Now right shift the value 33602, 2 times as required. You get
0010 0000 1101 0000
Now take an OR between 14 time left shifted value and 2 times right shifted value.
1000 0000 0000 0000 0010 0000 1101 0000 =================== 1010 0000 1101 0000 ===================
And you get your shifted rollover value. Remember bit wise operations are faster and this don't even required any loop.
Alternative pure Perl, fairly readable, no packages or options required:
perl -e "map {$x += $_} <> and print $x" < infile.txt
Fully example to demonstrate how jQuery query all data in HTML table.
Assume there is a table like the following in your HTML code.
<table id="someTable">
<thead>
<tr>
<td>title 0</td>
<td>title 1</td>
<td>title 2</td>
</tr>
</thead>
<tbody>
<tr>
<td>row 0 td 0</td>
<td>row 0 td 1</td>
<td>row 0 td 2</td>
</tr>
<tr>
<td>row 1 td 0</td>
<td>row 1 td 1</td>
<td>row 1 td 2</td>
</tr>
<tr>
<td>row 2 td 0</td>
<td>row 2 td 1</td>
<td>row 2 td 2</td>
</tr>
<tr> ... </tr>
<tr> ... </tr>
...
<tr> ... </tr>
<tr>
<td>row n td 0</td>
<td>row n td 1</td>
<td>row n td 2</td>
</tr>
</tbody>
</table>
Then, The Answer, the code to print all row all column, should like this
$('#someTable tbody tr').each( (tr_idx,tr) => {
$(tr).children('td').each( (td_idx, td) => {
console.log( '[' +tr_idx+ ',' +td_idx+ '] => ' + $(td).text());
});
});
After running the code, the result will show
[0,0] => row 0 td 0
[0,1] => row 0 td 1
[0,2] => row 0 td 2
[1,0] => row 1 td 0
[1,1] => row 1 td 1
[1,2] => row 1 td 2
[2,0] => row 2 td 0
[2,1] => row 2 td 1
[2,2] => row 2 td 2
...
[n,0] => row n td 0
[n,1] => row n td 1
[n,2] => row n td 2
Summary.
In the code,
tr_idx is the row index start from 0.
td_idx is the column index start from 0.
From this double-loop code,
you can get all loop-index and data in each td cell after comparing the Answer's source code and the output result.
On Mac; these two below commands completely remove Jenkins from your machine. just open your Terminal and execute them:
Thanks
The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.
The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.
To pull a remote branch locally, I do the following:
git checkout -b branchname
// creates a local branch with the same name and checks out on it
git pull origin branchname
// pulls the remote one onto your local one
The only time I did this and it didn't work, I deleted the repo, cloned it again and repeated the above 2 steps; it worked.
Just try this:
Bitmap bitmap = BitmapFactory.decodeFile("/path/images/image.jpg");
ByteArrayOutputStream blob = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /* Ignored for PNGs */, blob);
byte[] bitmapdata = blob.toByteArray();
If bitmapdata
is the byte array then getting Bitmap
is done like this:
Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);
Returns the decoded Bitmap
, or null
if the image could not be decoded.
Maybe you're not doing it as root?
Try sudo nginx -s reload
, if it still doesn't work, you might want to try sudo pkill -HUP nginx
.
I know this topic is old, but for future people who could wonder the same question, another incredibly inefficient solution could be to do:
PersonModel.find({$where : 'this.favouriteFoods.indexOf("sushi") != -1'});
This avoids all optimisations by MongoDB so do not use in production code.
I use oracle 12 and it tell me that if you need to invoke the procedure then use call keyword. In your case it should be:
begin
call temp_proc;
end;
Using select-string:
Get-EventLog Security | where {$_.UserName | select-string -notmatch user1,user2}
the solution is easy: execute via sh
... -exec sh -c "zcat {} | agrep -dEOE 'grep' " \;
$(document).ready(function(){_x000D_
_x000D_
$(".btn1").click(function(){_x000D_
$("div.test:not(:first)").hide();_x000D_
});_x000D_
_x000D_
$(".btn2").click(function(){_x000D_
$("div.test").show();_x000D_
$("div.test:not(:first):not(:last)").hide();_x000D_
});_x000D_
_x000D_
$(".btn3").click(function(){_x000D_
$("div.test").hide();_x000D_
$("div.test:not(:first):not(:last)").show();_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<button class="btn1">Hide All except First</button>_x000D_
<button class="btn2">Hide All except First & Last</button>_x000D_
<button class="btn3">Hide First & Last</button>_x000D_
_x000D_
<br/>_x000D_
_x000D_
<div class='test'>First</div>_x000D_
<div class='test'>Second</div>_x000D_
<div class='test'>Third</div>_x000D_
<div class='test'>Last</div>
_x000D_
Using generator:
def primes(num):
if 2 <= num:
yield 2
for i in range(3, num + 1, 2):
if all(i % x != 0 for x in range(3, int(math.sqrt(i) + 1))):
yield i
Usage:
for i in primes(10):
print(i)
2, 3, 5, 7
Could not find stored procedure?---- means when you get this.. our code like this
String sp="{call GetUnitReferenceMap}";
stmt=conn.prepareCall(sp);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
currencyMap.put(rs.getString(1).trim(), rs.getString(2).trim());
I have 4 DBs(sample1, sample2, sample3) But stmt
will search location is master
Default DB then we will get Exception.
we should provide DB name then problem resolves::
String sp="{call sample1..GetUnitReferenceMap}";
I feel like this has been well covered, maybe except for the following:
Simple KEY
/ INDEX
(or otherwise called SECONDARY INDEX
) do increase performance if selectivity is sufficient. On this matter, the usual recommendation is that if the amount of records in the result set on which an index is applied exceeds 20% of the total amount of records of the parent table, then the index will be ineffective. In practice each architecture will differ but, the idea is still correct.
Secondary Indexes (and that is very specific to mysql) should not be seen as completely separate and different objects from the primary key. In fact, both should be used jointly and, once this information known, provide an additional tool to the mysql DBA: in Mysql, indexes embed the primary key. It leads to significant performance improvements, specifically when cleverly building implicit covering indexes such as described there.
If you feel like your data should be UNIQUE
, use a unique index. You may think it's optional (for instance, working it out at application level) and that a normal index will do, but it actually represents a guarantee for Mysql that each row is unique, which incidentally provides a performance benefit.
You can only use FULLTEXT
(or otherwise called SEARCH INDEX
) with Innodb (In MySQL 5.6.4 and up) and Myisam Engines
You can only use FULLTEXT
on CHAR
, VARCHAR
and TEXT
column types
FULLTEXT
index involves a LOT more than just creating an index. There's a bunch of system tables created, a completely separate caching system and some specific rules and optimizations applied. See http://dev.mysql.com/doc/refman/5.7/en/fulltext-restrictions.html and http://dev.mysql.com/doc/refman/5.7/en/innodb-fulltext-index.html
You can use reduce
which works in all browser except IE8 and lower.
["20","40","80","400"].reduce(function(a, b) {
return parseInt(a, 10) + parseInt(b, 10);
})
I faced the same problem when I renamed my repository on GitHub. I tried to push at which point I got the error
fatal: 'origin' does not appear to be a git repository
fatal: The remote end hung up unexpectedly
I had to change the URL using
git remote set-url origin ssh://[email protected]/username/newRepoName.git
After this all commands started working fine. You can check the change by using
git remote -v
In my case after successfull change it showed correct renamed repo in URL
[aniket@alok Android]$ git remote -v
origin ssh://[email protected]/aniket91/TicTacToe.git (fetch)
origin ssh://[email protected]/aniket91/TicTacToe.git (push)
I know nothing about Jenkins, but it looks like you are trying to access environment variables using some form of unix syntax - that won't work.
If the name of the variable is WORKSPACE, then the value is expanded in Windows batch using
%WORKSPACE%
. That form of expansion is performed at parse time. For example, this will print to screen the value of WORKSPACE
echo %WORKSPACE%
If you need the value at execution time, then you need to use delayed expansion !WORKSPACE!
. Delayed expansion is not normally enabled by default. Use SETLOCAL EnableDelayedExpansion
to enable it. Delayed expansion is often needed because blocks of code within parentheses and/or multiple commands concatenated by &
, &&
, or ||
are parsed all at once, so a value assigned within the block cannot be read later within the same block unless you use delayed expansion.
setlocal enableDelayedExpansion
set WORKSPACE=BEFORE
(
set WORKSPACE=AFTER
echo Normal Expansion = %WORKSPACE%
echo Delayed Expansion = !WORKSPACE!
)
The output of the above is
Normal Expansion = BEFORE
Delayed Expansion = AFTER
Use HELP SET
or SET /?
from the command line to get more information about Windows environment variables and the various expansion options. For example, it explains how to do search/replace and substring operations.
You get this behavior, because int array [ROW][COLUMN] = {1};
does not mean "set all items to one". Let me try to explain how this works step by step.
The explicit, overly clear way of initializing your array would be like this:
#define ROW 2
#define COLUMN 2
int array [ROW][COLUMN] =
{
{0, 0},
{0, 0}
};
However, C allows you to leave out some of the items in an array (or struct/union). You could for example write:
int array [ROW][COLUMN] =
{
{1, 2}
};
This means, initialize the first elements to 1 and 2, and the rest of the elements "as if they had static storage duration". There is a rule in C saying that all objects of static storage duration, that are not explicitly initialized by the programmer, must be set to zero.
So in the above example, the first row gets set to 1,2 and the next to 0,0 since we didn't give them any explicit values.
Next, there is a rule in C allowing lax brace style. The first example could as well be written as
int array [ROW][COLUMN] = {0, 0, 0, 0};
although of course this is poor style, it is harder to read and understand. But this rule is convenient, because it allows us to write
int array [ROW][COLUMN] = {0};
which means: "initialize the very first column in the first row to 0, and all other items as if they had static storage duration, ie set them to zero."
therefore, if you attempt
int array [ROW][COLUMN] = {1};
it means "initialize the very first column in the first row to 1 and set all other items to zero".
Since Docker merges stdout and stderr for us, we can treat the log output like any other shell stream. To redirect the current logs to a file, use a redirection operator
$ docker logs test_container > output.log
docker logs -f test_container > output.log
Instead of sending output to stderr and stdout, redirect your application’s output to a file and map the file to permanent storage outside of the container.
$ docker logs test_container> /tmp/output.log
Docker will not accept relative paths on the command line, so if you want to use a different directory, you’ll need to use the complete path.
Keep in mind that it's the user that is running the oracle database that must have write permissions to the /defaultdir directory, not the user logged into oracle. Typically you're running the database as the user "Oracle". It's not the same user (necessarily) that you created the external table with.
Check your directory permissions, too.
The problem that I had with the above is that I wanted to associate a short cut key with a macro in an xlam which has no visible interface. I found that the folllowing worked
To associate a short cut key with a macro
In Excel (not VBA) on the Developer Tab click Macros - no macros will be shown Type the name of the Sub The Options button should then be enabled Click it Ctrl will be the default Hold down Shift and press the letter you want eg Shift and A will associate Ctrl-Shift-A with the Sub
$files = scandir('folder/');
foreach($files as $file) {
//do your work here
}
or glob may be even better for your needs:
$files = glob('folder/*.{jpg,png,gif}', GLOB_BRACE);
foreach($files as $file) {
//do your work here
}
OpenOffice templates + OOo command line interface.
There are tools and libraries available to ease each of those steps.
May be that helps.
You could use Hortonworks spark-llap library like this
import com.hortonworks.hwc.HiveWarehouseSession
df.write
.format("com.hortonworks.spark.sql.hive.llap.HiveWarehouseConnector")
.mode("append")
.option("table", "myDatabase.myTable")
.save()
The error could be improved, but the problem with your first version is you have a member variable, delegate
, that does not have a default value. All variables in Swift must always have a value. That means that you have to set it up in an initializer which you do not have or you could provide it a default value in-line.
When you make it optional, you allow it to be nil
by default, removing the need to explicitly give it a value or initialize it.
you can simply do this.
TextBox.CheckForIllegalCrossThreadCalls = false;
Option a. Simple straight fwd. What you see is what you get easy to make calculations.
Option b. Too messy to do this inline unless you want to have a site that can stretch. IE if you used the with:86em
however modern browsers seem to handle this functionally adequately for my purposes.. . Personally the only time that i would use something like this is if i were to create a thumbnails catalogue.
/*css*/
ul.myThumbs{}
ul.myThumbs li {float:left; width:50px;}
ul.myThumbs li img{width:50px; height:50px;border:0;}
<!--html-->
<ul><li>
<img src="~/img/products/thumbs/productid.jpg" alt="" />
</li></ul>
Option c. Too messy to maintain.
Adding this solution with grep
and basic sh
builtins for those interested in a more portable solution (independent of bash
version; also works with plain old sh
, on non-Linux platforms etc.)
# GLOB matching
gg=svm-grid-ch
case "$gg" in
*grid*) echo $gg ;;
esac
# REGEXP
if echo "$gg" | grep '^....grid*' >/dev/null ; then echo $gg ; fi
if echo "$gg" | grep '....grid*' >/dev/null ; then echo $gg ; fi
if echo "$gg" | grep 's...grid*' >/dev/null ; then echo $gg ; fi
# Extended REGEXP
if echo "$gg" | egrep '(^....grid*|....grid*|s...grid*)' >/dev/null ; then
echo $gg
fi
Some grep
incarnations also support the -q
(quiet) option as an alternative to redirecting to /dev/null
, but the redirect is again the most portable.
Suppose, you have a class String
:
class String {
public:
String(int n); // allocate n bytes to the String object
String(const char *p); // initializes object with char *p
};
Now, if you try:
String mystring = 'x';
The character 'x'
will be implicitly converted to int
and then the String(int)
constructor will be called. But, this is not what the user might have intended. So, to prevent such conditions, we shall define the constructor as explicit
:
class String {
public:
explicit String (int n); //allocate n bytes
String(const char *p); // initialize sobject with string p
};
If you want upload big size image or data in database. Just change the data type to 'BIG BLOB'
.
This does not allow space in the beginning. But allowes spaces in between words. Also allows for special characters between words. A good regex for FirstName and LastName fields.
\w+.*$
Handling key events consistently is not at all easy.
Firstly, there are two different types of codes: keyboard codes (a number representing the key on the keyboard the user pressed) and character codes (a number representing a Unicode character). You can only reliably get character codes in the keypress
event. Do not try to get character codes for keyup
and keydown
events.
Secondly, you get different sets of values in a keypress
event to what you get in a keyup
or keydown
event.
I recommend this page as a useful resource. As a summary:
If you're interested in detecting a user typing a character, use the keypress
event. IE bizarrely only stores the character code in keyCode
while all other browsers store it in which
. Some (but not all) browsers also store it in charCode
and/or keyCode
. An example keypress handler:
function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
alert(charStr);
}
If you're interested in detecting a non-printable key (such as a cursor key), use the keydown
event. Here keyCode
is always the property to use. Note that keyup
events have the same properties.
function(evt) {
evt = evt || window.event;
var keyCode = evt.keyCode;
// Check for left arrow key
if (keyCode == 37) {
alert("Left arrow");
}
}
You must have some virtual function declared in one of the parent classes and never implemented in any of the child classes. Make sure that all virtual functions are implemented somewhere in the inheritence chain. If a class's definition includes a pure virtual function that is never implemented, an instance of that class cannot ever be constructed.
I had the same issue in Win7 regarding running a script (.bat) at startup (When the computer boots vs when someone logs in) that would modify the network parameters using netsh. What ended up working for me was the following:
Click on “Create New Task” on the right hand side of the screen and set the parameters as follows:
a. Set the user account to SYSTEM
b. Choose "Run with highest privileges"
c. Choose the OS for Windows7
When I want to split the screens I usually do one of the following:
For simple iteration of key/values, sometimes libraries like underscorejs can be your friend.
const _ = require('underscore');
_.each(a, function (value, key) {
// handle
});
just for reference
I think this might have updated with jQuery 1.9.*
I'm finding the this is the only thing that works for me at the moment:
$._data($("#yourElementID")[0]).events
I created the following pipe for getting desired items from a list.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(items: any[], filter: string): any {
if(!items || !filter) {
return items;
}
// To search values only of "name" variable of your object(item)
//return items.filter(item => item.name.toLowerCase().indexOf(filter.toLowerCase()) !== -1);
// To search in values of every variable of your object(item)
return items.filter(item => JSON.stringify(item).toLowerCase().indexOf(filter.toLowerCase()) !== -1);
}
}
Lowercase conversion is just to match in case insensitive way. You can use it in your view like this:-
<div>
<input type="text" placeholder="Search reward" [(ngModel)]="searchTerm">
</div>
<div>
<ul>
<li *ngFor="let reward of rewardList | filter:searchTerm">
<div>
<img [src]="reward.imageUrl"/>
<p>{{reward.name}}</p>
</div>
</li>
</ul>
</div>
// 2 dimensional array of arrays of Ints
var arr = [[Int]]()
OR:
// 2 dimensional array of arrays of Ints
var arr: [[Int]] = []
OR if you need an array of predefined size (as mentioned by @0x7fffffff in comments):
// 2 dimensional array of arrays of Ints set to 0. Arrays size is 10x5
var arr = Array(count: 3, repeatedValue: Array(count: 2, repeatedValue: 0))
// ...and for Swift 3+:
var arr = Array(repeating: Array(repeating: 0, count: 2), count: 3)
arr[0][1] = 18
OR
let myVar = 18
arr[0][1] = myVar
arr[1] = [123, 456, 789]
OR
arr[0] += 234
OR
arr[0] += [345, 678]
If you had 3x2 array of 0(zeros) before these changes, now you have:
[
[0, 0, 234, 345, 678], // 5 elements!
[123, 456, 789],
[0, 0]
]
So be aware that sub arrays are mutable and you can redefine initial array that represented matrix.
let a = 0
let b = 1
if arr.count > a && arr[a].count > b {
println(arr[a][b])
}
Remarks: Same markup rules for 3 and N dimensional arrays.
Notepad v7.6 includes a Plugin Admin and from this you can install Plugin Manager(note1) but it doesn't work fine with npp v7.6(note2)
On the other hand Plugin Admin is only available on NPP "Setup version" and after following conditions
Plugin Admin will place plugins at C:\ProgramData\Notepad++\plugins
(note1)Installation from Plugin Admin is not complete and \updater\gpup.exe is missing (note2) Plugin manager is not using new plugins path and folder structure; from version 7.6 npp Plugins will be stored in individual folders (having same name than file.dll)
If you want to use npp7.6 portable, you can copy updater folder from Setup version, copy plugins from Setup version, or copy Plugins from npp v<7.6 and place each one in a individual folder.
You have to follow these steps:
Open the php configuration file, which is located in the following directory
C: \ xampp \ php \ php.ini
Within that file search the extension section and uncomment the following lines
extension = php_pdo_pgsql.dll
extension = php_pgsql.dll
and restart your apache
According to the documentation: https://jinja.palletsprojects.com/en/2.10.x/templates/#line-statements you may use multi-line statements as long as the code has parens/brackets around it. Example:
{% if ( (foo == 'foo' or bar == 'bar') and
(fooo == 'fooo' or baar == 'baar') ) %}
<li>some text</li>
{% endif %}
Edit: Using line_statement_prefix = '#'
* the code would look like this:
# if ( (foo == 'foo' or bar == 'bar') and
(fooo == 'fooo' or baar == 'baar') )
<li>some text</li>
# endif
*Here's an example of how you'd specify the line_statement_prefix
in the Environment
:
from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
loader=PackageLoader('yourapplication', 'templates'),
autoescape=select_autoescape(['html', 'xml']),
line_statement_prefix='#'
)
Or using Flask:
from flask import Flask
app = Flask(__name__, instance_relative_config=True, static_folder='static')
app.jinja_env.filters['zip'] = zip
app.jinja_env.line_statement_prefix = '#'
I'm not entirely sure of the general purpose of the function, but you could always do this:
function getMachine(color, qty) {
var retval;
$("#getMachine li").each(function() {
var thisArray = $(this).text().split("~");
if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
retval = thisArray[3];
return false;
}
});
return retval;
}
var retval = getMachine(color, qty);
DATE(readingstamp) BETWEEN '2016-07-21' AND '2016-07-31' AND TIME(readingstamp) BETWEEN '08:00:00' AND '17:59:59'
simply separate the casting of date and time
A frequent source of these bugs is when you have a method that accepts a reference or pointer to an object but leaves ownership unclear. Style and commenting conventions can make this less likely.
Let the case where the function takes ownership of the object be the special case. In all situations where this happens, be sure to write a comment next to the function in the header file indicating this. You should strive to make sure that in most cases the module or class which allocates an object is also responsible for deallocating it.
Using const can help a lot in some cases. If a function will not modify an object, and does not store a reference to it that persists after it returns, accept a const reference. From reading the caller's code it will be obvious that your function has not accepted ownership of the object. You could have had the same function accept a non-const pointer, and the caller may or may not have assumed that the callee accepted ownership, but with a const reference there's no question.
Do not use non-const references in argument lists. It is very unclear when reading the caller code that the callee may have kept a reference to the parameter.
I disagree with the comments recommending reference counted pointers. This usually works fine, but when you have a bug and it doesn't work, especially if your destructor does something non-trivial, such as in a multithreaded program. Definitely try to adjust your design to not need reference counting if it's not too hard.
i was having same problem with this error. It turn out my Kenel.php is having a wrong syntax when i try to comply with wrong php8 syntax
The line should be
protected $commands = [
//
];
instead of
protected array $commands = [
//
];
Adding a bit to mitigate the confusion here. Even though Darren Davies' (accepted) answer is more straight forward, I think Andrei's answer is a better approach for MVC applications.
The answer from Andrei means that you can use HttpContext
just as you would use System.Web.HttpContext.Current
. For example, if you want to do this:
System.Web.HttpContext.Current.User.Identity.Name
you should instead do this:
HttpContext.User.Identity.Name
Both achieve the same result, but (again) in terms of MVC, the latter is more recommended.
Another good and also straight forward information regarding this matter can be found here: Difference between HttpContext.Current and Controller.Context in MVC ASP.NET.
You can handle custom cell in uicollection view see below code.
- (void)viewDidLoad
{
UINib *nib2 = [UINib nibWithNibName:@"YourCustomCell" bundle:nil];
[CollectionVW registerNib:nib2 forCellWithReuseIdentifier:@"YourCustomCell"];
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setItemSize:CGSizeMake(200, 230)];
flowLayout.minimumInteritemSpacing = 0;
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
[CollectionVW setCollectionViewLayout:flowLayout];
[CollectionVW reloadData];
}
#pragma mark - COLLECTIONVIEW
#pragma mark Collection View CODE
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return Array.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"YourCustomCell";
YourCustomCell *cell = (YourCustomCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
cell.MainIMG.image=[UIImage imageNamed:[Array objectAtIndex:indexPath.row]];
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
}
#pragma mark Collection view layout things
// Layout: Set cell size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
CGSize mElementSize;
mElementSize=CGSizeMake(kScreenWidth/3.4, 150);
return mElementSize;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
return 5.0;
}
// Layout: Set Edges
- (UIEdgeInsets)collectionView: (UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
if (isIphone5 || isiPhone4)
{
return UIEdgeInsetsMake(15,15,5,15); // top, left, bottom, right
}
else if (isIphone6)
{
return UIEdgeInsetsMake(15,15,5,15); // top, left, bottom, right
}
else if (isIphone6P)
{
return UIEdgeInsetsMake(15,15,5,15); // top, left, bottom, right
}
return UIEdgeInsetsMake(15,15,5,15); // top, left, bottom, right
}
z
means (un)z_ip.x
means ex_tract files from the archive.v
means print the filenames v_erbosely.f
means the following argument is a f_ilename.For more details, see tar
's man page.
It's an infamous problem: .equals()
for arrays is badly broken, just don't use it, ever.
That said, it's not "broken" as in "someone has done it in a really wrong way" — it's just doing what's defined and not what's usually expected. So for purists: it's perfectly fine, and that also means, don't use it, ever.
Now the expected behaviour for equals
is to compare data. The default behaviour is to compare the identity, as Object
does not have any data (for purists: yes it has, but it's not the point); assumption is, if you need equals
in subclasses, you'll implement it. In arrays, there's no implementation for you, so you're not supposed to use it.
So the difference is, Arrays.equals(array1, array2)
works as you would expect (i.e. compares content), array1.equals(array2)
falls back to Object.equals
implementation, which in turn compares identity, and thus better replaced by ==
(for purists: yes I know about null
).
Problem is, even Arrays.equals(array1, array2)
will bite you hard if elements of array do not implement equals
properly. It's a very naive statement, I know, but there's a very important less-than-obvious case: consider a 2D array.
2D array in Java is an array of arrays, and arrays' equals
is broken (or useless if you prefer), so Arrays.equals(array1, array2)
will not work as you expect on 2D arrays.
Hope that helps.
I was able to get this to work by using the Invoke-Expression
cmdlet.
Invoke-Expression "& `"$scriptPath`" test -r $number -b $testNumber -f $FileVersion -a $ApplicationID"
There are several useful answers, but none seem to cover all the latest options. To that end all my examples also cater for the presence of matching label
elements and also allow you to dynamically add checkboxes and see the results in a side-panel (by redirecting console.log
).
Listening for click
events on checkboxes
is not a good idea as that will not allow for keyboard toggling or for changes made where a matching label
element was clicked. Always listen for the change
event.
Use the jQuery :checkbox
pseudo-selector, rather than input[type=checkbox]
. :checkbox
is shorter and more readable.
Use is()
with the jQuery :checked
pseudo-selector to test for whether a checkbox is checked. This is guaranteed to work across all browsers.
$('#myform :checkbox').change(function () {
if ($(this).is(':checked')) {
console.log($(this).val() + ' is now checked');
} else {
console.log($(this).val() + ' is now unchecked');
}
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/2/
:checkbox
selector, which is preferable to using input[type=checkbox]
Delegated event handlers are designed for situations where the elements may not yet exist (dynamically loaded or created) and is very useful. They delegate responsibility to an ancestor element (hence the term).
$('#myform').on('change', ':checkbox', function () {
if ($(this).is(':checked')) {
console.log($(this).val() + ' is now checked');
} else {
console.log($(this).val() + ' is now unchecked');
}
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/4/
change
) to bubble up to a non-changing ancestor element (in this case #myform
). ':checkbox'
in this case) to only the elements in the bubble chain.document
as the default to connect the delegated event handler, if nothing else is closer/convenient. body
to attach delegated events as it has a bug (to do with styling) that can stop it getting mouse events.The upshot of delegated handlers is that the matching elements only need to exist at event time and not when the event handler was registered. This allows for dynamically added content to generate the events.
Q: Is it slower?
A: So long as the events are at user-interaction speeds, you do not need to worry about the negligible difference in speed between a delegated event handler and a directly connected handler. The benefits of delegation far outweigh any minor downside. Delegated event handlers are actually faster to register as they typically connect to a single matching element.
prop('checked', true)
fire the change
event?This is actually by design. If it did fire the event you would easily get into a situation of endless updates. Instead, after changing the checked property, send a change event to the same element using trigger
(not triggerHandler
):
e.g. without trigger
no event occurs
$cb.prop('checked', !$cb.prop('checked'));
JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/5/
e.g. with trigger
the normal change event is caught
$cb.prop('checked', !$cb.prop('checked')).trigger('change');
JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/6/
Notes:
triggerHandler
as was suggested by one user, as it will not bubble events to a delegated event handler.JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/8/
although it will work for an event handler directly connected to the element:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/9/
Events triggered with .triggerHandler() do not bubble up the DOM hierarchy; if they are not handled by the target element directly, they do nothing.
Reference: http://api.jquery.com/triggerhandler/
If anyone has additional features they feel are not covered by this, please do suggest additions.
Try this
<html>
<head>
<script type="text/javascript">
function runProgram()
{
var shell = new ActiveXObject("WScript.Shell");
var appWinMerge = "\"C:\\Program Files\\WinMerge\\WinMergeU.exe\" /e /s /u /wl /wr /maximize";
var fileLeft = "\"D:\\Path\\to\\your\\file\"";
var fileRight= "\"D:\\Path\\to\\your\\file2\"";
shell.Run(appWinMerge + " " + fileLeft + " " + fileRight);
}
</script>
</head>
<body>
<a href="javascript:runProgram()">Run program</a>
</body>
</html>
Try this one.
Sample Code
String str = " hello there ";
System.out.println(str.replaceAll("( +)"," ").trim());
OUTPUT
hello there
First it will replace all the spaces with single space. Than we have to supposed to do trim String
because Starting of the String
and End of the String
it will replace the all space with single space if String
has spaces at Starting of the String
and End of the String
So we need to trim them. Than you get your desired String
.
As @Ansgar mentioned, [[
is a bashism, ie built into Bash and not available for other shells. If you want your script to be portable, use [
. Comparisons will also need a different syntax: change ==
to =
.
requests
does not handle parsing XML responses, no. XML responses are much more complex in nature than JSON responses, how you'd serialize XML data into Python structures is not nearly as straightforward.
Python comes with built-in XML parsers. I recommend you use the ElementTree API:
import requests
from xml.etree import ElementTree
response = requests.get(url)
tree = ElementTree.fromstring(response.content)
or, if the response is particularly large, use an incremental approach:
response = requests.get(url, stream=True)
# if the server sent a Gzip or Deflate compressed response, decompress
# as we read the raw stream:
response.raw.decode_content = True
events = ElementTree.iterparse(response.raw)
for event, elem in events:
# do something with `elem`
The external lxml project builds on the same API to give you more features and power still.
In simple sense the idea is to fill another tower among the three defined towers in the same order of discs as present without a larger disc overlapping a small disc at any time during the procedure.
Let 'A' , 'B' and 'C' be three towers. 'A' will be the tower containing 'n' discs initially. 'B' can be used as intermediate tower and 'C' is the target tower.
The algo is as follows:
The code is as follows in java:
public class TowerOfHanoi {
public void TOH(int n, int A , int B , int C){
if (n>0){
TOH(n-1,A,C,B);
System.out.println("Move a disk from tower "+A +" to tower " + C);
TOH(n-1,B,A,C);
}
}
public static void main(String[] args) {
new TowerOfHanoi().TOH(3, 1, 2, 3);
}
}
Simply declare your variable to final
In REST, each HTTP verbs has its place and meaning.
For example,
GET is to get the 'resource(s)' that is pointed to in the URL.
POST is to instructure the backend to 'create' a resource of the 'type' pointed to in the URL. You can supplement the POST operation with parameters or additional data in the body of the POST call.
In you case, since you are interested in 'getting' the info using query, thus it should be a GET operation instead of a POST operation.
This wiki may help to further clarify things.
Hope this help!
That code should work, but you need to include the localization in your page (it isn't included by default). Try putting this in your <head>
tag, somewhere after you include jQuery and jQueryUI:
<script type="text/javascript"
src="https://raw.githubusercontent.com/jquery/jquery-ui/master/ui/i18n/datepicker-fr.js">
</script>
I can't find where this is documented on the jQueryUI site, but if you view the source of this demo you'll see that this is how they do it. Also, please note that including this JS file will set the datepicker defaults to French, so if you want only some datepickers to be in French, you'll have to set the default back to English.
You can find all languages here at github: https://github.com/jquery/jquery-ui/tree/master/ui/i18n
There is a Headers
property in the HttpRequestMessage
class. You can add custom headers there, which will be sent with each HTTP request. The DefaultRequestHeaders
in the HttpClient
class, on the other hand, sets headers to be sent with each request sent using that client object, hence the name Default Request Headers.
Hope this makes things more clear, at least for someone seeing this answer in future.
If you didn't index too much data into the index yet, you can use term facet query on the field that you would like to debug to see the tokens and their frequencies:
curl -XDELETE 'http://localhost:9200/test-idx'
echo
curl -XPUT 'http://localhost:9200/test-idx' -d '
{
"settings": {
"index.number_of_shards" : 1,
"index.number_of_replicas": 0
},
"mappings": {
"doc": {
"properties": {
"message": {"type": "string", "analyzer": "snowball"}
}
}
}
}'
echo
curl -XPUT 'http://localhost:9200/test-idx/doc/1' -d '
{
"message": "How is this going to be indexed?"
}
'
echo
curl -XPOST 'http://localhost:9200/test-idx/_refresh'
echo
curl -XGET 'http://localhost:9200/test-idx/doc/_search?pretty=true&search_type=count' -d '{
"query": {
"match": {
"_id": "1"
}
},
"facets": {
"tokens": {
"terms": {
"field": "message"
}
}
}
}
'
echo
For both Python 3 and Python 2, this works:
try:
from urllib.request import Request, urlopen # Python 3
except ImportError:
from urllib2 import Request, urlopen # Python 2
req = Request('http://api.company.com/items/details?country=US&language=en')
req.add_header('apikey', 'xxx')
content = urlopen(req).read()
print(content)
If you need an array, separate the array columns with a comma:
SELECT * FROM (VALUES('WOMENS'),('MENS'),('CHILDRENS')) as X([Attribute])
,(VALUES(742),(318)) AS z([StoreID])
My thought is that you can never just swap ends, you must always move from beginning-to-end, move through the string and look for "how many bytes will this character require?" I attach the character starting at the original end position, and remove the character from the front of the string.
void StringReverser(std::string *original)
{
int eos = original->length() - 1;
while (eos > 0) {
char c = (*original)[0];
int characterBytes;
switch( (c & 0xF0) >> 4 ) {
case 0xC:
case 0xD: /* U+000080-U+0007FF: two bytes. */
characterBytes = 2;
break;
case 0xE: /* U+000800-U+00FFFF: three bytes. */
characterBytes = 3;
break;
case 0xF: /* U+010000-U+10FFFF: four bytes. */
characterBytes = 4;
break;
default:
characterBytes = 1;
break;
}
for (int i = 0; i < characterBytes; i++) {
original->insert(eos+i, 1, (*original)[i]);
}
original->erase(0, characterBytes);
eos -= characterBytes;
}
}
<!DOCTYPE html>
<html>
<head>
<style>
.block-system-branding-block {
flex: 0 1 40%;
}
@media screen and (min-width: 48em) {
.block-system-branding-block {
flex: 0 1 420px;
margin: 2.5rem 0;
text-align: left;
}
}
.flex-containerrow {
display: flex;
}
.flex-containerrow > div {
justify-content: center;
align-items: center;
}
.flex-containercolumn {
display: flex;
flex-direction: column;
}
.flex-containercolumn > div {
width: 300px;
margin: 10px;
text-align: left;
line-height: 20px;
font-size: 16px;
}
.flex-containercolumn > site-slogan {font-size: 12px;}
.flex-containercolumn > div > span{ font-size: 12px;}
</style>
</head>
<body>
<div id="block-umami-branding" class="block-system block-
system-branding-block">
<div class="flex-containerrow">
<div>
<a href="/" rel="home" class="site-logo">
<img src="https://placehold.it/120x120" alt="Home">
</a>
</div><div class="flex-containerrow"><div class="flex-containercolumn">
<div class="site-name ">
<a href="/" title="Home" rel="home">This is my sitename</a>
</div>
<div class="site-slogan "><span>Department of Test | Ministry of Test |
TGoII</span></div>
</div></div>
</div>
</div>
</body>
</html>
I explored the google docs and found that developer key and api is same thing.
var
stlst: TStringList;
begin
Label1.Caption := 'Hello,'+sLineBreak+'world!';
Label2.Caption := 'Hello,'#13#10'world!';
Label3.Caption := 'Hello,' + chr(13) + chr(10) + 'world!';
stlst := TStringList.Create;
stlst.Add('Hello,');
stlst.Add('world!');
Label4.Caption := stlst.Text;
Label5.WordWrap := True; //Multi-line Caption
Label5.Caption := 'Hello,'^M^J'world!';
Label6.Caption := AdjustLineBreaks('Hello,'#10'world!');
{http://delphi.about.com/library/rtl/blrtlAdjustLineBreaks.htm}
end;
I solved this problem I increased memory resource
resources:
limits:
cpu: 1
memory: 1Gi
requests:
cpu: 100m
memory: 250Mi
A mock is both a technical and a functional object.
The mock is technical. It is indeed created by a mocking library (EasyMock, JMockit and more recently Mockito are known for these) thanks to byte code generation.
The mock implementation is generated in a way where we could instrument it to return a specific value when a method is invoked but also some other things such as verifying that a mock method was invoked with some specific parameters (strict check) or whatever the parameters (no strict check).
Instantiating a mock :
@Mock Foo fooMock
Recording a behavior :
when(fooMock.hello()).thenReturn("hello you!");
Verifying an invocation :
verify(fooMock).hello()
These are clearly not the natural way to instantiate/override the Foo class/behavior. That's why I refer to a technical aspect.
But the mock is also functional because it is an instance of the class we need to isolate from the SUT. And with recorded behaviors on it, we could use it in the SUT in the same way than we would do with a stub.
The stub is just a functional object : that is an instance of the class we need to isolate from the SUT and that's all.
That means that both the stub class and all behaviors fixtures needed during our unit tests have to be defined explicitly.
For example to stub hello()
would need to subclass the Foo
class (or implements its interface it has it) and to override hello()
:
public class HelloStub extends Hello{
public String hello {
return "hello you!";
}
}
If another test scenario requires another value return, we would probably need to define a generic way to set the return :
public class HelloStub extends Hello{
public HelloStub(String helloReturn){
this.helloReturn = helloReturn;
}
public String hello {
return helloReturn;
}
}
Other scenario : if I had a side effect method (no return) and I would check that that method was invoked, I should probably have added a boolean or a counter in the stub class to count how many times the method was invoked.
Conclusion
The stub requires often much overhead/code to write for your unit test. What mock prevents thanks to providing recording/verifying features out of the box.
That's why nowadays, the stub approach is rarely used in practice with the advent of excellent mock libraries.
About the Martin Fowler Article : I don't think to be a "mockist" programmer while I use mocks and I avoid stubs.
But I use mock when it is really required (annoying dependencies) and I favor test slicing and mini-integration tests when I test a class with dependencies which mocking would be an overhead.
I normally have all of my work in a dropbox folder. This ensures me that I would have the current folder available outside my local machine and Github. I think it's my other step to guarantee a "version control" other than git. You can follow this in order to revert your file to previous versions of your dropbox files
Hope this helps.
This may happen due to the following reasons -
So by removing the implementation or adding them can remove this error. You can remove the "uses" code in the android manifest file.
Examples:
this wasted my 1 hour, cause I mistakenly added a class of wearable type, of course, I safe deleted that using refractor but it Didi not made changes to manifest file.
I used the firebase crashlytics code in my java project but I mistakenly deleted that in buld.gradle. Here below: implementation 'com.google.firebase:firebase-crashlytics:17.1.1'
The solution is in either BUILD>GRADLE or in AndroidManifest.xml, mostly.
For a class Book
like this:
package books;
public class Book {
private Integer id;
private Integer number;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "book{" +
"id=" + id +
", number=" + number +
", name='" + name + '\'' + '\n' +
'}';
}
}
sorting main class with mock objects
package books;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
System.out.println("Hello World!");
Book b = new Book();
Book c = new Book();
Book d = new Book();
Book e = new Book();
Book f = new Book();
Book g = new Book();
Book g1 = new Book();
Book g2 = new Book();
Book g3 = new Book();
Book g4 = new Book();
b.setId(1);
b.setNumber(12);
b.setName("gk");
c.setId(2);
c.setNumber(12);
c.setName("gk");
d.setId(2);
d.setNumber(13);
d.setName("maths");
e.setId(3);
e.setNumber(3);
e.setName("geometry");
f.setId(3);
f.setNumber(34);
b.setName("gk");
g.setId(3);
g.setNumber(11);
g.setName("gk");
g1.setId(3);
g1.setNumber(88);
g1.setName("gk");
g2.setId(3);
g2.setNumber(91);
g2.setName("gk");
g3.setId(3);
g3.setNumber(101);
g3.setName("gk");
g4.setId(3);
g4.setNumber(4);
g4.setName("gk");
List<Book> allBooks = new ArrayList<Book>();
allBooks.add(b);
allBooks.add(c);
allBooks.add(d);
allBooks.add(e);
allBooks.add(f);
allBooks.add(g);
allBooks.add(g1);
allBooks.add(g2);
allBooks.add(g3);
allBooks.add(g4);
System.out.println(allBooks.size());
Collections.sort(allBooks, new Comparator<Book>() {
@Override
public int compare(Book t, Book t1) {
int a = t.getId()- t1.getId();
if(a == 0){
int a1 = t.getNumber() - t1.getNumber();
return a1;
}
else
return a;
}
});
System.out.println(allBooks);
}
}
Run the application in Emulator after you insert some data, just close the application.
Now open the DDMS or Android Monitor and select your emulator, on the right side you can see the File Explorer, look for Data folder in it and look for your application package that you have created, in that you can find the shared preference file open it , you can see the XML file, click it and click the pull a file from the device button in the top right corner.
The XML file will be saved in your desired location, then you can open it using any editor like notepad++ and can view the data you have entered.
You can execute raw sql in EF Core - Add this class to your project. This will allow you to execute raw SQL and get the raw results without having to define a POCO and a DBSet. See https://github.com/aspnet/EntityFramework/issues/1862#issuecomment-220787464 for original example.
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Storage;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.EntityFrameworkCore
{
public static class RDFacadeExtensions
{
public static RelationalDataReader ExecuteSqlQuery(this DatabaseFacade databaseFacade, string sql, params object[] parameters)
{
var concurrencyDetector = databaseFacade.GetService<IConcurrencyDetector>();
using (concurrencyDetector.EnterCriticalSection())
{
var rawSqlCommand = databaseFacade
.GetService<IRawSqlCommandBuilder>()
.Build(sql, parameters);
return rawSqlCommand
.RelationalCommand
.ExecuteReader(
databaseFacade.GetService<IRelationalConnection>(),
parameterValues: rawSqlCommand.ParameterValues);
}
}
public static async Task<RelationalDataReader> ExecuteSqlQueryAsync(this DatabaseFacade databaseFacade,
string sql,
CancellationToken cancellationToken = default(CancellationToken),
params object[] parameters)
{
var concurrencyDetector = databaseFacade.GetService<IConcurrencyDetector>();
using (concurrencyDetector.EnterCriticalSection())
{
var rawSqlCommand = databaseFacade
.GetService<IRawSqlCommandBuilder>()
.Build(sql, parameters);
return await rawSqlCommand
.RelationalCommand
.ExecuteReaderAsync(
databaseFacade.GetService<IRelationalConnection>(),
parameterValues: rawSqlCommand.ParameterValues,
cancellationToken: cancellationToken);
}
}
}
}
Here's an example of how to use it:
// Execute a query.
using(var dr = await db.Database.ExecuteSqlQueryAsync("SELECT ID, Credits, LoginDate FROM SamplePlayer WHERE " +
"Name IN ('Electro', 'Nitro')"))
{
// Output rows.
var reader = dr.DbDataReader;
while (reader.Read())
{
Console.Write("{0}\t{1}\t{2} \n", reader[0], reader[1], reader[2]);
}
}
Probably the easiest way is to use the timers plugin. http://plugins.jquery.com/project/timers and then call something like
$(this).oneTime(1000, function() {
$("#something").hide();
});
To request a new password for the postgres user (without showing it in the command):
sudo -u postgres psql -c "\password"
Not sure why @user3133050 is voted down, that's all you need to do...
Here's the structure you need, based on your script tag's src, assuming you are trying to load moment.js
into index.html
:
/js/moment.js
/some-other-directory/index.html
The ../
looks "up" at the "some-other-directory" folder level, finds the js
folder next to it, and loads the moment.js
inside.
It sounds like your index.html
is at root level, or nested even deeper.
If you're still struggling, create a test.js
file in the same location as index.html
, and add a <script src="test.js"></script>
and see if that loads. If that fails, check your syntax. Tested in Chrome 46.
You should verify that new File(".")
is really pointing to where you think it is pointing - .classpath
suggests the root of some Eclipse project....
Try this. I've use the Large Object Binary (LOB) format for storing generated PDF documents, some of which were 10+ MB in size, in a database and it worked wonderfully.
It is possible to load the second version of the jQuery use it and then restore to the original or keep the second version if there was no jQuery loaded before. Here is an example:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
var jQueryTemp = jQuery.noConflict(true);
var jQueryOriginal = jQuery || jQueryTemp;
if (window.jQuery){
console.log('Original jQuery: ', jQuery.fn.jquery);
console.log('Second jQuery: ', jQueryTemp.fn.jquery);
}
window.jQuery = window.$ = jQueryTemp;
</script>
<script type="text/javascript">
console.log('Script using second: ', jQuery.fn.jquery);
</script>
<script type="text/javascript">
// Restore original jQuery:
window.jQuery = window.$ = jQueryOriginal;
console.log('Script using original or the only version: ', jQuery.fn.jquery);
</script>
Only this worked for me:
#container:hover .cube { background-color: yellow; }
Where .cube
is CssClass of the #cube
.
Tested in Firefox, Chrome and Edge.
The comment of @enl8enmentnow should be an answer to fix the problem using genymotion:
If you have this problem on Genymotion even when using the ARM translator it is because you are creating an x86 virtual device like the Google Nexus 10. Pick an ARM virtual device instead, like one of the Custom Tablets.
Nope, there is not. You'll have to use the primitive long
data type and deal with signedness issues, or use a class such as BigInteger
.
I've found the following "pattern" to be very useful:
MainCtrl.$inject = ['$scope', '$rootScope', '$location', 'socket', ...];
function MainCtrl (scope, rootscope, location, thesocket, ...) {
where, MainCtrl is a controller. I am uncomfortable relying on the parameter names of the Controller function doing a one-for-one mimic of the instances for fear that I might change names and muck things up. I much prefer explicitly using $inject for this purpose.
If the program was written in C# you can get the source code in almost its original form using .NET Reflector. You won't be able to see comments and local variable names, but it is very readable.
If it was written C++ it's not so easy... even if you could decompile the code into valid C++ it is unlikely that it will resemble the original source because of inlined functions and optimizations which are hard to reverse.
Please note that by reverse engineering and modifying the source code you might breaking the terms of use of the programs unless you wrote them yourself or have permission from the author.
Check out this one:
https://github.com/VBA-tools/VBA-Web
It's a high level library for dealing with REST. It's OOP, works with JSON, but also works with any other format.
You can use git checkout <file>
to check out the committed version of the file (thus discarding your changes), or git reset --hard HEAD
to throw away any uncommitted changes for all files.
There are 5 6 NINE (or 63*, depending how you count) different ways to write multi-line strings in YAML.
Use >
most of the time: interior line breaks are stripped out, although you get one at the end:
key: >
Your long
string here.
Use |
if you want those linebreaks to be preserved as \n
(for instance, embedded markdown with paragraphs).
key: |
### Heading
* Bullet
* Points
Use >-
or |-
instead if you don't want a linebreak appended at the end.
Use "..."
if you need to split lines in the middle of words or want to literally type linebreaks as \n
:
key: "Antidisestab\
lishmentarianism.\n\nGet on it."
YAML is crazy.
>
, |
)These allow characters such as \
and "
without escaping, and add a new line (\n
) to the end of your string.
>
Folded style removes single newlines within the string (but adds one at the end, and converts double newlines to singles):
Key: >
this is my very very very
long string
? this is my very very very long string\n
|
Literal style turns every newline within the string into a literal newline, and adds one at the end:
Key: |
this is my very very very
long string
? this is my very very very\nlong string\n
Here's the official definition from the YAML Spec 1.2
Scalar content can be written in block notation, using a literal style (indicated by “|”) where all line breaks are significant. Alternatively, they can be written with the folded style (denoted by “>”) where each line break is folded to a space unless it ends an empty or a more-indented line.
>-
, |-
, >+
, |+
)You can control the handling of the final new line in the string, and any trailing blank lines (\n\n
) by adding a block chomping indicator character:
>
, |
: "clip": keep the line feed, remove the trailing blank lines.>-
, |-
: "strip": remove the line feed, remove the trailing blank lines.>+
, |+
: "keep": keep the line feed, keep trailing blank lines.
, "
, '
)These have limited escaping, and construct a single-line string with no new line characters. They can begin on the same line as the key, or with additional newlines first.
plain style (no escaping, no #
or :
combinations, limits on first character):
Key: this is my very very very
long string
double-quoted style (\
and "
must be escaped by \
, newlines can be inserted with a literal \n
sequence, lines can be concatenated without spaces with trailing \
):
Key: "this is my very very \"very\" loooo\
ng string.\n\nLove, YAML."
→ "this is my very very \"very\" loooong string.\n\nLove, YAML."
single-quoted style (literal '
must be doubled, no special characters, possibly useful for expressing strings starting with double quotes):
Key: 'this is my very very "very"
long string, isn''t it.'
→ "this is my very very \"very\" long string, isn't it."
In this table, _
means space character
. \n
means "newline character" (\n
in JavaScript), except for the "in-line newlines" row, where it means literally a backslash and an n).
> | " ' >- >+ |- |+
-------------------------|------|-----|-----|-----|------|------|------|------
Trailing spaces | Kept | Kept | | | | Kept | Kept | Kept | Kept
Single newline => | _ | \n | _ | _ | _ | _ | _ | \n | \n
Double newline => | \n | \n\n | \n | \n | \n | \n | \n | \n\n | \n\n
Final newline => | \n | \n | | | | | \n | | \n
Final dbl nl's => | | | | | | | Kept | | Kept
In-line newlines | No | No | No | \n | No | No | No | No | No
Spaceless newlines| No | No | No | \ | No | No | No | No | No
Single quote | ' | ' | ' | ' | '' | ' | ' | ' | '
Double quote | " | " | " | \" | " | " | " | " | "
Backslash | \ | \ | \ | \\ | \ | \ | \ | \ | \
" #", ": " | Ok | Ok | No | Ok | Ok | Ok | Ok | Ok | Ok
Can start on same | No | No | Yes | Yes | Yes | No | No | No | No
line as key |
Note the trailing spaces on the line before "spaces."
- >
very "long"
'string' with
paragraph gap, \n and
spaces.
- |
very "long"
'string' with
paragraph gap, \n and
spaces.
- very "long"
'string' with
paragraph gap, \n and
spaces.
- "very \"long\"
'string' with
paragraph gap, \n and
s\
p\
a\
c\
e\
s."
- 'very "long"
''string'' with
paragraph gap, \n and
spaces.'
- >-
very "long"
'string' with
paragraph gap, \n and
spaces.
[
"very \"long\" 'string' with\nparagraph gap, \\n and spaces.\n",
"very \"long\"\n'string' with\n\nparagraph gap, \\n and \nspaces.\n",
"very \"long\" 'string' with\nparagraph gap, \\n and spaces.",
"very \"long\" 'string' with\nparagraph gap, \n and spaces.",
"very \"long\" 'string' with\nparagraph gap, \\n and spaces.",
"very \"long\" 'string' with\nparagraph gap, \\n and spaces."
]
Just in case the above isn't enough for you, you can add a "block indentation indicator" (after your block chomping indicator, if you have one):
- >8
My long string
starts over here
- |+1
This one
starts here
If you insert extra spaces at the start of not-the-first lines in Folded style, they will be kept, with a bonus newline. This doesn't happen with flow styles:
- >
my long
string
- my long
string
? ["my long\n string\n", "my long string"]
I can't even.
*
2 block styles, each with 2 possible block chomping indicators (or none), and with 9 possible indentation indicators (or none), 1 plain style and 2 quoted styles: 2 x (2 + 1) x (9 + 1) + 1 + 2 = 63
Some of this information has also been summarised here.
$query=mysql_query("select * from tablename")or die(mysql_error());
$xml="<libraray>\n\t\t";
while($data=mysql_fetch_array($query))
{
$xml .="<mail_address>\n\t\t";
$xml .= "<id>".$data['id']."</id>\n\t\t";
$xml .= "<email>".$data['email_address']."</email>\n\t\t";
$xml .= "<verify_code>".$data['verify']."</verify_code>\n\t\t";
$xml .= "<status>".$data['status']."</status>\n\t\t";
$xml.="</mail_address>\n\t";
}
$xml.="</libraray>\n\r";
$xmlobj=new SimpleXMLElement($xml);
$xmlobj->asXML("text.xml");
Its simple just connect with your database it will create test.xml file in your project folder
You can also like this:
$ nvm alias default lts/fermium
Fn + 7 is a solution for keyboards where the num keypad is merged with the main keypad. Here the key with 7 (and &) is the key that has the blue-coloured 7.
I generally prefer, where possible, to use the default value of value types to determine whether they've been set. This obviously isn't possible all the time, especially with ints - but for DateTimes, I think reserving the MinValue to signify that it hasn't been changed is fair enough. The benefit of this over nullables is that there's one less place where you'll get a null reference exception (and probably lots of places where you don't have to check for null before accessing it!)
Your DateFormat
pattern does not match you input date String
. You could use
new SimpleDateFormat("dd-MMM-yyyy")
Nobody has actually given a pure javascript
answer (as requested by OP), so here it is:
function postAsync(url2get, sendstr) {
var req;
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
// req.overrideMimeType("application/json"); // if request result is JSON
try {
req.open("POST", url2get, false); // 3rd param is whether "async"
}
catch(err) {
alert("couldnt complete request. Is JS enabled for that domain?\\n\\n" + err.message);
return false;
}
req.send(sendstr); // param string only used for POST
if (req.readyState == 4) { // only if req is "loaded"
if (req.status == 200) // only if "OK"
{ return req.responseText ; }
else { return "XHR error: " + req.status +" "+req.statusText; }
}
}
alert("req for getAsync is undefined");
}
var var_str = "var1=" + var1 + "&var2=" + var2;
var ret = postAsync(url, var_str) ;
// hint: encodeURIComponent()
if (ret.match(/^XHR error/)) {
console.log(ret);
return;
}
In your case:
var var_str = "video_time=" + document.getElementById('video_time').value
+ "&video_id=" + document.getElementById('video_id').value;
No.
The content-type should be whatever it is known to be, if you know it. application/octet-stream
is defined as "arbitrary binary data" in RFC 2046, and there's a definite overlap here of it being appropriate for entities whose sole intended purpose is to be saved to disk, and from that point on be outside of anything "webby". Or to look at it from another direction; the only thing one can safely do with application/octet-stream is to save it to file and hope someone else knows what it's for.
You can combine the use of Content-Disposition
with other content-types, such as image/png
or even text/html
to indicate you want saving rather than display. It used to be the case that some browsers would ignore it in the case of text/html
but I think this was some long time ago at this point (and I'm going to bed soon so I'm not going to start testing a whole bunch of browsers right now; maybe later).
RFC 2616 also mentions the possibility of extension tokens, and these days most browsers recognise inline
to mean you do want the entity displayed if possible (that is, if it's a type the browser knows how to display, otherwise it's got no choice in the matter). This is of course the default behaviour anyway, but it means that you can include the filename
part of the header, which browsers will use (perhaps with some adjustment so file-extensions match local system norms for the content-type in question, perhaps not) as the suggestion if the user tries to save.
Hence:
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="picture.png"
Means "I don't know what the hell this is. Please save it as a file, preferably named picture.png".
Content-Type: image/png
Content-Disposition: attachment; filename="picture.png"
Means "This is a PNG image. Please save it as a file, preferably named picture.png".
Content-Type: image/png
Content-Disposition: inline; filename="picture.png"
Means "This is a PNG image. Please display it unless you don't know how to display PNG images. Otherwise, or if the user chooses to save it, we recommend the name picture.png for the file you save it as".
Of those browsers that recognise inline
some would always use it, while others would use it if the user had selected "save link as" but not if they'd selected "save" while viewing (or at least IE used to be like that, it may have changed some years ago).
And for all SQL Server versions
SELECT CAST(0.973684210526315789 * 100 AS DECIMAL(18, 2))
SELECT * FROM courses WHERE (NOW() + INTERVAL 2 HOUR) > start_time
Support, unfortunately, is brutal at best. Here's a post on the topic:
https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/
And the post content:
$sth = mysqli_query($conn, "SELECT ...");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
The function json_encode
needs PHP >= 5.2 and the php-json package - as mentioned here
NOTE: mysql
is deprecated as of PHP 5.5.0, use mysqli
extension instead http://php.net/manual/en/migration55.deprecated.php.
What does copying an object mean? There are a few ways you can copy objects--let's talk about the 2 kinds you're most likely referring to--deep copy and shallow copy.
Since we're in an object-oriented language (or at least are assuming so), let's say you have a piece of memory allocated. Since it's an OO-language, we can easily refer to chunks of memory we allocate because they are usually primitive variables (ints, chars, bytes) or classes we defined that are made of our own types and primitives. So let's say we have a class of Car as follows:
class Car //A very simple class just to demonstrate what these definitions mean.
//It's pseudocode C++/Javaish, I assume strings do not need to be allocated.
{
private String sPrintColor;
private String sModel;
private String sMake;
public changePaint(String newColor)
{
this.sPrintColor = newColor;
}
public Car(String model, String make, String color) //Constructor
{
this.sPrintColor = color;
this.sModel = model;
this.sMake = make;
}
public ~Car() //Destructor
{
//Because we did not create any custom types, we aren't adding more code.
//Anytime your object goes out of scope / program collects garbage / etc. this guy gets called + all other related destructors.
//Since we did not use anything but strings, we have nothing additional to handle.
//The assumption is being made that the 3 strings will be handled by string's destructor and that it is being called automatically--if this were not the case you would need to do it here.
}
public Car(const Car &other) // Copy Constructor
{
this.sPrintColor = other.sPrintColor;
this.sModel = other.sModel;
this.sMake = other.sMake;
}
public Car &operator =(const Car &other) // Assignment Operator
{
if(this != &other)
{
this.sPrintColor = other.sPrintColor;
this.sModel = other.sModel;
this.sMake = other.sMake;
}
return *this;
}
}
A deep copy is if we declare an object and then create a completely separate copy of the object...we end up with 2 objects in 2 completely sets of memory.
Car car1 = new Car("mustang", "ford", "red");
Car car2 = car1; //Call the copy constructor
car2.changePaint("green");
//car2 is now green but car1 is still red.
Now let's do something strange. Let's say car2 is either programmed wrong or purposely meant to share the actual memory that car1 is made of. (It's usually a mistake to do this and in classes is usually the blanket it's discussed under.) Pretend that anytime you ask about car2, you're really resolving a pointer to car1's memory space...that's more or less what a shallow copy is.
//Shallow copy example
//Assume we're in C++ because it's standard behavior is to shallow copy objects if you do not have a constructor written for an operation.
//Now let's assume I do not have any code for the assignment or copy operations like I do above...with those now gone, C++ will use the default.
Car car1 = new Car("ford", "mustang", "red");
Car car2 = car1;
car2.changePaint("green");//car1 is also now green
delete car2;/*I get rid of my car which is also really your car...I told C++ to resolve
the address of where car2 exists and delete the memory...which is also
the memory associated with your car.*/
car1.changePaint("red");/*program will likely crash because this area is
no longer allocated to the program.*/
So regardless of what language you're writing in, be very careful about what you mean when it comes to copying objects because most of the time you want a deep copy.
What are the copy constructor and the copy assignment operator?
I have already used them above. The copy constructor is called when you type code such as Car car2 = car1;
Essentially if you declare a variable and assign it in one line, that's when the copy constructor is called. The assignment operator is what happens when you use an equal sign--car2 = car1;
. Notice car2
isn't declared in the same statement. The two chunks of code you write for these operations are likely very similar. In fact the typical design pattern has another function you call to set everything once you're satisfied the initial copy/assignment is legitimate--if you look at the longhand code I wrote, the functions are nearly identical.
When do I need to declare them myself? If you are not writing code that is to be shared or for production in some manner, you really only need to declare them when you need them. You do need to be aware of what your program language does if you choose to use it 'by accident' and didn't make one--i.e. you get the compiler default. I rarely use copy constructors for instance, but assignment operator overrides are very common. Did you know you can override what addition, subtraction, etc. mean as well?
How can I prevent my objects from being copied? Override all of the ways you're allowed to allocate memory for your object with a private function is a reasonable start. If you really don't want people copying them, you could make it public and alert the programmer by throwing an exception and also not copying the object.
great work on this class. Simple and easy to use. I modified the class to include a title in the first row of the export; figured I would share:
use:
CsvExport myExport = new CsvExport();
myExport.addTitle = String.Format("Name: {0},{1}", lastName, firstName));
class:
public class CsvExport
{
List<string> fields = new List<string>();
public string addTitle { get; set; } // string for the first row of the export
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> currentRow
{
get
{
return rows[rows.Count - 1];
}
}
public object this[string field]
{
set
{
if (!fields.Contains(field)) fields.Add(field);
currentRow[field] = value;
}
}
public void AddRow()
{
rows.Add(new Dictionary<string, object>());
}
string MakeValueCsvFriendly(object value)
{
if (value == null) return "";
if (value is Nullable && ((INullable)value).IsNull) return "";
if (value is DateTime)
{
if (((DateTime)value).TimeOfDay.TotalSeconds == 0)
return ((DateTime)value).ToString("yyyy-MM-dd");
return ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss");
}
string output = value.ToString();
if (output.Contains(",") || output.Contains("\""))
output = '"' + output.Replace("\"", "\"\"") + '"';
return output;
}
public string Export()
{
StringBuilder sb = new StringBuilder();
// if there is a title
if (!string.IsNullOrEmpty(addTitle))
{
// escape chars that would otherwise break the row / export
char[] csvTokens = new[] { '\"', ',', '\n', '\r' };
if (addTitle.IndexOfAny(csvTokens) >= 0)
{
addTitle = "\"" + addTitle.Replace("\"", "\"\"") + "\"";
}
sb.Append(addTitle).Append(",");
sb.AppendLine();
}
// The header
foreach (string field in fields)
sb.Append(field).Append(",");
sb.AppendLine();
// The rows
foreach (Dictionary<string, object> row in rows)
{
foreach (string field in fields)
sb.Append(MakeValueCsvFriendly(row[field])).Append(",");
sb.AppendLine();
}
return sb.ToString();
}
public void ExportToFile(string path)
{
File.WriteAllText(path, Export());
}
public byte[] ExportToBytes()
{
return Encoding.UTF8.GetBytes(Export());
}
}
<?php
$j=1;
?>
<script>
var i = "<?php echo $j; ?>";
//Do something
</script>
<?php
echo $j;
?>
This is the easiest way of passing a php variable to javascript without Ajax.
You can also use something like this:
var i = "<?php echo json_encode($j); ?>";
This said to be safer or more secure. i think
package com.copy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class CopyArray {
public static void main(String[] args) {
List<Integer> list1, list2 = null;
Integer[] intarr = { 3, 4, 2, 1 };
list1 = new ArrayList<Integer>(Arrays.asList(intarr));
list1.add(30);
list2 = Arrays.asList(intarr);
// list2.add(40); Here, we can't modify the existing list,because it's a wrapper
System.out.println("List1");
Iterator<Integer> itr1 = list1.iterator();
while (itr1.hasNext()) {
System.out.println(itr1.next());
}
System.out.println("List2");
Iterator<Integer> itr2 = list2.iterator();
while (itr2.hasNext()) {
System.out.println(itr2.next());
}
}
}
Hey i think The fastest way to handle that kind of operation is to memset() the memory.
Example-
memset(&myPage.pageArray[0][0], 0, sizeof(myPage.pageArray));
A similar C++ way would be to use std::fill
char *begin = myPage.pageArray[0][0];
char *end = begin + sizeof(myPage.pageArray);
std::fill(begin, end, 0);
My piece: nodejs is great for making real time systems like analytics, chat-apps, apis, ad servers, etc. Hell, I made my first chat app using nodejs and socket.io under 2 hours and that too during exam week!
Edit
Its been several years since I have started using nodejs and I have used it in making many different things including static file servers, simple analytics, chat apps and much more. This is my take on when to use nodejs
When to use
When making system which put emphasis on concurrency and speed.
When not to use
Its a very versatile webserver so you can use it wherever you want but probably not these places.
Keep in mind that I am just nitpicking. For static file servers, apache is better mainly because it is widely available. The nodejs community has grown larger and more mature over the years and it is safe to say nodejs can be used just about everywhere if you have your own choice of hosting.
Here are a couple of things to notice in order to understand the connected component's behavior in your code:
The Arity of connect
Matters: connect(mapStateToProps, mapDispatchToProps)
React-Redux calls connect
with the first argument mapStateToProps
, and second argument mapDispatchToProps
.
Therefore, although you've passed in your mapDispatchToProps
, React-Redux in fact treats that as mapState
because it is the first argument. You still get the injected onSubmit
function in your component because the return of mapState
is merged into your component's props. But that is not how mapDispatch
is supposed to be injected.
You may use mapDispatch
without defining mapState
. Pass in null
in place of mapState
and your component will not subject to store changes.
Connected Component Receives dispatch
by Default, When No mapDispatch
Is Provided
Also, your component receives dispatch
because it received null
for its second position for mapDispatch
. If you properly pass in mapDispatch
, your component will not receive dispatch
.
The above answers why the component behaved that way. Although, it is common practice that you simply pass in your action creator using mapStateToProps
's object shorthand. And call that within your component's onSubmit
That is:
import { setAddresses } from '../actions.js'
const Start = (props) => {
// ... omitted
return <div>
{/** omitted */}
<FlatButton
label='Does Not Work'
onClick={this.props.setAddresses({
pickup: this.refs.pickup.state.address,
dropoff: this.refs.dropoff.state.address
})}
/>
</div>
};
const mapStateToProps = { setAddresses };
export default connect(null, mapDispatchToProps)(Start)
To change the popover width you may override the template:
$('#name').popover({
template: '<div class="popover" role="tooltip" style="width: 500px;"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"><div class="data-content"></div></div></div>'
})
Something like this:
if($('#postageyes').is(':checked')) {
// do stuff
}
This Works
function saveBase64AsFile(base64, fileName) {
var link = document.createElement("a");
document.body.appendChild(link);
link.setAttribute("type", "hidden");
link.href = "data:text/plain;base64," + base64;
link.download = fileName;
link.click();
document.body.removeChild(link);
}
Based on the answer above but with some changes
You can use a standard ASP.NET Panel and then set it's visible property in your code behind.
<asp:Panel ID="Panel1" runat="server" visible="false" />
To show panel in codebehind:
Panel1.Visible = true;
background-image: url("/your-dir/your_image.jpg");
min-height: 100%;
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
background-size: cover;}
I didn't see anyone answer this correctly. So I'm posting it here. In order to get columns to show up you need to specify the following line.
lvRegAnimals.View = View.Details;
And then add your columns after that.
lvRegAnimals.Columns.Add("Id", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Name", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Age", -2, HorizontalAlignment.Left);
Hope this helps anyone else looking for this answer in the future.
Try this->
EditText text = (EditText) findViewById(R.id.text_input);
Editable name = text.getText();
Editable is the return data type of getText() method it will handle both string and integer values
This simple solution works natively and implements a smooth scroll to any position.
It avoids using anchor links (those with #
) that, in my opinion, are useful if you want to link to a section, but are not so comfortable in some situations, specially when pointing to top which could lead to two different URLs pointing to the same location (http://www.example.org and http://www.example.org/#).
Put an id to the tag you want to scroll to, for example your first section, which answers this question, but the id could be placed everywhere in the page.
<body>
<section id="top">
<!-- your content -->
</section>
<div id="another"><!-- more content --></div>
Then as a button you can use a link, just edit the onclick attribute with a code like this.
<a onclick="document.getElementById('top').scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest' })">Click me</a>
Where the argument of document.getElementById
is the id of the tag you want to scroll to after click.
official Link of DB 2 JDBC Driver from IBM