You cannot add methods to an existing type unless the existing type is marked as partial, you can only add methods that appear to be a member of the existing type through extension methods. Since this is the case you cannot add static methods to the type itself since extension methods use instances of that type.
There is nothing stopping you from creating your own static helper method like this:
static class DateTimeHelper
{
public static DateTime Tomorrow
{
get { return DateTime.Now.AddDays(1); }
}
}
Which you would use like this:
DateTime tomorrow = DateTimeHelper.Tomorrow;
What I would do is put a span inside the <a>
tag, set the span to block, and add size to the span, or just apply the styling to the <a>
tag. Definitely handle the positioning in the <a>
tag style. Add an onclick event
to the a where
JavaScript will catch the event, then return false at the end of the JavaScript event to prevent default action of the href
and bubbling of the click. This works in cases with or without JavaScript enabled, and any AJAX can be handled in the Javascript listener.
If you're using jQuery, you can use this as your listener and omit the onclick
in the a
tag.
$('#idofdiv').live("click", function(e) {
//add stuff here
e.preventDefault; //or use return false
});
this allows you to attach listeners to any changed elements as necessary.
You can do something like this:
// show loading image
$('#loader_img').show();
// main image loaded ?
$('#main_img').on('load', function(){
// hide/remove the loading image
$('#loader_img').hide();
});
You assign load
event to the image which fires when image has finished loading. Before that, you can show your loader image.
Indeed, the 9th byte indicates the check state of the button, but the answers above don't take into account the checkbox which enables manual configuration. This check state value is also present in this ninth byte. The real answer should thus be:
Byte value
00001001 = Manual proxy is checked
00000101 = Use automatic configuration script is checked
00000011 = Automatically detect settings is checked
When multiple checkboxes are checked, the value of the 9th byte is the result of the bitwise OR operation on the values for which the checkbox is checked.
XML Blueprint also does that; instructions here
http://www.xmlblueprint.com/help/html/topic_170.htm
It's not free, but there's a 10-day free trial; it seems fast and efficient; unfortunately it's Windows only.
You can try this method:
Get the total number of records in the collection with
db.dbcollection.count()
Then use skip:
db.dbcollection.find().skip(db.dbcollection.count() - 1).pretty()
TO FIND 1ST and Last day of the Previous, Current and Next Month in Oracle SQL
-----------------------------------------------------------------------------
SELECT
SYSDATE,
LAST_DAY(ADD_MONTHS(SYSDATE,-2))+1 FDPM,
LAST_DAY(ADD_MONTHS(SYSDATE,-1)) LDPM,
LAST_DAY(ADD_MONTHS(SYSDATE,-1))+1 FDCM,
LAST_DAY(SYSDATE)LDCM,
LAST_DAY(SYSDATE)+1 FDNM,
LAST_DAY(LAST_DAY(SYSDATE)+1) LDNM
FROM DUAL
I had the same problem with Visual Studio 2008 and solved adding the following event handler to the textbox:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar >= 'a') && (e.KeyChar <= 'z'))
{
int iPos = textBox1.SelectionStart;
int iLen = textBox1.SelectionLength;
textBox1.Text = textBox1.Text.Remove(iPos, iLen).Insert(iPos, Char.ToUpper(e.KeyChar).ToString());
textBox1.SelectionStart = iPos + 1;
e.Handled = true;
}
}
It works even if you type a lowercase character in a textbox where some characters are selected. I don't know if the code works with a Multiline textbox.
If you want something slightly more complex than a simple join you can use LINQ e.g.
var result = myList.Aggregate((total, part) => total + "(" + part.ToLower() + ")");
Will take ["A", "B", "C"] and produce "(a)(b)(c)"
via https://speakerdeck.com/anguscroll/es6-uncensored by Angus Croll
It turns out, we can use spread
operator:
var myArr = [...mySet];
Or, alternatively, use Array.from
:
var myArr = Array.from(mySet);
If question i.e.
$a = [
[
"_id" => "5a96933414d48831a41901f2",
"discount_amount" => 3.29,
"discount_id" => "5a92656a14d488570c2c44a2",
],
[
"_id" => "5a9790fd14d48879cf16a9e8",
"discount_amount" => 4.53,
"discount_id" => "5a9265b914d488548513b122",
],
[
"_id" => "5a98083614d488191304b6c3",
"discount_amount" => 15.24,
"discount_id" => "5a92806a14d48858ff5c2ec3",
],
[
"_id" => "5a982a4914d48824721eafe3",
"discount_amount" => 45.74,
"discount_id" => "5a928ce414d488609e73b443",
],
[
"_id" => "5a982a4914d48824721eafe55",
"discount_amount" => 10.26,
"discount_id" => "5a928ce414d488609e73b443",
],
];
Ans:
function searchForId($id, $array) {
$did=0;
$dia=0;
foreach ($array as $key => $val) {
if ($val['discount_id'] === $id) {
$dia +=$val['discount_amount'];
$did++;
}
}
if($dia != '') {
echo $dia;
var_dump($did);
}
return null;
};
print_r(searchForId('5a928ce414d488609e73b443',$a));
CREATE FUNCTION ActionState_Preassigned()
RETURNS tinyint
AS
BEGIN
RETURN 0
END
GO
CREATE FUNCTION ActionState_Unassigned()
RETURNS tinyint
AS
BEGIN
RETURN 1
END
-- etc...
Where performance matters, still use the hard values.
protected void FindCsv()
{
string strToFind = "2";
importFolder = @"C:\Documents and Settings\gmendez\Desktop\";
fileName = "CSVFile.csv";
connectionString= @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq="+importFolder+";Extended Properties=Text;HDR=No;FMT=Delimited";
conn = new OdbcConnection(connectionString);
System.Data.Odbc.OdbcDataAdapter da = new OdbcDataAdapter("select * from [" + fileName + "]", conn);
DataTable dt = new DataTable();
da.Fill(dt);
dt.Columns[0].ColumnName = "id";
DataRow[] dr = dt.Select("id=" + strToFind);
Response.Write(dr[0][0].ToString() + dr[0][1].ToString() + dr[0][2].ToString() + dr[0][3].ToString() + dr[0][4].ToString() + dr[0][5].ToString());
}
button {
width:1000px;
}
or even
button {
width:1000px !important
}
If thats what you mean
We had an issue relating to duplicated data in our database, with a date field having multiple values where we were meant to have 1. I thought I'd add the way we resolved the issue for reference.
We have a collection called "data" with a numeric "value" field and a date "date" field. We had a process which we thought was idempotent, but ended up adding 2 x values per day on second run:
{ "_id" : "1", "type":"x", "value":1.23, date : ISODate("2013-05-21T08:00:00Z")}
{ "_id" : "2", "type":"x", "value":1.23, date : ISODate("2013-05-21T17:00:00Z")}
We only need 1 of the 2 records, so had to resort the javascript to clean up the db. Our initial approach was going to be to iterate through the results and remove any field with a time of between 6am and 11am (all duplicates were in the morning), but during implementation, made a change. Here's the script used to fix it:
var data = db.data.find({"type" : "x"})
var found = [];
while (data.hasNext()){
var datum = data.next();
var rdate = datum.date;
// instead of the next set of conditions, we could have just used rdate.getHour() and checked if it was in the morning, but this approach was slightly better...
if (typeof found[rdate.getDate()+"-"+rdate.getMonth() + "-" + rdate.getFullYear()] !== "undefined") {
if (datum.value != found[rdate.getDate()+"-"+rdate.getMonth() + "-" + rdate.getFullYear()]) {
print("DISCREPENCY!!!: " + datum._id + " for date " + datum.date);
}
else {
print("Removing " + datum._id);
db.data.remove({ "_id": datum._id});
}
}
else {
found[rdate.getDate()+"-"+rdate.getMonth() + "-" + rdate.getFullYear()] = datum.value;
}
}
and then ran it with mongo thedatabase fixer_script.js
What follows from the code and code docs is that coalesce(n)
is the same as coalesce(n, shuffle = false)
and repartition(n)
is the same as coalesce(n, shuffle = true)
Thus, both coalesce
and repartition
can be used to increase number of partitions
With
shuffle = true
, you can actually coalesce to a larger number of partitions. This is useful if you have a small number of partitions, say 100, potentially with a few partitions being abnormally large.
Another important note to accentuate is that if you drastically decrease number of partitions you should consider using shuffled version of coalesce
(same as repartition
in that case). This will allow your computations be performed in parallel on parent partitions (multiple task).
However, if you're doing a drastic coalesce, e.g. to
numPartitions = 1
, this may result in your computation taking place on fewer nodes than you like (e.g. one node in the case ofnumPartitions = 1
). To avoid this, you can passshuffle = true
. This will add a shuffle step, but means the current upstream partitions will be executed in parallel (per whatever the current partitioning is).
Please also refer to the related answer here
As suggested by @[Tomasz Zielinski] and @Williams python-dateutil can do it just 5 lines.
from dateutil.relativedelta import *
from datetime import date
today = date.today()
dob = date(1982, 7, 5)
age = relativedelta(today, dob)
>>relativedelta(years=+33, months=+11, days=+16)`
again this is JS :) this still works ....
var linkToClick = document.getElementById('something');
linkToClick.click();
<Link id="something" to={/somewhaere}> the link </Link>
Yes there is.
try
{
//Read/write file
}catch(Exception ex)
{
//catches all exceptions extended from Exception (which is everything)
}
While using Column, use this inside the column widget :
mainAxisAlignment: MainAxisAlignment.center
It align its children(s) to the center of its parent Space is its main axis i.e. vertically
or, wrap the column with a Center widget:
Center(
child: Column(
children: <ListOfWidgets>,
),
)
if it doesn't resolve the issue wrap the parent container with a Expanded widget..
Expanded(
child:Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: children,
),
),
)
Let's say you have a button with the text, "Click Me". What width should that button be?
First, you definitely don't want the button to be smaller than the text. Otherwise, the text would be clipped. This is the horizontal compression resistance priority.
Second, you don't want the button to be bigger than it needs to be. A button that looked like this, [ Click Me ], is obviously too big. You want the button to "hug" its contents without too much padding. This is the horizontal content hugging priority. For a button, it isn't as strong as the horizontal compression resistance priority.
$('#' + id).is(":checked")
That gets if the checkbox is checked.
For an array of checkboxes with the same name you can get the list of checked ones by:
var $boxes = $('input[name=thename]:checked');
Then to loop through them and see what's checked you can do:
$boxes.each(function(){
// Do stuff here with this
});
To find how many are checked you can do:
$boxes.length;
Also, if you are using more than one project and don't want to set global project every time, you can use select project flag.
For example: to connect a virtual machine, named my_vm
under a project named my_project
in Google Cloud Platform:
gcloud --project my_project compute ssh my_vm
This way, you can work with multiple project and change between them easily by just putting project flag. You can find much more information about other GCP flags from here.
There are plenty available. Try using Modal windows of Jquery or DHTML would do good. Put the content in your div or Change your content in div dynamically and show it to the user. It won't be a popup but a modal window.
Jquery's Thickbox would clear your problem.
Generally speaking, for boolean
or bit
data types, you would use 0
or 1
like so:
UPDATE tbl SET bitCol = 1 WHERE bitCol = 0
See also:
This is very often a symptom of an antipattern. The tool which produced the line numbers may well be replaced with one which deletes the lines right away. For example;
grep -nh error logfile | cut -d: -f1 | deletelines logfile
(where deletelines
is the utility you are imagining you need) is the same as
grep -v error logfile
Having said that, if you are in a situation where you genuinely need to perform this task, you can generate a simple sed
script from the file of line numbers. Humorously (but perhaps slightly confusingly) you can do this with sed
.
sed 's%$%d%' linenumbers
This accepts a file of line numbers, one per line, and produces, on standard output, the same line numbers with d
appended after each. This is a valid sed
script, which we can save to a file, or (on some platforms) pipe to another sed
instance:
sed 's%$%d%' linenumbers | sed -f - logfile
On some platforms, sed -f
does not understand the option argument -
to mean standard input, so you have to redirect the script to a temporary file, and clean it up when you are done, or maybe replace the lone dash with /dev/stdin
or /proc/$pid/fd/1
if your OS (or shell) has that.
As always, you can add -i
before the -f
option to have sed
edit the target file in place, instead of producing the result on standard output. On *BSDish platforms (including OSX) you need to supply an explicit argument to -i
as well; a common idiom is to supply an empty argument; -i ''
.
Another way based on amadan:
SELECT * FROM [Purchasing].[Vendor] WHERE
( (@url IS null OR @url = '' OR @url = 'ALL') and PurchasingWebServiceURL LIKE '%')
or
( @url = 'blank' and PurchasingWebServiceURL = '')
or
(@url = 'fail' and PurchasingWebServiceURL NOT LIKE '%treyresearch%')
or( (@url not in ('fail','blank','','ALL') and @url is not null and
PurchasingWebServiceUrl Like '%'+@ur+'%')
END
If you are using babel, you should check out babel-plugin-lodash, it will cherry-pick the parts of lodash you are using for you, less hassle and a smaller bundle.
It has a few limitations:
Here is an example using PREPARE statements. You still can't use ?
, but you can use $n
notation:
PREPARE foo(integer) AS
SELECT *
FROM somewhere
WHERE something = $1;
EXECUTE foo(5);
DEALLOCATE foo;
Only use WOFF2, or if you need legacy support, WOFF. Do not use any other format
(svg
and eot
are dead formats, ttf
and otf
are full system fonts, and should not be used for web purposes)
In short, font-face is very old, but only recently has been supported by more than IE.
eot
is needed for Internet Explorers that are older than IE9 - they invented the spec, but eot was a proprietary solution.
ttf
and otf
are normal old fonts, so some people got annoyed that this meant anyone could download expensive-to-license fonts for free.
Time passes, SVG 1.1 adds a "fonts" chapter that explains how to model a font purely using SVG markup, and people start to use it. More time passes and it turns out that they are absolutely terrible compared to just a normal font format, and SVG 2 wisely removes the entire chapter again.
Then, woff
gets invented by people with quite a bit of domain knowledge, which makes it possible to host fonts in a way that throws away bits that are critically important for system installation, but irrelevant for the web (making people worried about piracy happy) and allows for internal compression to better suit the needs of the web (making users and hosts happy). This becomes the preferred format.
2019 edit A few years later, woff2
gets drafted and accepted, which improves the compression, leading to even smaller files, along with the ability to load a single font "in parts" so that a font that supports 20 scripts can be stored as "chunks" on disk instead, with browsers automatically able to load the font "in parts" as needed, rather than needing to transfer the entire font up front, further improving the typesetting experience.
If you don't want to support IE 8 and lower, and iOS 4 and lower, and android 4.3 or earlier, then you can just use WOFF (and WOFF2, a more highly compressed WOFF, for the newest browsers that support it.)
@font-face {
font-family: 'MyWebFont';
src: url('myfont.woff2') format('woff2'),
url('myfont.woff') format('woff');
}
Support for woff
can be checked at http://caniuse.com/woff
Support for woff2
can be checked at http://caniuse.com/woff2
wr.writerow(item) #column by column
wr.writerows(item) #row by row
This is quite simple if your goal is just to write the output column by column.
If your item is a list:
yourList = []
with open('yourNewFileName.csv', 'w', ) as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
for word in yourList:
wr.writerow([word])
I used (the suggested answer from above)
sudo apt-get install eclipse eclipse-cdt g++
but ONLY after then also doing
sudo eclipse -clean
Hope that also helps.
In the initialization use:
"fnServerData": function ( sSource, aoData, fnCallback ) {
//* Add some extra data to the sender *
newData = aoData;
newData.push({ "name": "key", "value": $('#value').val() });
$.getJSON( sSource, newData, function (json) {
//* Do whatever additional processing you want on the callback, then tell DataTables *
fnCallback(json);
} );
},
And then just use:
$("#table_id").dataTable().fnDraw();
The important thing in the fnServerData is:
newData = aoData;
newData.push({ "name": "key", "value": $('#value').val() });
if you push directly to aoData, the change is permanent the first time you draw the table and fnDraw don't work the way you want.
Depending on the hibernate flush mode that you are using (AUTO
is the default) save
may or may not write your changes to the DB straight away. When you call saveAndFlush
you are enforcing the synchronization of your model state with the DB.
If you use flush mode AUTO and you are using your application to first save and then select the data again, you will not see a difference in bahvior between save()
and saveAndFlush()
because the select triggers a flush first. See the documention.
you can simply make it transparent
{
width: 20px;
height: 20px;
overflow: hidden;
color:transparent;
}
Yes you can also do:
switch (true) {
case (var1 === true && var2 === true) :
//do something
break;
case (var1 === false && var2 === false) :
//do something
break;
default:
}
This will always execute the switch, pretty much just like if/else but looks cleaner. Just continue checking your variables in the case expressions.
If we have:
enum Gender
{
M = 0,
F = 1,
U = 2
}
and
enum Gender2
{
Male = 0,
Female = 1,
Unknown = 2
}
We can safely do
var gender = Gender.M;
var gender2 = (Gender2)(int)gender;
Or even
var enumOfGender2Type = (Gender2)0;
If you want to cover the case where an enum on the right side of the '=' sign has more values than the enum on the left side - you will have to write your own method/dictionary to cover that as others suggested.
Working with a dictionary ->level2 above comes from a dictionary in my case (just in case anybody will find it useful) Trying the first example I stumbled over this error: "This document already has a 'DocumentElement' node." I was inspired by the answer here
and edited my code: (xmlDoc.DocumentElement.AppendChild(body))
//a dictionary:
Dictionary<string, string> Level2Data
{
{"level2", "text"},
{"level2", "other text"},
{"same_level2", "more text"}
}
//xml Decalration:
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = xmlDoc.DocumentElement;
xmlDoc.InsertBefore(xmlDeclaration, root);
// add body
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.AppendChild(body);
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.DocumentElement.AppendChild(body); //without DocumentElement ->ERR
foreach (KeyValuePair<string, string> entry in Level2Data)
{
//write to xml: - it works version 1.
XmlNode keyNode = xmlDoc.CreateElement(entry.Key); //open TAB
keyNode.InnerText = entry.Value;
body.AppendChild(keyNode); //close TAB
//Write to xmml verdion 2: (uncomment the next 4 lines and comment the above 3 - version 1
//XmlElement key = xmlDoc.CreateElement(string.Empty, entry.Key, string.Empty);
//XmlText value = xmlDoc.CreateTextNode(entry.Value);
//key.AppendChild(value);
//body.AppendChild(key);
}
Both versions (1 and 2 inside foreach loop) give the output:
<?xml version="1.0" encoding="UTF-8"?>
<body>
<level1>
<level2>text</level2>
<level2>ther text</level2>
<same_level2>more text</same_level2>
</level1>
</body>
(Note: third line "same level2" in dictionary can be also level2 as the others but I wanted to ilustrate the advantage of the dictionary - in my case I needed level2 with different names.
While map
is a proper solution to select 'columns' from a list of objects, it has a downside. If not explicitly checked whether or not the columns exists, it'll throw an error and (at best) provide you with undefined
.
I'd opt for a reduce
solution, which can simply ignore the property or even set you up with a default value.
function getFields(list, field) {
// reduce the provided list to an array only containing the requested field
return list.reduce(function(carry, item) {
// check if the item is actually an object and does contain the field
if (typeof item === 'object' && field in item) {
carry.push(item[field]);
}
// return the 'carry' (which is the list of matched field values)
return carry;
}, []);
}
This would work even if one of the items in the provided list is not an object or does not contain the field.
It can even be made more flexible by negotiating a default value should an item not be an object or not contain the field.
function getFields(list, field, otherwise) {
// reduce the provided list to an array containing either the requested field or the alternative value
return list.reduce(function(carry, item) {
// If item is an object and contains the field, add its value and the value of otherwise if not
carry.push(typeof item === 'object' && field in item ? item[field] : otherwise);
// return the 'carry' (which is the list of matched field values)
return carry;
}, []);
}
This would be the same with map, as the length of the returned array would be the same as the provided array. (In which case a map
is slightly cheaper than a reduce
):
function getFields(list, field, otherwise) {
// map the provided list to an array containing either the requested field or the alternative value
return list.map(function(item) {
// If item is an object and contains the field, add its value and the value of otherwise if not
return typeof item === 'object' && field in item ? item[field] : otherwise;
}, []);
}
And then there is the most flexible solution, one which lets you switch between both behaviours simply by providing an alternative value.
function getFields(list, field, otherwise) {
// determine once whether or not to use the 'otherwise'
var alt = typeof otherwise !== 'undefined';
// reduce the provided list to an array only containing the requested field
return list.reduce(function(carry, item) {
// If item is an object and contains the field, add its value and the value of 'otherwise' if it was provided
if (typeof item === 'object' && field in item) {
carry.push(item[field]);
}
else if (alt) {
carry.push(otherwise);
}
// return the 'carry' (which is the list of matched field values)
return carry;
}, []);
}
As the examples above (hopefully) shed some light on the way this works, lets shorten the function a bit by utilising the Array.concat
function.
function getFields(list, field, otherwise) {
var alt = typeof otherwise !== 'undefined';
return list.reduce(function(carry, item) {
return carry.concat(typeof item === 'object' && field in item ? item[field] : (alt ? otherwise : []));
}, []);
}
numba
module for speed up.On big datasets (500k >
) pd.cut
can be quite slow for binning data.
I wrote my own function in numba
with just in time compilation, which is roughly 16x
faster:
from numba import njit
@njit
def cut(arr):
bins = np.empty(arr.shape[0])
for idx, x in enumerate(arr):
if (x >= 0) & (x < 1):
bins[idx] = 1
elif (x >= 1) & (x < 5):
bins[idx] = 2
elif (x >= 5) & (x < 10):
bins[idx] = 3
elif (x >= 10) & (x < 25):
bins[idx] = 4
elif (x >= 25) & (x < 50):
bins[idx] = 5
elif (x >= 50) & (x < 100):
bins[idx] = 6
else:
bins[idx] = 7
return bins
cut(df['percentage'].to_numpy())
# array([5., 5., 7., 5.])
Optional: you can also map it to bins as strings:
a = cut(df['percentage'].to_numpy())
conversion_dict = {1: 'bin1',
2: 'bin2',
3: 'bin3',
4: 'bin4',
5: 'bin5',
6: 'bin6',
7: 'bin7'}
bins = list(map(conversion_dict.get, a))
# ['bin5', 'bin5', 'bin7', 'bin5']
Speed comparison:
# create dataframe of 8 million rows for testing
dfbig = pd.concat([df]*2000000, ignore_index=True)
dfbig.shape
# (8000000, 1)
%%timeit
cut(dfbig['percentage'].to_numpy())
# 38 ms ± 616 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit
bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
pd.cut(dfbig['percentage'], bins=bins, labels=labels)
# 215 ms ± 9.76 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
Another way is to use a transparent 1x1.png with width: 100%
, height: auto
in a div
and absolutely positioned content within it:
html:
<div>
<img src="1x1px.png">
<h1>FOO</h1>
</div>
css:
div {
position: relative;
width: 50%;
}
img {
width: 100%;
height: auto;
}
h1 {
position: absolute;
top: 10px;
left: 10px;
}
Use PREPARE
/EXECUTE
and querying the schema.
The host doesn't need to have permission to create or run procedures :
SET @dbname = DATABASE();
SET @tablename = "tableName";
SET @columnname = "colName";
SET @preparedStatement = (SELECT IF(
(
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE
(table_name = @tablename)
AND (table_schema = @dbname)
AND (column_name = @columnname)
) > 0,
"SELECT 1",
CONCAT("ALTER TABLE ", @tablename, " ADD ", @columnname, " INT(11);")
));
PREPARE alterIfNotExists FROM @preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;
Both files define variable k
as an integer (int
).
As a result, the linker sees two variables with the same name, and is unsure which one it should use if you ever refer to k
.
To fix this, change one of the declarations to:
extern int k;
That means: "k is an integer, declared here, but defined externally (ie. the other file)."
Now there is only one variable k
, that can be properly referred to by two different files.
The scope <scope>provided</scope>
gives you an opportunity to tell that the jar would be available at runtime, so do not bundle it. It does not mean that you do not need it at compile time, hence maven would try to download that.
Now I think, the below maven artifact do not exist at all. I tries searching google, but not able to find. Hence you are getting this issue.
Change groupId
to <groupId>net.sourceforge.ant4x</groupId>
to get the latest jar.
<dependency>
<groupId>net.sourceforge.ant4x</groupId>
<artifactId>ant4x</artifactId>
<version>${net.sourceforge.ant4x-version}</version>
<scope>provided</scope>
</dependency>
Another solution for this problem is:
Where http://localhost/repo is your local repo URL:
<repositories>
<repository>
<id>wmc-central</id>
<url>http://localhost/repo</url>
</repository>
<-- Other repository config ... -->
</repositories>
Nothing worked for me except, I loggined using pgAdmin4 and on the Dashboard I disconnected all connections except pgAdmin4 and then was able to rename by right lick on the database and properties and typed new name.
Actually, a third is preferred:
ArrayList<Object> array = new ArrayList<Object>();
array.add(Integer.valueOf(3));
array.add("ss");
This avoids autoboxing (Integer.valueOf(3)
versus 3
) and doesn't create an unnecessary String object.
Eclipse complains when you don't use type arguments with a generic type like ArrayList, because you are using something called a raw type, which is discouraged. If a class is generic (that is, it has type parameters), then you should always use type arguments with that class.
Autoboxing, on the other hand, is a personal preference. Some people are okay with it, and some not. I don't like it, and I turn on the warning for autoboxing/autounboxing.
You could simply do df.withColumn("date", date_format(col("string"),"yyyy-MM-dd HH:mm:ss.ssssss")).show()
Yes, you can input multiple items from cin
, using exactly the syntax you describe. The result is essentially identical to:
cin >> a;
cin >> b;
cin >> c;
This is due to a technique called "operator chaining".
Each call to operator>>(istream&, T)
(where T
is some arbitrary type) returns a reference to its first argument. So cin >> a
returns cin
, which can be used as (cin>>a)>>b
and so forth.
Note that each call to operator>>(istream&, T)
first consumes all whitespace characters, then as many characters as is required to satisfy the input operation, up to (but not including) the first next whitespace character, invalid character, or EOF.
getClass().getResourcesAsStream()
works fine on Android. Just make sure the file you are trying to open is correctly embedded in your APK (open the APK as ZIP).
Normally on Android you put such files in the assets
directory. So if you put the raw_resources.dat
in the assets
subdirectory of your project, it will end up in the assets
directory in the APK and you can use:
getClass().getResourcesAsStream("/assets/raw_resources.dat");
It is also possible to customize the build process so that the file doesn't land in the assets
directory in the APK.
Create a folder where you want to keep the code, and right click on it. Choose SVN Checkout... and type http://wittytwitter.googlecode.com/svn/trunk into the URL of repository field.
You can also run
svn checkout http://wittytwitter.googlecode.com/svn/trunk
from the command line in the folder you want to keep it (svn.exe has to be in your path, of course).
Yes, you must call __init__
for each parent class. The same goes for functions, if you are overriding a function that exists in both parents.
why not use date() just like below,try this
$t = strtotime('20130409163705');
echo date('d/m/y H:i:s',$t);
and will be output
09/04/13 16:37:05
Python 3.4 introduced the pathlib
module into the standard library, which provides an object oriented approach to handle filesystem paths:
from pathlib import Path
p = Path('./')
[f for f in p.iterdir() if f.is_dir()]
?legend
will tell you:
Arguments
x
, y
the x
and y
co-ordinates to be used to position the legend. They can be specified by keyword or in any way which is accepted by xy.coords
: See ‘Details’.
Details:
Arguments x
, y
, legend are interpreted in a non-standard way to allow the coordinates to be specified via one or two arguments. If legend is missing and y
is not numeric, it is assumed that the second argument is intended to be legend and that the first argument specifies the coordinates.
The coordinates can be specified in any way which is accepted by xy.coords
. If this gives the coordinates of one point, it is used as the top-left coordinate of the rectangle containing the legend. If it gives the coordinates of two points, these specify opposite corners of the rectangle (either pair of corners, in any order).
The location may also be specified by setting x
to a single keyword from the list bottomright
, bottom
, bottomleft
, left
, topleft
, top
, topright
, right
and center
. This places the legend on the inside of the plot frame at the given location. Partial argument matching is used. The optional inset argument specifies how far the legend is inset from the plot margins. If a single value is given, it is used for both margins; if two values are given, the first is used for x- distance, the second for y-distance.
You can use placeholders and feed_dict.
Suppose we have numpy arrays like these:
trX = np.linspace(-1, 1, 101)
trY = 2 * trX + np.random.randn(*trX.shape) * 0.33
You can declare two placeholders:
X = tf.placeholder("float")
Y = tf.placeholder("float")
Then, use these placeholders (X, and Y) in your model, cost, etc.: model = tf.mul(X, w) ... Y ... ...
Finally, when you run the model/cost, feed the numpy arrays using feed_dict:
with tf.Session() as sess:
....
sess.run(model, feed_dict={X: trY, Y: trY})
Here's one approach. Using a combination of the answers above do the following:
As a formula, just use the example below with <> replaced with your range reference.
=SUM(IF(ISERROR(DATEVALUE(TEXT(<<RANGE HERE>>, "MM/dd/yyyy"))), 0, 1))
You must enter this as an array formula with CTRL + SHIFT + ENTER.
Another approach you can take if you need to back up a single table out of multiple tables in a database is:
Generate script of specific table(s) from a database (Right-click database, click Task > Generate Scripts...
Run the script in the query editor. You must change/add the first line (USE DatabaseName) in the script to a new database, to avoid getting the "Database already exists" error.
Right-click on the newly created database, and click on Task > Back Up... The backup will contain the selected table(s) from the original database.
What Dragan B suggested is right way to go for Bootstrap 4. I have put one example below. e.g. mr-3 is margin-right:1rem!important
<div class="btn-toolbar pull-right">
<button type="button" class="btn mr-3">btn1</button>
<button type="button" class="btn mr-3">btn2</button>
<button type="button" class="btn">btn3</button>
</div>
p.s: in my case I wanted my buttons to be displayed to the right of the screen and hence pull-right.
With Bootstrap 3, you can use the 'text-center' styling attribute.
<div class="col-md-3 text-center">
<button id="button" name="button" class="btn btn-primary">Press Me!</button>
</div>
First drop
your foreign key and try your above command, put add constraint
instead of modify constraint
.
Now this is the command:
ALTER TABLE child_table_name
ADD CONSTRAINT fk_name
FOREIGN KEY (child_column_name)
REFERENCES parent_table_name(parent_column_name)
ON DELETE CASCADE;
I had a similar problem that I am facing where I need to store live candlesticks from an event source limited to x items. I could have them stored in an object where the timestamp of each candle would act as the key and the candle itself would act as the value. Another possibility was that I could store it in an array where each item was the candle itself. One problem about live candles is that they keep sending updates on the same timestamp where the latest update holds the most recent data therefore you either update an existing item or add a new one. So here is a nice benchmark that attempts to combine all 3 possibilities. Arrays in the solution below are atleast 4x faster on average. Feel free to play
"use strict";
const EventEmitter = require("events");
let candleEmitter = new EventEmitter();
//Change this to set how fast the setInterval should run
const frequency = 1;
setInterval(() => {
// Take the current timestamp and round it down to the nearest second
let time = Math.floor(Date.now() / 1000) * 1000;
let open = Math.random();
let high = Math.random();
let low = Math.random();
let close = Math.random();
let baseVolume = Math.random();
let quoteVolume = Math.random();
//Clear the console everytime before printing fresh values
console.clear()
candleEmitter.emit("candle", {
symbol: "ABC:DEF",
time: time,
open: open,
high: high,
low: low,
close: close,
baseVolume: baseVolume,
quoteVolume: quoteVolume
});
}, frequency)
// Test 1 would involve storing the candle in an object
candleEmitter.on('candle', storeAsObject)
// Test 2 would involve storing the candle in an array
candleEmitter.on('candle', storeAsArray)
//Container for the object version of candles
let objectOhlc = {}
//Container for the array version of candles
let arrayOhlc = {}
//Store a max 30 candles and delete older ones
let limit = 30
function storeAsObject(candle) {
//measure the start time in nanoseconds
const hrtime1 = process.hrtime()
const start = hrtime1[0] * 1e9 + hrtime1[1]
const { symbol, time } = candle;
// Create the object structure to store the current symbol
if (typeof objectOhlc[symbol] === 'undefined') objectOhlc[symbol] = {}
// The timestamp of the latest candle is used as key with the pair to store this symbol
objectOhlc[symbol][time] = candle;
// Remove entries if we exceed the limit
const keys = Object.keys(objectOhlc[symbol]);
if (keys.length > limit) {
for (let i = 0; i < (keys.length - limit); i++) {
delete objectOhlc[symbol][keys[i]];
}
}
//measure the end time in nano seocnds
const hrtime2 = process.hrtime()
const end = hrtime2[0] * 1e9 + hrtime2[1]
console.log("Storing as objects", end - start, Object.keys(objectOhlc[symbol]).length)
}
function storeAsArray(candle) {
//measure the start time in nanoseconds
const hrtime1 = process.hrtime()
const start = hrtime1[0] * 1e9 + hrtime1[1]
const { symbol, time } = candle;
if (typeof arrayOhlc[symbol] === 'undefined') arrayOhlc[symbol] = []
//Get the bunch of candles currently stored
const candles = arrayOhlc[symbol];
//Get the last candle if available
const lastCandle = candles[candles.length - 1] || {};
// Add a new entry for the newly arrived candle if it has a different timestamp from the latest one we storeds
if (time !== lastCandle.time) {
candles.push(candle);
}
//If our newly arrived candle has the same timestamp as the last stored candle, update the last stored candle
else {
candles[candles.length - 1] = candle
}
if (candles.length > limit) {
candles.splice(0, candles.length - limit);
}
//measure the end time in nano seocnds
const hrtime2 = process.hrtime()
const end = hrtime2[0] * 1e9 + hrtime2[1]
console.log("Storing as array", end - start, arrayOhlc[symbol].length)
}
Conclusion 10 is the limit here
Storing as objects 4183 nanoseconds 10
Storing as array 373 nanoseconds 10
add dependency for retrofit2
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
create class for base url
public class ApiClient
{
public static final String BASE_URL = "base_url";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
after that create class model to get value
public class ApprovalModel {
@SerializedName("key_parameter")
private String approvalName;
public String getApprovalName() {
return approvalName;
}
}
create interface class
public interface ApiInterface {
@GET("append_url")
Call<CompanyDetailsResponse> getCompanyDetails();
}
after that in main class
if(Connectivity.isConnected(mContext)){
final ProgressDialog mProgressDialog = new ProgressDialog(mContext);
mProgressDialog.setIndeterminate(true);
mProgressDialog.setMessage("Loading...");
mProgressDialog.show();
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<CompanyDetailsResponse> call = apiService.getCompanyDetails();
call.enqueue(new Callback<CompanyDetailsResponse>() {
@Override
public void onResponse(Call<CompanyDetailsResponse>call, Response<CompanyDetailsResponse> response) {
mProgressDialog.dismiss();
if(response!=null && response.isSuccessful()) {
List<CompanyDetails> companyList = response.body().getCompanyDetailsList();
if (companyList != null&&companyList.size()>0) {
for (int i = 0; i < companyList.size(); i++) {
Log.d(TAG, "" + companyList.get(i));
}
//get values
}else{
//show alert not get value
}
}else{
//show error message
}
}
@Override
public void onFailure(Call<CompanyDetailsResponse>call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
mProgressDialog.dismiss();
}
});
}else{
//network error alert box
}
Flexbox can do this with just two css rules on a surrounding div.
.social-media{_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
}
_x000D_
<div class="social-media">_x000D_
<a href="mailto:[email protected]">_x000D_
<img class="fblogo" border="0" alt="Mail" src="http://olympiahaacht.be/wp-content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/></a>_x000D_
<a href="https://www.facebook.com/OlympiaHaacht" target="_blank">_x000D_
<img class="fblogo" border="0" alt="Facebook" src="http://olympiahaacht.be/wp-content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/></a>_x000D_
</div>
_x000D_
Process text to and from Unicode at the I/O boundaries of your program using open
with the encoding
parameter. Make sure to use the (hopefully documented) encoding of the file being read. The default encoding varies by OS (specifically, locale.getpreferredencoding(False)
is the encoding used), so I recommend always explicitly using the encoding
parameter for portability and clarity (Python 3 syntax below):
with open(filename, 'r', encoding='utf8') as f:
text = f.read()
# process Unicode text
with open(filename, 'w', encoding='utf8') as f:
f.write(text)
If still using Python 2 or for Python 2/3 compatibility, the io
module implements open
with the same semantics as Python 3's open
and exists in both versions:
import io
with io.open(filename, 'r', encoding='utf8') as f:
text = f.read()
# process Unicode text
with io.open(filename, 'w', encoding='utf8') as f:
f.write(text)
POD_HOST=$(kubectl get pod $POD_NAME --template={{.status.podIP}})
This command will return you an IP
for ($s=65; $s<=90; $s++) {
//echo chr($s);
$objPHPExcel->getActiveSheet()->getColumnDimension(chr($s))->setAutoSize(true);
}
if you are using .bind(this), try this:
let index = Array.from(evt.target.parentElement.children).indexOf(evt.target);
$(this.pagination).find("a").on('click', function(evt) {
let index = Array.from(evt.target.parentElement.children).indexOf(evt.target);
this.goTo(index);
}.bind(this))
S.Lott inserted a comment, but it should be an answer: see the same question.
Since it wasn't as obvious as I intended it to be, here follows a verbatim copy of S.Lott's answer in the other question:
I'm a big fan of ARGO UML from Tigris.org. Draws nice pictures using standard UML notation. It does some code generation, but mostly Java classes, which isn't SQL DDL, so that may not be close enough to what you want to do.
You can look at the Data Modelling Tools list and see if anything there is better than Argo UML. Many of the items on this list are free or cheap.
Also, if you're using Eclipse or NetBeans, there are many design plug-ins, some of which may have the features you're looking for.
This code is better.
public static byte[] getByteArrayFromImageView(ImageView imageView)
{
BitmapDrawable bitmapDrawable = ((BitmapDrawable) imageView.getDrawable());
Bitmap bitmap;
if(bitmapDrawable==null){
imageView.buildDrawingCache();
bitmap = imageView.getDrawingCache();
imageView.buildDrawingCache(false);
}else
{
bitmap = bitmapDrawable .getBitmap();
}
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
return stream.toByteArray();
}
I've found this issue to be prevalent in Entity Framework when we instantiate an Entity manually rather than through DBContext which will resolve all the Navigation Properties. If there are Foreign Key references (Navigation Properties) between tables and you use those references in your lambda (e.g. ProductDetail.Products.ID) then that "Products" context remains null if you manually created the Entity.
Remove the directory (basically a copy of https://stackoverflow.com/a/38201611/1695680), Ansible does this operation with rmtree
under the hood.
- name: remove files and directories
file:
state: "{{ item }}"
path: "/srv/deleteme/"
owner: 1000 # set your owner, group, and mode accordingly
group: 1000
mode: '0777'
with_items:
- absent
- directory
If you don't have the luxury of removing the whole directory and recreating it, you can scan it for files, (and directories), and delete them one by one. Which will take a while. You probably want to make sure you have [ssh_connection]\npipelining = True
in your ansible.cfg on.
- block:
- name: 'collect files'
find:
paths: "/srv/deleteme/"
hidden: True
recurse: True
# file_type: any # Added in ansible 2.3
register: collected_files
- name: 'collect directories'
find:
paths: "/srv/deleteme/"
hidden: True
recurse: True
file_type: directory
register: collected_directories
- name: remove collected files and directories
file:
path: "{{ item.path }}"
state: absent
with_items: >
{{
collected_files.files
+ collected_directories.files
}}
Since you don't care, I chose the max ID for each number.
select tbl.* from tbl
inner join (
select max(id) as maxID, number from tbl group by number) maxID
on maxID.maxID = tbl.id
Query Explanation
select
tbl.* -- give me all the data from the base table (tbl)
from
tbl
inner join ( -- only return rows in tbl which match this subquery
select
max(id) as maxID -- MAX (ie distinct) ID per GROUP BY below
from
tbl
group by
NUMBER -- how to group rows for the MAX aggregation
) maxID
on maxID.maxID = tbl.id -- join condition ie only return rows in tbl
-- whose ID is also a MAX ID for a given NUMBER
A simple client-side pagination example where data is fetched only once at page loading.
// dummy data_x000D_
const myarr = [{ "req_no": 1, "title": "test1" },_x000D_
{ "req_no": 2, "title": "test2" },_x000D_
{ "req_no": 3, "title": "test3" },_x000D_
{ "req_no": 4, "title": "test4" },_x000D_
{ "req_no": 5, "title": "test5" },_x000D_
{ "req_no": 6, "title": "test6" },_x000D_
{ "req_no": 7, "title": "test7" },_x000D_
{ "req_no": 8, "title": "test8" },_x000D_
{ "req_no": 9, "title": "test9" },_x000D_
{ "req_no": 10, "title": "test10" },_x000D_
{ "req_no": 11, "title": "test11" },_x000D_
{ "req_no": 12, "title": "test12" },_x000D_
{ "req_no": 13, "title": "test13" },_x000D_
{ "req_no": 14, "title": "test14" },_x000D_
{ "req_no": 15, "title": "test15" },_x000D_
{ "req_no": 16, "title": "test16" },_x000D_
{ "req_no": 17, "title": "test17" },_x000D_
{ "req_no": 18, "title": "test18" },_x000D_
{ "req_no": 19, "title": "test19" },_x000D_
{ "req_no": 20, "title": "test20" },_x000D_
{ "req_no": 21, "title": "test21" },_x000D_
{ "req_no": 22, "title": "test22" },_x000D_
{ "req_no": 23, "title": "test23" },_x000D_
{ "req_no": 24, "title": "test24" },_x000D_
{ "req_no": 25, "title": "test25" },_x000D_
{ "req_no": 26, "title": "test26" }];_x000D_
_x000D_
// on page load collect data to load pagination as well as table_x000D_
const data = { "req_per_page": document.getElementById("req_per_page").value, "page_no": 1 };_x000D_
_x000D_
// At a time maximum allowed pages to be shown in pagination div_x000D_
const pagination_visible_pages = 4;_x000D_
_x000D_
_x000D_
// hide pages from pagination from beginning if more than pagination_visible_pages_x000D_
function hide_from_beginning(element) {_x000D_
if (element.style.display === "" || element.style.display === "block") {_x000D_
element.style.display = "none";_x000D_
} else {_x000D_
hide_from_beginning(element.nextSibling);_x000D_
}_x000D_
}_x000D_
_x000D_
// hide pages from pagination ending if more than pagination_visible_pages_x000D_
function hide_from_end(element) {_x000D_
if (element.style.display === "" || element.style.display === "block") {_x000D_
element.style.display = "none";_x000D_
} else {_x000D_
hide_from_beginning(element.previousSibling);_x000D_
}_x000D_
}_x000D_
_x000D_
// load data and style for active page_x000D_
function active_page(element, rows, req_per_page) {_x000D_
var current_page = document.getElementsByClassName('active');_x000D_
var next_link = document.getElementById('next_link');_x000D_
var prev_link = document.getElementById('prev_link');_x000D_
var next_tab = current_page[0].nextSibling; _x000D_
var prev_tab = current_page[0].previousSibling;_x000D_
current_page[0].className = current_page[0].className.replace("active", "");_x000D_
if (element === "next") {_x000D_
if (parseInt(next_tab.text).toString() === 'NaN') {_x000D_
next_tab.previousSibling.className += " active";_x000D_
next_tab.setAttribute("onclick", "return false");_x000D_
} else {_x000D_
next_tab.className += " active"_x000D_
render_table_rows(rows, parseInt(req_per_page), parseInt(next_tab.text));_x000D_
if (prev_link.getAttribute("onclick") === "return false") {_x000D_
prev_link.setAttribute("onclick", `active_page('prev',\"${rows}\",${req_per_page})`);_x000D_
}_x000D_
if (next_tab.style.display === "none") {_x000D_
next_tab.style.display = "block";_x000D_
hide_from_beginning(prev_link.nextSibling)_x000D_
}_x000D_
}_x000D_
} else if (element === "prev") {_x000D_
if (parseInt(prev_tab.text).toString() === 'NaN') {_x000D_
prev_tab.nextSibling.className += " active";_x000D_
prev_tab.setAttribute("onclick", "return false");_x000D_
} else {_x000D_
prev_tab.className += " active";_x000D_
render_table_rows(rows, parseInt(req_per_page), parseInt(prev_tab.text));_x000D_
if (next_link.getAttribute("onclick") === "return false") {_x000D_
next_link.setAttribute("onclick", `active_page('next',\"${rows}\",${req_per_page})`);_x000D_
}_x000D_
if (prev_tab.style.display === "none") {_x000D_
prev_tab.style.display = "block";_x000D_
hide_from_end(next_link.previousSibling)_x000D_
}_x000D_
}_x000D_
} else {_x000D_
element.className += "active";_x000D_
render_table_rows(rows, parseInt(req_per_page), parseInt(element.text));_x000D_
if (prev_link.getAttribute("onclick") === "return false") {_x000D_
prev_link.setAttribute("onclick", `active_page('prev',\"${rows}\",${req_per_page})`);_x000D_
}_x000D_
if (next_link.getAttribute("onclick") === "return false") {_x000D_
next_link.setAttribute("onclick", `active_page('next',\"${rows}\",${req_per_page})`);_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
// Render the table's row in table request-table_x000D_
function render_table_rows(rows, req_per_page, page_no) {_x000D_
const response = JSON.parse(window.atob(rows));_x000D_
const resp = response.slice(req_per_page * (page_no - 1), req_per_page * page_no)_x000D_
$('#request-table').empty()_x000D_
$('#request-table').append('<tr><th>Index</th><th>Request No</th><th>Title</th></tr>');_x000D_
resp.forEach(function (element, index) {_x000D_
if (Object.keys(element).length > 0) {_x000D_
const { req_no, title } = element;_x000D_
const td = `<tr><td>${++index}</td><td>${req_no}</td><td>${title}</td></tr>`;_x000D_
$('#request-table').append(td)_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
// Pagination logic implementation_x000D_
function pagination(data, myarr) {_x000D_
const all_data = window.btoa(JSON.stringify(myarr));_x000D_
$(".pagination").empty();_x000D_
if (data.req_per_page !== 'ALL') {_x000D_
let pager = `<a href="#" id="prev_link" onclick=active_page('prev',\"${all_data}\",${data.req_per_page})>«</a>` +_x000D_
`<a href="#" class="active" onclick=active_page(this,\"${all_data}\",${data.req_per_page})>1</a>`;_x000D_
const total_page = Math.ceil(parseInt(myarr.length) / parseInt(data.req_per_page));_x000D_
if (total_page < pagination_visible_pages) {_x000D_
render_table_rows(all_data, data.req_per_page, data.page_no);_x000D_
for (let num = 2; num <= total_page; num++) {_x000D_
pager += `<a href="#" onclick=active_page(this,\"${all_data}\",${data.req_per_page})>${num}</a>`;_x000D_
}_x000D_
} else {_x000D_
render_table_rows(all_data, data.req_per_page, data.page_no);_x000D_
for (let num = 2; num <= pagination_visible_pages; num++) {_x000D_
pager += `<a href="#" onclick=active_page(this,\"${all_data}\",${data.req_per_page})>${num}</a>`;_x000D_
}_x000D_
for (let num = pagination_visible_pages + 1; num <= total_page; num++) {_x000D_
pager += `<a href="#" style="display:none;" onclick=active_page(this,\"${all_data}\",${data.req_per_page})>${num}</a>`;_x000D_
}_x000D_
}_x000D_
pager += `<a href="#" id="next_link" onclick=active_page('next',\"${all_data}\",${data.req_per_page})>»</a>`;_x000D_
$(".pagination").append(pager);_x000D_
} else {_x000D_
render_table_rows(all_data, myarr.length, 1);_x000D_
}_x000D_
}_x000D_
_x000D_
//calling pagination function_x000D_
pagination(data, myarr);_x000D_
_x000D_
_x000D_
// trigger when requests per page dropdown changes_x000D_
function filter_requests() {_x000D_
const data = { "req_per_page": document.getElementById("req_per_page").value, "page_no": 1 };_x000D_
pagination(data, myarr);_x000D_
}
_x000D_
.box {_x000D_
float: left;_x000D_
padding: 50px 0px;_x000D_
}_x000D_
_x000D_
.clearfix::after {_x000D_
clear: both;_x000D_
display: table;_x000D_
}_x000D_
_x000D_
.options {_x000D_
margin: 5px 0px 0px 0px;_x000D_
float: left;_x000D_
}_x000D_
_x000D_
.pagination {_x000D_
float: right;_x000D_
}_x000D_
_x000D_
.pagination a {_x000D_
color: black;_x000D_
float: left;_x000D_
padding: 8px 16px;_x000D_
text-decoration: none;_x000D_
transition: background-color .3s;_x000D_
border: 1px solid #ddd;_x000D_
margin: 0 4px;_x000D_
}_x000D_
_x000D_
.pagination a.active {_x000D_
background-color: #4CAF50;_x000D_
color: white;_x000D_
border: 1px solid #4CAF50;_x000D_
}_x000D_
_x000D_
.pagination a:hover:not(.active) {_x000D_
background-color: #ddd;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div>_x000D_
<table id="request-table">_x000D_
</table>_x000D_
</div>_x000D_
_x000D_
<div class="clearfix">_x000D_
<div class="box options">_x000D_
<label>Requests Per Page: </label>_x000D_
<select id="req_per_page" onchange="filter_requests()">_x000D_
<option>5</option>_x000D_
<option>10</option>_x000D_
<option>ALL</option>_x000D_
</select>_x000D_
</div>_x000D_
<div class="box pagination">_x000D_
</div>_x000D_
</div>
_x000D_
MySQL says:
All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.
When do I use it ?
Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED
data type.
A common mistake is to use a primary key that is an auto-increment INT
starting at zero, yet the type is SIGNED
, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.
while the above answers didn't solve my problem. I finally solved it by specifically going to this link https://www.microsoft.com/net/download/visual-studio-sdks and download the required sdk for Visual Studio. It was really confusing and i don't understand why but that solved my problem
If all you are trying to do is capture the output from a command, then this will work well.
I use it for changing system time, as [timezoneinfo]::local
always produces the same information, even after you have made changes to the system. This is the only way I can validate and log the change in time zone:
$NewTime = (powershell.exe -command [timezoneinfo]::local)
$NewTime | Tee-Object -FilePath $strLFpath\$strLFName -Append
Meaning that I have to open a new PowerShell session to reload the system variables.
Besides using multiple proxies or proxy-networks, you might want to try the planet-lab. (And probably there are other similar institutions around).
The social solution would be to post a question on some board that you are searching for volunteers that proxy your requests. (They only have to allow for one destination in their proxy config thus the danger of becoming spam-whores is relatively low.) You should prepare credentials that ensure your partners of the authenticity of the claim that the destination is indeed your computer.
For Chrome Version 50+ for Mac Users. Close all opened chrome first and run the below command
open -a Google\ Chrome --args --disable-web-security --user-data-dir=""
The above will work. Thanks
The provided answers do not work in Firefox (Quantum). The event listener needs to be changed from mousewheel to wheel:
$(':input[type=number]').on('wheel',function(e){ $(this).blur(); });
This code works on Firefox Quantum and Chrome.
If you want to do it typed:
class Something {
areas: Area[][];
constructor() {
this.areas = new Array<Array<Area>>();
for (let y = 0; y <= 100; y++) {
let row:Area[] = new Array<Area>();
for (let x = 0; x <=100; x++){
row.push(new Area(x, y));
}
this.areas.push(row);
}
}
}
Add this in your css to hide both scroll bar
iframe
{
overflow-x:hidden;
overflow-Y:hidden;
}
Microsoft always ploughs a self-defeating (at least in IE) furrow:
http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/
CORS works with XDomainRequest in IE8. But IE 8 does not support Preflighted or Credentialed Requests while Firefox 3.5+, Safari 4+, and Chrome all support such requests.
You have two approaches to this:
I would suggest the second method because its less irritating. Remember to also check onpaste
. If you use only keypress Then We Can Copy and paste special characters so use onpaste
also to restrict Pasting special characters
Additionally, I will also suggest that you reconsider if you really want to prevent users from entering special characters. Because many people have $, #, @ and * in their passwords.
I presume that this might be in order to prevent SQL injection; if so: its better that you handle the checks server-side. Or better still, escape the values and store them in the database.
IF OBJECT_ID('mytablename') IS NOT NULL
$newarr=arsort($arr);
$max_key=array_shift(array_keys($new_arr));
I published one here: FullParam SQL Blog
/* Reto Egeter, fullparam.wordpress.com */
DECLARE @SearchStrTableName nvarchar(255), @SearchStrColumnName nvarchar(255), @SearchStrColumnValue nvarchar(255), @SearchStrInXML bit, @FullRowResult bit, @FullRowResultRows int
SET @SearchStrColumnValue = '%searchthis%' /* use LIKE syntax */
SET @FullRowResult = 1
SET @FullRowResultRows = 3
SET @SearchStrTableName = NULL /* NULL for all tables, uses LIKE syntax */
SET @SearchStrColumnName = NULL /* NULL for all columns, uses LIKE syntax */
SET @SearchStrInXML = 0 /* Searching XML data may be slow */
IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
CREATE TABLE #Results (TableName nvarchar(128), ColumnName nvarchar(128), ColumnValue nvarchar(max),ColumnType nvarchar(20))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256) = '',@ColumnName nvarchar(128),@ColumnType nvarchar(20), @QuotedSearchStrColumnValue nvarchar(110), @QuotedSearchStrColumnName nvarchar(110)
SET @QuotedSearchStrColumnValue = QUOTENAME(@SearchStrColumnValue,'''')
DECLARE @ColumnNameTable TABLE (COLUMN_NAME nvarchar(128),DATA_TYPE nvarchar(20))
WHILE @TableName IS NOT NULL
BEGIN
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND TABLE_NAME LIKE COALESCE(@SearchStrTableName,TABLE_NAME)
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)), 'IsMSShipped') = 0
)
IF @TableName IS NOT NULL
BEGIN
DECLARE @sql VARCHAR(MAX)
SET @sql = 'SELECT QUOTENAME(COLUMN_NAME),DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(''' + @TableName + ''', 2)
AND TABLE_NAME = PARSENAME(''' + @TableName + ''', 1)
AND DATA_TYPE IN (' + CASE WHEN ISNUMERIC(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@SearchStrColumnValue,'%',''),'_',''),'[',''),']',''),'-','')) = 1 THEN '''tinyint'',''int'',''smallint'',''bigint'',''numeric'',''decimal'',''smallmoney'',''money'',' ELSE '' END + '''char'',''varchar'',''nchar'',''nvarchar'',''timestamp'',''uniqueidentifier''' + CASE @SearchStrInXML WHEN 1 THEN ',''xml''' ELSE '' END + ')
AND COLUMN_NAME LIKE COALESCE(' + CASE WHEN @SearchStrColumnName IS NULL THEN 'NULL' ELSE '''' + @SearchStrColumnName + '''' END + ',COLUMN_NAME)'
INSERT INTO @ColumnNameTable
EXEC (@sql)
WHILE EXISTS (SELECT TOP 1 COLUMN_NAME FROM @ColumnNameTable)
BEGIN
PRINT @ColumnName
SELECT TOP 1 @ColumnName = COLUMN_NAME,@ColumnType = DATA_TYPE FROM @ColumnNameTable
SET @sql = 'SELECT ''' + @TableName + ''',''' + @ColumnName + ''',' + CASE @ColumnType WHEN 'xml' THEN 'LEFT(CAST(' + @ColumnName + ' AS nvarchar(MAX)), 4096),'''
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + '),'''
ELSE 'LEFT(' + @ColumnName + ', 4096),''' END + @ColumnType + '''
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + CASE @ColumnType WHEN 'xml' THEN 'CAST(' + @ColumnName + ' AS nvarchar(MAX))'
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + ')'
ELSE @ColumnName END + ' LIKE ' + @QuotedSearchStrColumnValue
INSERT INTO #Results
EXEC(@sql)
IF @@ROWCOUNT > 0 IF @FullRowResult = 1
BEGIN
SET @sql = 'SELECT TOP ' + CAST(@FullRowResultRows AS VARCHAR(3)) + ' ''' + @TableName + ''' AS [TableFound],''' + @ColumnName + ''' AS [ColumnFound],''FullRow>'' AS [FullRow>],*' +
' FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + CASE @ColumnType WHEN 'xml' THEN 'CAST(' + @ColumnName + ' AS nvarchar(MAX))'
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + ')'
ELSE @ColumnName END + ' LIKE ' + @QuotedSearchStrColumnValue
EXEC(@sql)
END
DELETE FROM @ColumnNameTable WHERE COLUMN_NAME = @ColumnName
END
END
END
SET NOCOUNT OFF
SELECT TableName, ColumnName, ColumnValue, ColumnType, COUNT(*) AS Count FROM #Results
GROUP BY TableName, ColumnName, ColumnValue, ColumnType
According to http://blog.flameeyes.eu/2008/04/14/what-about-those-la-files, they're needed to handle dependencies. But using pkg-config may be a better option:
In a perfect world, every static library needing dependencies would have its own .pc file for pkg-config, and every package trying to statically link to that library would be using pkg-config --static to get the libraries to link to.
I think it is not useful to configure the mysql server without caching_sha2_password encryption, we have to find a way to publish, send or obtain secure information through the network. As you see in the code below I dont use variable $db_name, and Im using a user in mysql server with standar configuration password. Just create a Standar user password and config all privilages. it works, but how i said without segurity.
<?php
$db_name="db";
$mysql_username="root";
$mysql_password="****";
$server_name="localhost";
$conn=mysqli_connect($server_name,$mysql_username,$mysql_password);
if ($conn) {
echo "connetion success";
}
else{
echo mysqli_error($conn);
}
?>
It looks like you are currently pointing JAVA_HOME to /usr/lib/jvm/java-6-openjdk/jre
which appears to be a JRE not a JDK. Try setting JAVA_HOME to /usr/lib/jvm/java-6-openjdk
.
The JRE does not contain the Java compiler, only the JDK (Java Developer Kit) contains it.
You must use $lastId = $this->db->insert_id();
I just had a similar issue. I'm not totally sure how to describe the actual fault but it seems like the hostname in the reservation is incorrect. Try this in an elevated command prompt...
netsh http delete urlacl url=http://localhost:62940/
... then ...
netsh http add urlacl url=http://*:62940/ user=everyone
and restart your site. It should work.
The problem is that you are using the bitwise or operator: |
. If you use the logical or operator, ||
, your code will work fine.
See also:
http://en.wikipedia.org/wiki/Short-circuit_evaluation
Difference between & and && in Java?
Yes, I think for Windows users you need to change all the python3
calls to python
to solve your original error. This change will run the Python version set in your current environment. If you need to keep this call as it is (aka python3
) because you are working in cross-platform or for any other reason, then a work around is to create a soft link. To create it, go to the folder that contains the Python executable and create the link. For example, this worked in my case in Windows 10 using mklink:
cd C:\Python3
mklink python3.exe python.exe
Use a (soft) symbolic link in Linux:
cd /usr/bin/python3
ln -s python.exe python3.exe
After much try and study, I was able to figure it out. First, the variable data from Intent will always be null so, therefore, checking for !null
will crash your app so long you are passing a URI to startActivityForResult.Follow the example below.
I will be using Kotlin.
Open the camera intent
fun addBathroomPhoto(){
addbathroomphoto.setOnClickListener{
request_capture_image=2
var takePictureIntent:Intent?
takePictureIntent =Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if(takePictureIntent.resolveActivity(activity?.getPackageManager()) != null){
val photoFile: File? = try {
createImageFile()
} catch (ex: IOException) {
// Error occurred while creating the File
null
}
if (photoFile != null) {
val photoURI: Uri = FileProvider.getUriForFile(
activity!!,
"ogavenue.ng.hotelroomkeeping.fileprovider",photoFile)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
photoURI);
startActivityForResult(takePictureIntent,
request_capture_image);
}
}
}
}`
Create the createImageFile().But you MUST make the imageFilePath variable global. Example on how to create it is on Android official documentation and pretty straightforward
Get Intent
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == 1 && resultCode == RESULT_OK) {
add_room_photo_txt.text=""
var myBitmap=BitmapFactory.decodeFile(imageFilePath)
addroomphoto.setImageBitmap(myBitmap)
var file=File(imageFilePath)
var fis=FileInputStream(file)
var bm = BitmapFactory.decodeStream(fis);
roomphoto=getBytesFromBitmap(bm) }}
The getBytesFromBitmap method
fun getBytesFromBitmap(bitmap:Bitmap):ByteArray{
var stream=ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
return stream.toByteArray();
}
I hope this helps.
To calculate the sum of a column in a DataTable use the DataTable.Compute method.
Example of usage from the linked MSDN article:
DataTable table = dataSet.Tables["YourTableName"];
// Declare an object variable.
object sumObject;
sumObject = table.Compute("Sum(Amount)", string.Empty);
Display the result in your Total Amount Label like so:
lblTotalAmount.Text = sumObject.ToString();
After going through other answers I came up with this, just apply class nested-counter-list
to root ol
tag:
sass code:
ol.nested-counter-list {
counter-reset: item;
li {
display: block;
&::before {
content: counters(item, ".") ". ";
counter-increment: item;
font-weight: bold;
}
}
ol {
counter-reset: item;
& > li {
display: block;
&::before {
content: counters(item, ".") " ";
counter-increment: item;
font-weight: bold;
}
}
}
}
css code:
ol.nested-counter-list {
counter-reset: item;
}
ol.nested-counter-list li {
display: block;
}
ol.nested-counter-list li::before {
content: counters(item, ".") ". ";
counter-increment: item;
font-weight: bold;
}
ol.nested-counter-list ol {
counter-reset: item;
}
ol.nested-counter-list ol > li {
display: block;
}
ol.nested-counter-list ol > li::before {
content: counters(item, ".") " ";
counter-increment: item;
font-weight: bold;
}
ol.nested-counter-list {
counter-reset: item;
}
ol.nested-counter-list li {
display: block;
}
ol.nested-counter-list li::before {
content: counters(item, ".") ". ";
counter-increment: item;
font-weight: bold;
}
ol.nested-counter-list ol {
counter-reset: item;
}
ol.nested-counter-list ol>li {
display: block;
}
ol.nested-counter-list ol>li::before {
content: counters(item, ".") " ";
counter-increment: item;
font-weight: bold;
}
_x000D_
<ol class="nested-counter-list">
<li>one</li>
<li>two
<ol>
<li>two.one</li>
<li>two.two</li>
<li>two.three</li>
</ol>
</li>
<li>three
<ol>
<li>three.one</li>
<li>three.two
<ol>
<li>three.two.one</li>
<li>three.two.two</li>
</ol>
</li>
</ol>
</li>
<li>four</li>
</ol>
_x000D_
And if you need trailing .
at the end of the nested list's counters use this:
ol.nested-counter-list {
counter-reset: item;
}
ol.nested-counter-list li {
display: block;
}
ol.nested-counter-list li::before {
content: counters(item, ".") ". ";
counter-increment: item;
font-weight: bold;
}
ol.nested-counter-list ol {
counter-reset: item;
}
_x000D_
<ol class="nested-counter-list">
<li>one</li>
<li>two
<ol>
<li>two.one</li>
<li>two.two</li>
<li>two.three</li>
</ol>
</li>
<li>three
<ol>
<li>three.one</li>
<li>three.two
<ol>
<li>three.two.one</li>
<li>three.two.two</li>
</ol>
</li>
</ol>
</li>
<li>four</li>
</ol>
_x000D_
That is how I make it work :
sudo apt-get install default-jre
sudo apt-get install default-jdk
sudo R CMD javareconf
install.packages("rJava")
If the file share is not open to everybody you will need to serve it up in the background from the file system via the web server.
You can use something like this "ASP.Net Serve File For Download" example (archived copy of 2).
I think you'll have to write a script to do this. To be honest, I might install python to do it so that you can use os.walk
to cd
to each directory and issue the appropriate commands. Using python or some other scripting language, other than batch, would allow you to easily add/remove subprojects with out having to modify the script.
Both of these are primary from the old printing days.
Carriage return is from the days of the teletype printers/old typewriters, where literally the carriage would return to the next line, and push the paper up. This is what we now call \r
.
Line feed LF
signals the end of the line, it signals that the line has ended - but doesn't move the cursor to the next line. In other words, it doesn't "return" the cursor/printer head to the next line.
For more sundry details, the mighty wikipedia to the rescue.
Solved this issue by increasing swap size:
https://askubuntu.com/questions/1075505/how-do-i-increase-swapfile-in-ubuntu-18-04
self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshData)];
}
-(void)refreshData{
progressHud= [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
[progressHud setLabelText:@"?????..."];
[self loadNetwork];
}
$(".pushme").click(function () {
var button = $(this);
button.text(button.text() == "PUSH ME" ? "DON'T PUSH ME" : "PUSH ME")
});
This ternary operator has an implicit return.
If the expression before ?
is true
it returns "DON'T PUSH ME"
, else returns "PUSH ME"
This if-else statement:
if (condition) { return A }
else { return B }
has the equivalent ternary expression:
condition ? A : B
FOR A ONE LINER SOLUTION, type the following in Command prompt or Terminal at project root.
echo node_modules > .dockerignore
This creates the extension-less . prefixed file without any issue. Replace node_modules with the folder you want to exclude.
If you don't want your code to depend on other packages, you can always just write these functions:
perm = function(n, x) {
factorial(n) / factorial(n-x)
}
comb = function(n, x) {
factorial(n) / factorial(n-x) / factorial(x)
}
With Yglu, you can write your example as:
paths:
root: /path/to/root/
patha: !? .paths.root + a
pathb: !? .paths.root + b
pathc: !? .paths.root + c
Disclaimer: I am the author of Yglu.
Matthew's answer awoke many emotions, because of the fact that it still lacks a minor detail. The general command would be:
# yum --nogpgcheck localinstall <package1_file_name> ... <packageN_file_name>
The package_file_name
above can include local absolute or relative path, or be a URL (possibly even an URI).
Yum would search for dependencies among all package files given on the command line AND IF IT FAILS to find the dependencies there, it will also use any configured and enabled yum repositories.
Neither the current working directory, nor the paths of any of package_file_name
will be searched, except when any of these directories has been previously configured as an enabled yum
repository.
So in the OP's case the yum
command:
# cd <path with pkg files>; yum --nogpgcheck localinstall ./proj1-1.0-1.x86_64.rpm ./libtest1-1.0-1.x86_64.rpm
would do, as would do the rpm
:
# cd <path with pkg files>; rpm -i proj1-1.0-1.x86_64.rpm libtest1-1.0-1.x86_64.rpm
The differencve between these yum
and rpm
invocations would only be visible if one of the packages listed to be installed had further dependencies on packages NOT listed on the command line.
In such a case rpm
will just refuse to continue, while yum
would use any configured and enabled yum repositories to search for dependencies, and may possibly succeed.
The current working directory will NOT be searched in any case, except when it has been previously configured as an enabled yum
repository.
Unfortunately there is no way to add Tooltips for UDF Arguments.
To extend Remou's reply you can find a fuller but more complex approach to descriptions for the Function Wizard at
http://www.jkp-ads.com/Articles/RegisterUDF00.asp
I do realize that the author asks question in relation to a class-based component, however I think it's worth mentioning that as of React 16.8.0 (February 6, 2019) you can take advantage of hooks in function-based components.
Example code:
import { useRef } from 'react'
function Component() {
const inputRef = useRef()
return (
<input ref={inputRef} />
<div
onScroll={() => {
const { offsetTop } = inputRef.current
...
}}
>
)
}
There are three ways to resolve this issue.
Right click the project and click "Properties". Then select "Android" from left. You can then select the target version from right side.
Right Click on Project and select "run as" , then a drop down list will be open.
Select "Run Configuration" from Drop Down list.Then a form will be open ,
Select "Target" tab from "Form" and also select Android Version Api ,
On which you want to execute your application, it is a fastest way to check
your application on different Target Version.
Edit the following elements in the AndroidManifest.xml file
xml:
<uses-sdk android:minSdkVersion="3" />
<uses-sdk android:targetSdkVersion="8" />
using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT * FROM learer WHERE id = @id";
cmd.Parameters.AddWithValue("@id", index);
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
learerLabel.Text = reader.GetString(reader.GetOrdinal("somecolumn"))
}
}
}
R treats backslashes as escape values for character constants. (... and so do regular expressions. Hence the need for two backslashes when supplying a character argument for a pattern. The first one isn't actually a character, but rather it makes the second one into a character.) You can see how they are processed using cat
.
y <- "double quote: \", tab: \t, newline: \n, unicode point: \u20AC"
print(y)
## [1] "double quote: \", tab: \t, newline: \n, unicode point: €"
cat(y)
## double quote: ", tab: , newline:
## , unicode point: €
Further reading: Escaping a backslash with a backslash in R produces 2 backslashes in a string, not 1
To use special characters in a regular expression the simplest method is usually to escape them with a backslash, but as noted above, the backslash itself needs to be escaped.
grepl("\\[", "a[b")
## [1] TRUE
To match backslashes, you need to double escape, resulting in four backslashes.
grepl("\\\\", c("a\\b", "a\nb"))
## [1] TRUE FALSE
The rebus
package contains constants for each of the special characters to save you mistyping slashes.
library(rebus)
OPEN_BRACKET
## [1] "\\["
BACKSLASH
## [1] "\\\\"
For more examples see:
?SpecialCharacters
Your problem can be solved this way:
library(rebus)
grepl(OPEN_BRACKET, "a[b")
You can also wrap the special characters in square brackets to form a character class.
grepl("[?]", "a?b")
## [1] TRUE
Two of the special characters have special meaning inside character classes: \
and ^
.
Backslash still needs to be escaped even if it is inside a character class.
grepl("[\\\\]", c("a\\b", "a\nb"))
## [1] TRUE FALSE
Caret only needs to be escaped if it is directly after the opening square bracket.
grepl("[ ^]", "a^b") # matches spaces as well.
## [1] TRUE
grepl("[\\^]", "a^b")
## [1] TRUE
rebus
also lets you form a character class.
char_class("?")
## <regex> [?]
If you want to match all punctuation, you can use the [:punct:]
character class.
grepl("[[:punct:]]", c("//", "[", "(", "{", "?", "^", "$"))
## [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE
stringi
maps this to the Unicode General Category for punctuation, so its behaviour is slightly different.
stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "[[:punct:]]")
## [1] TRUE TRUE TRUE TRUE TRUE FALSE FALSE
You can also use the cross-platform syntax for accessing a UGC.
stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "\\p{P}")
## [1] TRUE TRUE TRUE TRUE TRUE FALSE FALSE
Placing characters between \\Q
and \\E
makes the regular expression engine treat them literally rather than as regular expressions.
grepl("\\Q.\\E", "a.b")
## [1] TRUE
rebus
lets you write literal blocks of regular expressions.
literal(".")
## <regex> \Q.\E
Regular expressions are not always the answer. If you want to match a fixed string then you can do, for example:
grepl("[", "a[b", fixed = TRUE)
stringr::str_detect("a[b", fixed("["))
stringi::stri_detect_fixed("a[b", "[")
You have to set seed every time you want to get a reproducible random result.
set.seed(1)
rnorm(4)
set.seed(1)
rnorm(4)
Using dynamic variable for search in array
/* https://ideone.com/Pfb0Ou */
$array = array('kitchen', 'bedroom', 'living_room', 'dining_room');
/* variable search */
$search = 'living_room';
if (in_array($search, $array)) {
echo "this array contains $search";
} else
echo "this array NOT contains $search";
If you want to find interactively logged on users, I found a great tip here :https://p0w3rsh3ll.wordpress.com/2012/02/03/get-logged-on-users/ (Win32_ComputerSystem did not help me)
$explorerprocesses = @(Get-WmiObject -Query "Select * FROM Win32_Process WHERE Name='explorer.exe'" -ErrorAction SilentlyContinue)
If ($explorerprocesses.Count -eq 0)
{
"No explorer process found / Nobody interactively logged on"
}
Else
{
ForEach ($i in $explorerprocesses)
{
$Username = $i.GetOwner().User
$Domain = $i.GetOwner().Domain
Write-Host "$Domain\$Username logged on since: $($i.ConvertToDateTime($i.CreationDate))"
}
}
On Mac OS X el captain with brew, try:
brew install pkgconfig
This worked for me.
Element.style
MDNvar toggle = document.getElementById("toggle");
var content = document.getElementById("content");
toggle.addEventListener("click", function() {
content.style.display = (content.dataset.toggled ^= 1) ? "block" : "none";
});
_x000D_
#content{
display:none;
}
_x000D_
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
_x000D_
About the ^
bitwise XOR as I/O toggler
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
.classList.toggle()
var toggle = document.getElementById("toggle");
var content = document.getElementById("content");
toggle.addEventListener("click", function() {
content.classList.toggle("show");
});
_x000D_
#content{
display:none;
}
#content.show{
display:block; /* P.S: Use `!important` if missing `#content` (selector specificity). */
}
_x000D_
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
_x000D_
.toggle()
Docs; .fadeToggle()
Docs; .slideToggle()
Docs$("#toggle").on("click", function(){
$("#content").toggle(); // .fadeToggle() // .slideToggle()
});
_x000D_
#content{
display:none;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
_x000D_
.toggleClass()
Docs.toggle()
toggles an element's display
"block"/"none"
values
$("#toggle").on("click", function(){
$("#content").toggleClass("show");
});
_x000D_
#content{
display:none;
}
#content.show{
display:block; /* P.S: Use `!important` if missing `#content` (selector specificity). */
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
_x000D_
<summary>
and <details>
(unsupported on IE and Opera Mini)
<details>
<summary>TOGGLE</summary>
<p>Some content...</p>
</details>
_x000D_
checkbox
[id^=toggle],
[id^=toggle] + *{
display:none;
}
[id^=toggle]:checked + *{
display:block;
}
_x000D_
<label for="toggle-1">TOGGLE</label>
<input id="toggle-1" type="checkbox">
<div>Some content...</div>
_x000D_
radio
[id^=switch],
[id^=switch] + *{
display:none;
}
[id^=switch]:checked + *{
display:block;
}
_x000D_
<label for="switch-1">SHOW 1</label>
<label for="switch-2">SHOW 2</label>
<input id="switch-1" type="radio" name="tog">
<div>1 Merol Muspi...</div>
<input id="switch-2" type="radio" name="tog">
<div>2 Lorem Ipsum...</div>
_x000D_
:target
(just to make sure you have it in your arsenal)
[id^=switch] + *{
display:none;
}
[id^=switch]:target + *{
display:block;
}
_x000D_
<a href="#switch1">SHOW 1</a>
<a href="#switch2">SHOW 2</a>
<i id="switch1"></i>
<div>1 Merol Muspi ...</div>
<i id="switch2"></i>
<div>2 Lorem Ipsum...</div>
_x000D_
If you pick one of JS / jQuery way to actually toggle a className
, you can always add animated transitions to your element, here's a basic example:
var toggle = document.getElementById("toggle");
var content = document.getElementById("content");
toggle.addEventListener("click", function(){
content.classList.toggle("appear");
}, false);
_x000D_
#content{
/* DON'T USE DISPLAY NONE/BLOCK! Instead: */
background: #cf5;
padding: 10px;
position: absolute;
visibility: hidden;
opacity: 0;
transition: 0.6s;
-webkit-transition: 0.6s;
transform: translateX(-100%);
-webkit-transform: translateX(-100%);
}
#content.appear{
visibility: visible;
opacity: 1;
transform: translateX(0);
-webkit-transform: translateX(0);
}
_x000D_
<button id="toggle">TOGGLE</button>
<div id="content">Some Togglable content...</div>
_x000D_
import org.springframework.core.Ordered;
public class MyFilter implements Filter, Ordered {
@Override
public void init(FilterConfig filterConfig) {
// do something
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
// do something
}
@Override
public void destroy() {
// do something
}
@Override
public int getOrder() {
return -100;
}
}
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
public class MyAutoConfiguration {
@Bean
public MyFilter myFilter() {
return new MyFilter();
}
}
Move doSomething
definition outside of its class declaration and after B
and also make add
accessible to A
by public
-ing it or friend
-ing it.
class B;
class A
{
void doSomething(B * b);
};
class B
{
public:
void add() {}
};
void A::doSomething(B * b)
{
b->add();
}
Check out: MSDN Article
You can use GetModuleName
(I think?) to get the name and check against that.
I wrote a simple test for all the above.
def eq(a, b)
puts "#{[a, '==', b]} : #{a == b}"
puts "#{[a, '===', b]} : #{a === b}"
puts "#{[a, '.eql?', b]} : #{a.eql?(b)}"
puts "#{[a, '.equal?', b]} : #{a.equal?(b)}"
end
eq("all", "all")
eq(:all, :all)
eq(Object.new, Object.new)
eq(3, 3)
eq(1, 1.0)
Using the contentWindow.focus() method, the timeout is probably necessary to wait for the iframe to be completely loaded.
For me, also using attribute onload="this.contentWindow.focus()"
works, with firefox, into the iframe tag
You can use below IsValidDate():
public static bool IsValidDate(string value, string[] dateFormats)
{
DateTime tempDate;
bool validDate = DateTime.TryParseExact(value, dateFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, ref tempDate);
if (validDate)
return true;
else
return false;
}
And you can pass in the value and date formats. For example:
var data = "02-08-2019";
var dateFormats = {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"}
if (IsValidDate(data, dateFormats))
{
//Do something
}
else
{
//Do something else
}
Use the date function:
select date(timestamp_field) from table
From a character field representation to a date you can use:
select date(substring('2011/05/26 09:00:00' from 1 for 10));
Test code:
create table test_table (timestamp_field timestamp);
insert into test_table (timestamp_field) values(current_timestamp);
select timestamp_field, date(timestamp_field) from test_table;
Test result:
Since this appears to be a simple parent/child relationship between pets
and pets_activities
, you would be better off creating your foreign key constraint with a deleting cascade.
That way, when a pets
row is deleted, the pets_activities
rows associated with it are automatically deleted as well.
Then your query becomes a simple:
delete from `pets`
where `order` > :order
and `pet_id` = :pet_id
Assuming you use Python 2.7 (not 3):
print "I have", card.price
(as mentioned above).
print "I have %s" % card.price
(using string formatting)
print " ".join(map(str, ["I have", card.price]))
(by joining lists)
There are a lot of ways to do the same, actually. I would prefer the second one.
You can find answer in depth here.
But in general with float
you need to be aware and take care of the surrounding elements and inline-block
simple way to line elements.
Thanks
Please make the following part of the Collectors API:
<K, V> Collector<? super Map.Entry<K, V>, ?, Map<K, V>> toMap() {
return Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue);
}
Incase of arrays, the base address (i.e. address of the array) is the address of the 1st element in the array. Also the array name acts as a pointer.
Consider a row of houses (each is an element in the array). To identify the row, you only need the 1st house address.You know each house is followed by the next (sequential).Getting the address of the 1st house, will also give you the address of the row.
Incase of string literals(character arrays defined at declaration), they are automatically
appended by \0
.
printf
prints using the format specifier and the address provided. Since, you use %s
it prints from the 1st address (incrementing the pointer using arithmetic) until '\0'
A SimpleDateFormat
, as its name indicates, formats Date
s. Not a Calendar
. So, if you want to format a GregorianCalendar
using a SimpleDateFormat
, you must convert the Calendar
to a Date
first:
dateFormat.format(calendar.getTime());
And what you see printed is the toString()
representation of the calendar. It's intended usage is debugging. It's not intended to be used to display a date in a GUI. For that, use a (Simple
)DateFormat
.
Finally, to convert from a String
to a Date
, you should also use a (Simple
)DateFormat
(its parse()
method), rather than splitting the String
as you're doing. This will give you a Date
object, and you can create a Calendar
from the Date
by instanciating it (Calendar.getInstance()
) and setting its time (calendar.setTime()
).
My advice would be: Googling is not the solution here. Reading the API documentation is what you need to do.
Basically <key>ITSAppUsesNonExemptEncryption</key><false/>
stands for a Boolean value equal to NO.
Update by @JosepH: This value means that the app uses no encryption, or only exempt encryption. If your app uses encryption and is not exempt, you must set this value to YES/true.
It seems debatable sometimes when an app is considered to use encryption.
All of the above answers worked but did have their faults. The below code is an amalgamation of two of the above answers that works flawlessly with no blinking.
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
transition: background-color 5000s ease-in-out 0s;
-webkit-box-shadow: 0 0 0px 1000px #fff inset;
}
I really recommend you use jquery for the javascript calls and some implementation of JSR311 like jersey for the service layer, which would delegate to your controllers.
This will help you with all the underlying logic of handling the HTTP calls and your data serialization, which is a big help.
If you are using ES6 in Node 4, you cannot use ES6 module syntax without a transpiler, but CommonJS modules (Node's standard modules) work the same.
module.export.AspectType
should be
module.exports.AspectType
hence the error message "Cannot set property 'AspectType' of undefined" because module.export === undefined
.
Also, for
var AspectType = class AspectType {
// ...
};
can you just write
class AspectType {
// ...
}
and get essentially the same behavior.
It's because val is not null
, but contains 'null'
as a string.
Try to check with 'null'
if ('null' != val)
For an explanation of when and why this works, see the details below.
A segmentation fault or access violation occurs when a program attempts to access a memory location that is not exist, or attempts to access a memory location in a way that is not allowed.
/* "Array out of bounds" error
valid indices for array foo
are 0, 1, ... 999 */
int foo[1000];
for (int i = 0; i <= 1000 ; i++)
foo[i] = i;
Here i[1000] not exist, so segfault occurs.
Causes of segmentation fault:
it arise primarily due to errors in use of pointers for virtual memory addressing, particularly illegal access.
De-referencing NULL pointers – this is special-cased by memory management hardware.
Attempting to access a nonexistent memory address (outside process’s address space).
Attempting to access memory the program does not have rights to (such as kernel structures in process context).
Attempting to write read-only memory (such as code segment).
Lookarounds can be nested.
So this regex matches "drupal-6.14/" that is not followed by "sites" that is not followed by "/all" or "/default".
Confusing? Using different words, we can say it matches "drupal-6.14/" that is not followed by "sites" unless that is further followed by "/all" or "/default"
You could just do this:
var rnd = new Random();
return (MyEnum) rnd.Next(Enum.GetNames(typeof(MyEnum)).Length);
No need to store arrays
Using bitwise operation would be a better solution. Try this
function formatSizeUnits(bytes)
{
if ( ( bytes >> 30 ) & 0x3FF )
bytes = ( bytes >>> 30 ) + '.' + ( bytes & (3*0x3FF )) + 'GB' ;
else if ( ( bytes >> 20 ) & 0x3FF )
bytes = ( bytes >>> 20 ) + '.' + ( bytes & (2*0x3FF ) ) + 'MB' ;
else if ( ( bytes >> 10 ) & 0x3FF )
bytes = ( bytes >>> 10 ) + '.' + ( bytes & (0x3FF ) ) + 'KB' ;
else if ( ( bytes >> 1 ) & 0x3FF )
bytes = ( bytes >>> 1 ) + 'Bytes' ;
else
bytes = bytes + 'Byte' ;
return bytes ;
}
For JPA 2.1 the javax.persistence package can be found in here:
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
See: hibernate-jpa-2.1-api on Maven Central The pattern seems to be to change the artefact name as the JPA version changes. If this continues new versions can be expected to arrive in Maven Central here: Hibernate JPA versions
The above JPA 2.1 APi can be used in conjunction with Hibernate 4.3.7, specifically:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.7.Final</version>
</dependency>
If you would like to see the details of the tag SOMETAG (tagger, date, etc), the hash of the commit it points to and a bit of info about the commit but without the full diff, try
git show --name-status SOMETAG
Example output:
tag SOMETAG
Tagger: ....
Date: Thu Jan 26 17:40:53 2017 +0100
.... tag message .......
commit 9f00ce27c924c7e972e96be7392918b826a3fad9
Author: .............
Date: Thu Jan 26 17:38:35 2017 +0100
.... commit message .......
..... list of changed files with their change-status (like git log --name-status) .....
For iOS 7 & 8:
Objective-C:
NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
[[UIDevice currentDevice] setValue:value forKey:@"orientation"];
Swift 3+:
let value = UIInterfaceOrientation.landscapeLeft.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
I call it in - viewDidAppear:
.
You can use image.shape to get the dimensions of the image. It returns 3 values. First value is width of an image, second is height and last one is channel. You dont need last value here so you can use below code to get height and width of image:
width, height = src.shape[:2]<br>
print(width, height)
Bash 4 has a coproc
command which establishes a named pipe to a command and allows you to communicate through it.
echo `date +%s`/86400 | bc
This message means there is a syntax error in your XML file. If Logcat cannot pinpoint the error with a friendly log message with the xml file name, try cleaning the project and rebuilding the project. It worked for me.
In the Build tab, you will get a node named Android Issues.
The error message explaining the error with the XML file is under it.
You must know how to type to be a programmer.
It's controversial among people who don't know how to type, but who insist that they can two-finger hunt-and-peck as fast as any typist, or that they don't really need to spend that much time typing, or that Intellisense relieves the need to type...
I've never met anyone who does know how to type, but insists that it doesn't make a difference.
See also: Programming's Dirtiest Little Secret
If you're still getting this error message while using the WCF Test Client, it's because the client has a separate MaxBufferSize setting.
To correct the issue:
A list of editable settings will appear, including MaxBufferSize.
Note: Auto-generated proxy clients also set MaxBufferSize to 65536 by default.
In the Android Studio go to File
then Close Project
. Then take the folder (in the workspace folder) of the project and copy it to a flash memory or whatever. Then when you get comfortable at home, copy this folder in the workspace folder you've already created, open the Android Studio and go to File
then Open
and import this project into your workspace.
The problem you have with this is that you're searching for the wrong term here, because in Android, exporting a project means compiling it to .apk
file (not exporting the project). Import/Export is used for the .apk
management, what you need is Open/Close project, the other thing is just copy/paste.
Convert JSONObject into String and save as TEXT/ VARCHAR. While retrieving the same column convert the String into JSONObject.
For example
Write into DB
String stringToBeInserted = jsonObject.toString();
//and insert this string into DB
Read from DB
String json = Read_column_value_logic_here
JSONObject jsonObject = new JSONObject(json);
You would want to use ->forget()
$collection->forget($key);
Link to the forget method documentation
I am a little late but I used this:
dir /B *.* > dir_file.txt
then you can make a simple FOR loop to extract the file name and use them. e.g:
for /f "tokens=* delims= " %%a in (dir_file.txt) do (
gawk -f awk_script_file.awk %%a
)
or store them into Vars (!N1!, !N2!..!Nn!) for later use. e.g:
set /a N=0
for /f "tokens=* delims= " %%a in (dir_file.txt) do (
set /a N+=1
set v[!N!]=%%a
)
From GIT documentation: Git Docs
Below gives the full information. In short, simple
will only push the current working branch
and even then only if it also has the same name on the remote. This is a very good setting for beginners and will become the default in GIT 2.0
Whereas matching
will push all branches locally that have the same name on the remote. (Without regard to your current working branch ). This means potentially many different branches will be pushed, including those that you might not even want to share.
In my personal usage, I generally use a different option: current
which pushes the current working branch, (because I always branch for any changes). But for a beginner I'd suggest simple
push.default
Defines the action git push should take if no refspec is explicitly given. Different values are well-suited for specific workflows; for instance, in a purely central workflow (i.e. the fetch source is equal to the push destination), upstream is probably what you want. Possible values are:nothing - do not push anything (error out) unless a refspec is explicitly given. This is primarily meant for people who want to avoid mistakes by always being explicit.
current - push the current branch to update a branch with the same name on the receiving end. Works in both central and non-central workflows.
upstream - push the current branch back to the branch whose changes are usually integrated into the current branch (which is called @{upstream}). This mode only makes sense if you are pushing to the same repository you would normally pull from (i.e. central workflow).
simple - in centralized workflow, work like upstream with an added safety to refuse to push if the upstream branch's name is different from the local one.
When pushing to a remote that is different from the remote you normally pull from, work as current. This is the safest option and is suited for beginners.
This mode will become the default in Git 2.0.
matching - push all branches having the same name on both ends. This makes the repository you are pushing to remember the set of branches that will be pushed out (e.g. if you always push maint and master there and no other branches, the repository you push to will have these two branches, and your local maint and master will be pushed there).
To use this mode effectively, you have to make sure all the branches you would push out are ready to be pushed out before running git push, as the whole point of this mode is to allow you to push all of the branches in one go. If you usually finish work on only one branch and push out the result, while other branches are unfinished, this mode is not for you. Also this mode is not suitable for pushing into a shared central repository, as other people may add new branches there, or update the tip of existing branches outside your control.
This is currently the default, but Git 2.0 will change the default to simple.
Don't let white space fool you. Just test this in a console browser.
Use native javascript. Here is and example with two 'ul' sets with the same class. You don't need to have your 'ul' list all in one line to avoid white space just use your array count to jump over white space.
How to get around white space with querySelector()
then childNodes[]
js fiddle link: https://jsfiddle.net/aparadise/56njekdo/
var y = document.querySelector('.list');
var myNode = y.childNodes[11].style.backgroundColor='red';
<ul class="list">
<li>8</li>
<li>9</li>
<li>100</li>
</ul>
<ul class="list">
<li>ABC</li>
<li>DEF</li>
<li>XYZ</li>
</ul>
Using ES6 solution
For those still reading this answer, if you are using ES6 the find
method was added in arrays. So assuming the same collection, the solution'd be:
const foo = { "results": [
{
"id": 12,
"name": "Test"
},
{
"id": 2,
"name": "Beispiel"
},
{
"id": 3,
"name": "Sample"
}
] };
foo.results.find(item => item.id === 2)
I'd totally go for this solution now, as is less tied to angular or any other framework. Pure Javascript.
Angular solution (old solution)
I aimed to solve this problem by doing the following:
$filter('filter')(foo.results, {id: 1})[0];
A use case example:
app.controller('FooCtrl', ['$filter', function($filter) {
var foo = { "results": [
{
"id": 12,
"name": "Test"
},
{
"id": 2,
"name": "Beispiel"
},
{
"id": 3,
"name": "Sample"
}
] };
// We filter the array by id, the result is an array
// so we select the element 0
single_object = $filter('filter')(foo.results, function (d) {return d.id === 2;})[0];
// If you want to see the result, just check the log
console.log(single_object);
}]);
Plunker: http://plnkr.co/edit/5E7FYqNNqDuqFBlyDqRh?p=preview
$("#file-upload").change(function () {
var validExtensions = ["jpg","pdf","jpeg","gif","png"]
var file = $(this).val().split('.').pop();
if (validExtensions.indexOf(file) == -1) {
alert("Only formats are allowed : "+validExtensions.join(', '));
}
});
Client side code: I had a requirement where my nodejs webserver should work as both server as well as client, so i added below code when i need it as client, It should work fine, i am using it and working fine for me!!!
const socket = require('socket.io-client')('http://192.168.0.8:5000', {
reconnection: true,
reconnectionDelay: 10000
});
socket.on('connect', (data) => {
console.log('Connected to Socket');
});
socket.on('event_name', (data) => {
console.log("-----------------received event data from the socket io server");
});
//either 'io server disconnect' or 'io client disconnect'
socket.on('disconnect', (reason) => {
console.log("client disconnected");
if (reason === 'io server disconnect') {
// the disconnection was initiated by the server, you need to reconnect manually
console.log("server disconnected the client, trying to reconnect");
socket.connect();
}else{
console.log("trying to reconnect again with server");
}
// else the socket will automatically try to reconnect
});
socket.on('error', (error) => {
console.log(error);
});
This will work also when the string is invalid or does not contain flags etc:
function regExpFromString(q) {_x000D_
let flags = q.replace(/.*\/([gimuy]*)$/, '$1');_x000D_
if (flags === q) flags = '';_x000D_
let pattern = (flags ? q.replace(new RegExp('^/(.*?)/' + flags + '$'), '$1') : q);_x000D_
try { return new RegExp(pattern, flags); } catch (e) { return null; }_x000D_
}_x000D_
_x000D_
console.log(regExpFromString('\\bword\\b'));_x000D_
console.log(regExpFromString('\/\\bword\\b\/gi'));_x000D_
_x000D_
^\+[1-9]{1}[0-9]{7,11}$
The Regular Expression ^\+[1-9]{1}[0-9]{7,11}$
fails for "+290 8000" and similar valid numbers that are shorter than 8 digits.
The longest numbers could be something like 3 digit country code, 3 digit area code, 8 digit subscriber number, making 14 digits.
I'd use months_between
, possibly combined with floor
:
select floor(months_between(date '2012-10-10', date '2011-10-10') /12) from dual;
select floor(months_between(date '2012-10-9' , date '2011-10-10') /12) from dual;
floor
makes sure you get down-rounded years. If you want the fractional parts, you obviously want to not use floor
.
Just in case you're wondering how you can set multiple different sizes in the same textview, but using an absolute size and not a relative one, you can achieve that using AbsoluteSizeSpan
instead of a RelativeSizeSpan
.
Just get the dimension in pixels of the desired text size
int textSize1 = getResources().getDimensionPixelSize(R.dimen.text_size_1);
int textSize2 = getResources().getDimensionPixelSize(R.dimen.text_size_2);
and then create a new AbsoluteSpan
based on the text
String text1 = "Hi";
String text2 = "there";
SpannableString span1 = new SpannableString(text1);
span1.setSpan(new AbsoluteSizeSpan(textSize1), 0, text1.length(), SPAN_INCLUSIVE_INCLUSIVE);
SpannableString span2 = new SpannableString(text2);
span2.setSpan(new AbsoluteSizeSpan(textSize2), 0, text2.length(), SPAN_INCLUSIVE_INCLUSIVE);
// let's put both spans together with a separator and all
CharSequence finalText = TextUtils.concat(span1, " ", span2);
You can't create arrays with a generic component type.
Create an array of an explicit type, like Object[]
, instead. You can then cast this to PCB[]
if you want, but I don't recommend it in most cases.
PCB[] res = (PCB[]) new Object[list.size()]; /* Not type-safe. */
If you want type safety, use a collection like java.util.List<PCB>
instead of an array.
By the way, if list
is already a java.util.List
, you should use one of its toArray()
methods, instead of duplicating them in your code. This doesn't get your around the type-safety problem though.
you can also use:
<td style="visibility:hidden;">
or
<td style="visibility:collapse;">
The difference between them that "hidden" hides the cell but it holds the space but with "collapse" the space is not held like display:none. This is significant when hidding a whole column or row.
You can change easy marker label css without use any extra plugin.
var marker = new google.maps.Marker({
position: this.overlay_text,
draggable: true,
icon: '',
label: {
text: this.overlay_field_text,
color: '#fff',
fontSize: '20px',
fontWeight: 'bold',
fontFamily: 'custom-label'
},
map:map
});
marker.setMap(map);
$("[style*='custom-label']").css({'text-shadow': '2px 2px #000'})
You need to tell it which index in data
to use, or double loop through all.
E.g., to get the values in the 4th index in the outside array.:
foreach($user->data[3]->values as $values)
{
echo $values->value . "\n";
}
To go through all:
foreach($user->data as $mydata)
{
foreach($mydata->values as $values) {
echo $values->value . "\n";
}
}
I had the same problem and I added tx:annotation-driven
in applicationContext.xml
and it worked.
if isinstance(v, list):
, which scrubs the list using the original scrub_dict(d)
implementation. @staticmethod
def scrub_dict(d):
new_dict = {}
for k, v in d.items():
if isinstance(v, dict):
v = scrub_dict(v)
if isinstance(v, list):
v = scrub_list(v)
if not v in (u'', None, {}):
new_dict[k] = v
return new_dict
@staticmethod
def scrub_list(d):
scrubbed_list = []
for i in d:
if isinstance(i, dict):
i = scrub_dict(i)
scrubbed_list.append(i)
return scrubbed_list
After hours of research, I finally found a solution to take a screenshot of an element, even if the origin-clean
FLAG is set (to prevent XSS), that´s why you can even capture for example Google Maps (in my case). I wrote a universal function to get a screenshot. The only thing you need in addition is the html2canvas library (https://html2canvas.hertzen.com/).
Example:
getScreenshotOfElement($("div#toBeCaptured").get(0), 0, 0, 100, 100, function(data) {
// in the data variable there is the base64 image
// exmaple for displaying the image in an <img>
$("img#captured").attr("src", "data:image/png;base64,"+data);
});
Keep in mind console.log()
and alert()
won´t generate output if the size of the image is great.
Function:
function getScreenshotOfElement(element, posX, posY, width, height, callback) {
html2canvas(element, {
onrendered: function (canvas) {
var context = canvas.getContext('2d');
var imageData = context.getImageData(posX, posY, width, height).data;
var outputCanvas = document.createElement('canvas');
var outputContext = outputCanvas.getContext('2d');
outputCanvas.width = width;
outputCanvas.height = height;
var idata = outputContext.createImageData(width, height);
idata.data.set(imageData);
outputContext.putImageData(idata, 0, 0);
callback(outputCanvas.toDataURL().replace("data:image/png;base64,", ""));
},
width: width,
height: height,
useCORS: true,
taintTest: false,
allowTaint: false
});
}
To return a value from a VBScript function, assign the value to the name of the function, like this:
Function getNumber
getNumber = "423"
End Function
I couldn't get the parse ifconfig script to work for me on an AMI so got this to work measuring received traffic averaged over 10 seconds
date && rxstart=`ifconfig eth0 | grep bytes | awk '{print $2}' | cut -d : -f 2` && sleep 10 && rxend=`ifconfig eth0 | grep bytes | awk '{print $2}' | cut -d : -f 2` && difference=`expr $rxend - $rxstart` && echo "Received `expr $difference / 10` bytes per sec"
Sorry, it's ever so cheap and nasty but it worked!
The string that you pass to the constructor JSONObject
has to be escaped with quote()
:
public static java.lang.String quote(java.lang.String string)
Your code would now be:
JSONObject jsonObj = new JSONObject.quote(jsonString.toString());
System.out.println(jsonString);
System.out.println("---------------------------");
System.out.println(jsonObj);
<html>
<body>
<a href="#" onclick="DoEdit('Preliminary Assessment "Mini"'); return false;">edit</a>
</body>
</html>
Should do the trick.
If none of the other answers fix your problem and it started occurring after change any configuration direct or indirectly (via git pull / merge / rebase) and your project is a Maven project:
mvn clean
Hope this fixes your problem. Or someones
You could try Ladon. It serves up multiple web server protocols at once so you can offer more flexibility at the client side.
I think that the problem is in the nesting of the elements. Once you attach an event to the outer element the clicks on the inner elements are actually firing the same click event for the outer element. So, you actually never go to the second state. What you can do is to check the clicked element. And if it is the close button then to avoid the class changing. Here is my solution:
var element = $(".clickable");
var closeButton = element.find(".close_button");
var onElementClick = function(e) {
if(e.target !== closeButton[0]) {
element.removeClass("spot").addClass("grown");
element.off("click");
closeButton.on("click", onCloseClick);
}
}
var onCloseClick = function() {
element.removeClass("grown").addClass("spot");
closeButton.off("click");
element.on("click", onElementClick);
}
element.on("click", onElementClick);
In addition I'm adding and removing event handlers.
JSFiddle -> http://jsfiddle.net/zmw9E/1/
You can do like this:
SELECT convert(datetime, convert(date, '27-09-2013', 103), 103)
to scroll till particular element from the message box top checkout the following demo:
https://jsfiddle.net/6smajv0t/
function scrollToBottom(){_x000D_
const messages = document.getElementById('messages');_x000D_
const messagesid = document.getElementById('messagesid'); _x000D_
messages.scrollTop = messagesid.offsetTop - 10;_x000D_
}_x000D_
_x000D_
scrollToBottom();_x000D_
setInterval(scrollToBottom, 1000);
_x000D_
#messages {_x000D_
height: 200px;_x000D_
overflow-y: auto;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="messages">_x000D_
<div class="message">_x000D_
Hello world1_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world2_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world3_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world4_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world5_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world7_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world8_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world9_x000D_
</div>_x000D_
<div class="message" >_x000D_
Hello world10_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world11_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world12_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world13_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world14_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world15_x000D_
</div>_x000D_
<div class="message" id="messagesid">_x000D_
Hello world16 here_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world17_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world18_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world19_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world20_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world21_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world22_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world23_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world24_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world25_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world26_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world27_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world28_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world29_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world30_x000D_
</div>_x000D_
</div>
_x000D_
You actually have to use pow(number, power);. Unfortunately, carats don't work as a power sign in C. Many times, if you find yourself not being able to do something from another language, its because there is a diffetent function that does it for you.
There are no auto incrementing features in Oracle for a column. You need to create a SEQUENCE object. You can use the sequence like:
insert into table(batch_id, ...) values(my_sequence.nextval, ...)
...to return the next number. To find out the last created sequence nr (in your session), you would use:
my_sequence.currval
This site has several complete examples on how to use sequences.
If you're working in a virtual environment (virtualenv), you'll definitely need to update the python.lintint.pylintPath
setting (and probably the python.pythonPath
setting, as well, if you haven't already) if you want linting to work, like this:
// File "settings.json" (workspace-specific one is probably best)
{
// ...
"python.linting.pylintPath": "C:/myproject/venv/Scripts/pylint.exe",
"python.pythonPath": "C:/myproject/venv/Scripts/python.exe",
// ...
}
That's for Windows, but other OSs are similar. The .exe
extension was necessary for it to work for me on Windows, even though it's not required when actually running it in the console.
If you just want to disable it, then use the python.linting.pylintEnabled": false
setting as mentioned in Ben Delaney's answer.
It is Yoda condition writing in different manner
In java
String myString = null;
if (myString.equals("foobar")) { /* ... */ } //Will give u null pointer
yoda condition
String myString = null;
if ("foobar".equals(myString)) { /* ... */ } // will be false
You can also use a fadeIn/FadeOut Combo, too....
$('.test').bind('click', function(){
$('.div1').fadeIn(500);
$('.div2').fadeOut(500);
$('.div3').fadeOut(500);
return false;
});
Use this line to get the division behavior you want:
from __future__ import division
Alternatively, you could use modulus:
if (a % b) == 0: #do something
Both result.class.to_s
and result.class.name
work.
Maybe the uuid module?
In my case changing the ~/.zshenv
did not work. I had to make the changes inside ~/.zshrc
.
I just added:
# Include rbenv for ZSH
export PATH="$HOME/.rbenv/bin:$PATH"
eval "$(rbenv init -)"
at the top of ~/.zshrc
, restarted the shell and logged out.
Check if it worked:
? ~ rbenv install 2.4.0
? ~ rbenv global 2.4.0
? ~ rbenv global
2.4.0
? ~ ruby -v
ruby 2.4.0p0 (2016-12-24 revision 57164) [x86_64-darwin16]
When you're using iOS >= 4
dispatch_async(dispatch_get_main_queue(), ^{
//Your main thread code goes in here
NSLog(@"Im on the main thread");
});
The following code works well (On FireFox, IE and Chrome) :
var display_out = "This is line 1" + "<br>" + "This is line 2";
document.getElementById("demo").innerHTML = display_out;
I couldn't find a simple example about the differences between ES6 and ES5, so I made one. Both code samples create exactly the same object. But the ES5 example also works in older browsers (like IE11), wheres the ES6 example doesn't.
ES6
var matrix = {};
var a = 'one';
var b = 'two';
var c = 'three';
var d = 'four';
matrix[a] = {[b]: {[c]: d}};
ES5
var matrix = {};
var a = 'one';
var b = 'two';
var c = 'three';
var d = 'four';
function addObj(obj, key, value) {
obj[key] = value;
return obj;
}
matrix[a] = addObj({}, b, addObj({}, c, d));
"Exception: Python in worker has different version 2.6 than that in driver 2.7, PySpark cannot run with different minor versions".
Edit this file: /opt/cloudera/parcels/cdh5.5.4.p0.9/lib/spark/conf/spark-env.sh
Add these lines:
export PYSPARK_PYTHON=/usr/bin/python
export PYSPARK_DRIVER_PYTHON=python
You can simply use Arrays.sort()
array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));
Working Example :
var array = [{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"VPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""},},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"adfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"bbfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}}];_x000D_
array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));_x000D_
_x000D_
console.log(array);
_x000D_
Be aware that the line-height
approach fails if you have a long sentence in the span
which breaks the line because there's not enough space. In this case, you would have two lines with a gap with the height of the N pixels specified in the property.
I stuck into it when I wanted to show an image with vertically centered text on its right side which works in a responsive web application. As a base I use the approach suggested by Eric Nickus and Felipe Tadeo.
If you want to achieve:
and this:
.container {_x000D_
background: url( "https://i.imgur.com/tAlPtC4.jpg" ) no-repeat;_x000D_
display: inline-block;_x000D_
background-size: 40px 40px; /* image's size */_x000D_
height: 40px; /* image's height */_x000D_
padding-left: 50px; /* image's width plus 10 px (margin between text and image) */_x000D_
}_x000D_
_x000D_
.container span {_x000D_
height: 40px; /* image's height */_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<span class="container">_x000D_
<span>This is a centered sentence next to an image</span>_x000D_
</span>
_x000D_
From your question it seems like you are using C99, as you have used %lf
for double.
To achieve the desired output replace:
sprintf(aa, "%lf", a);
with
sprintf(aa, "%0.7f", a);
The general syntax "%A.B"
means to use B digits after decimal point. The meaning of the A
is more complicated, but can be read about here.
I had this problem when I installed MySQL 8.0.15 with the community installer. The my.ini file that came with the installer did not work correctly after it had been edited. I did a full manual install by downloading that zip folder. I was able to create my own my.ini file containing only the parameters that I was concerned about and it worked.
include the parameters in that my.ini file that you are concerned about. so something like this(just ensure that there is already a folder created for the datadir or else initialization won't work):
[mysqld]
basedire=C:\program files\MySQL\MySQL8.0
datadir=D:\MySQL\Data
....continue with whatever parameters you want to include
initialize the data directory by running these two commands in the command prompt:
cd C:\program files\MySQL\MySQL8.0\bin
mysqld --default-file=C:\program files\MySQL\MySQL8.0\my.ini --initialize
install the MySQL server as a service by running these two commands:
cd C:\program files\MySQL\MySQL8.0\bin
mysqld --install --default-file=C:\program files\MySQL\MySQL8.0\my.ini
finally, start the server for the first time by running these two commands:
cd C:\program files\MySQL\MySQL8.0\bin
mysqld --console
Check the image above I hope it will help someone.
AngularJS Developer Guide - CSS classes used by AngularJS
- @property {boolean} $untouched True if control has not lost focus yet.
- @property {boolean} $touched True if control has lost focus.
- @property {boolean} $pristine True if user has not interacted with the control yet.
- @property {boolean} $dirty True if user has already interacted with the control.
The documentation on CREATE EVENT is quite good, but it takes a while to get it right.
You have two problems, first, making the event recur, second, making it run at 13:00 daily.
This example creates a recurring event.
CREATE EVENT e_hourly
ON SCHEDULE
EVERY 1 HOUR
COMMENT 'Clears out sessions table each hour.'
DO
DELETE FROM site_activity.sessions;
When in the command-line MySQL client, you can:
SHOW EVENTS;
This lists each event with its metadata, like if it should run once only, or be recurring.
The second problem: pointing the recurring event to a specific schedule item.
By trying out different kinds of expression, we can come up with something like:
CREATE EVENT IF NOT EXISTS `session_cleaner_event`
ON SCHEDULE
EVERY 13 DAY_HOUR
COMMENT 'Clean up sessions at 13:00 daily!'
DO
DELETE FROM site_activity.sessions;
If you use Bootstrap 3, you can use one of it's mixins:
.rotate(degrees);
Example:
.rotate(-90deg);
Try to use single quotes (') to avoid shell escaping of your string. Remember that the expression needs to match the whole path, i.e. needs to look like:
find . -regex '\./[a-f0-9-]*.jpg'
Apart from that, it seems that my find (GNU 4.4.2) only knows basic regular expressions, especially not the {36} syntax. I think you'll have to make do without it.
For a non-commandline approach, you can open the Extensions & Updates window (Tools->Extensions and Updates) and search for the Typescript for Microsoft Visual Studio extension under Installed