The most straight forward answer to this question is: You can't.
Youtube doesn't output their video's in the right format, thus they can't be embedded in a
<video/>
element.
There are a few solutions posted using javascript, but don't trust on those, they all need a fallback, and won't work cross-browser.
Your welcome page is set as That Servlet . So all css , images path should be given relative to that servlet DIR . which is a bad idea ! why do you need the servlet as a home page ? set .jsp as index page and redirect to any page from there ?
are you trying to populate any fields from db is that why you are using servlet ?
i got error related to recaptcha in laravel website, i resolved it by using some command and with env file and above answer will also help in this problem.
first of all check env file(in your case file which has google recaptcha key) for google recpatcha key.
second run these command :
php artisan route:clear
it will solve your problem
SELECT e.*,
cnt.colCount
FROM eventsTable e
INNER JOIN (
select columnName,count(columnName) as colCount
from eventsTable e2
group by columnName
) as cnt on cnt.columnName = e.columnName
WHERE e.columnName='Business'
-- Added space
You can add spring-context dependency for spring jars. You will get the following jars along with it.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
if you also want web components, you can use spring-webmvc dependency.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
You can use whatever version of that you want. I have used 5.0.5.RELEASE here.
To a great extent, that's someone elevating their own weaknesses to a general rule. There's nothing wrong per se with creating objects using the new
operator. What there is some argument for is that you have to do so with some discipline: if you create an object you need to make sure it's going to be destroyed.
The easiest way of doing that is to create the object in automatic storage, so C++ knows to destroy it when it goes out of scope:
{
File foo = File("foo.dat");
// do things
}
Now, observe that when you fall off that block after the end-brace, foo
is out of scope. C++ will call its dtor automatically for you. Unlike Java, you don't need to wait for the GC to find it.
Had you written
{
File * foo = new File("foo.dat");
you would want to match it explicitly with
delete foo;
}
or even better, allocate your File *
as a "smart pointer". If you aren't careful about that it can lead to leaks.
The answer itself makes the mistaken assumption that if you don't use new
you don't allocate on the heap; in fact, in C++ you don't know that. At most, you know that a small amout of memory, say one pointer, is certainly allocated on the stack. However, consider if the implementation of File is something like
class File {
private:
FileImpl * fd;
public:
File(String fn){ fd = new FileImpl(fn);}
then FileImpl
will still be allocated on the stack.
And yes, you'd better be sure to have
~File(){ delete fd ; }
in the class as well; without it, you'll leak memory from the heap even if you didn't apparently allocate on the heap at all.
As an alternative to explicitly catching and handling the exception you could tell Oracle to catch and automatically ignore the exception by including a /*+ hint */
in the insert statement. This is a little faster than explicitly catching the exception and then articulating how it should be handled. It is also easier to setup. The downside is that you do not get any feedback from Oracle that an exception was caught.
Here is an example where we would be selecting from another table, or perhaps an inner query, and inserting the results into a table called TABLE_NAME
which has a unique constraint on a column called IDX_COL_NAME
.
INSERT /*+ ignore_row_on_dupkey_index(TABLE_NAME(IDX_COL_NAME)) */
INTO TABLE_NAME(
INDEX_COL_NAME
, col_1
, col_2
, col_3
, ...
, col_n)
SELECT
INDEX_COL_NAME
, col_1
, col_2
, col_3
, ...
, col_n);
This is not a great solution if your goal it to catch and handle (i.e. print out or update the row that is violating the constraint). But if you just wanted to catch it and ignore the violating row then then this should do the job.
You can write if-else condition inside <% %>
in jsp pages and html code outside of <% %>
For example:
<%
String username = (String)session.getAttribute("username");
if(username==null) {
%>
<p> username is null</p> //html code
<%
} else {
%>
<p> username is not null</p> //html code
<%
}
%>
My problem was that I needed to Reset Window Layout.
The best what and easiest way to get nice var_dump is use xDebug (must have for any php dev) Debian way install
In console: apt-get install php-xdebug
after that you should open php.ini (depends on which stack you use) for it's /etc/php/7.0/fpm/php.ini
Search for display_errors
set same -> display_errors = On
Check html_errors
in same file a little bit below, it's also must be On
Save and exit
After open /etc/php/7.0/fpm/conf.d/20-xdebug.ini
And add to the end: ``` xdebug.cli_color=1
``` Save and exit.
A lot other available option and documentation for xdebug can be founded here.
Good luck and Have Fun !!!
Also, note that there shouldn't be any space after =
:
set JAVA_HOME=C:\Program Files\Java\jdk1.6.0_27
INSERT INTO ... ON DUPLICATE KEY UPDATE will only work for MYSQL, not for SQL Server.
for SQL server, the way to work around this is to first declare a temp table, insert value to that temp table, and then use MERGE
Like this:
declare @Source table
(
name varchar(30),
age decimal(23,0)
)
insert into @Source VALUES
('Helen', 24),
('Katrina', 21),
('Samia', 22),
('Hui Ling', 25),
('Yumie', 29);
MERGE beautiful AS Tg
using @source as Sc
on tg.namet=sc.name
when matched then update
set tg.age=sc.age
when not matched then
insert (name, age) VALUES
(SC.name, sc.age);
No need to use a macro. Supposing your first string is in A1.
=RIGHT(A1, 4)
Drag this down and you will get your four last characters.
Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()
=RIGHT(TRIMSPACES(A1), 4)
Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:
=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))
You can also do this :
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "showError",
"alert('" + ex.Message + "');", true);
}
this will show the exeption message in the alert box
To answer the original question: yes, you can access the index value of a row in apply()
. It is available under the key name
and requires that you specify axis=1
(because the lambda processes the columns of a row and not the rows of a column).
Working example (pandas 0.23.4):
>>> import pandas as pd
>>> df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
>>> df.set_index('a', inplace=True)
>>> df
b c
a
1 2 3
4 5 6
>>> df['index_x10'] = df.apply(lambda row: 10*row.name, axis=1)
>>> df
b c index_x10
a
1 2 3 10
4 5 6 40
assign
is good, but I have not found a function for referring back to the variable you've created in an automated script. (as.name
seems to work the opposite way). More experienced coders will doubtless have a better solution, but this solution works and is slightly humorous perhaps, in that it gets R to write code for itself to execute.
Say I have just assigned value 5 to x
(var.name <- "x"; assign(var.name, 5)
) and I want to change the value to 6. If I am writing a script and don't know in advance what the variable name (var.name
) will be (which seems to be the point of the assign
function), I can't simply put x <- 6
because var.name
might have been "y"
. So I do:
var.name <- "x"
#some other code...
assign(var.name, 5)
#some more code...
#write a script file (1 line in this case) that works with whatever variable name
write(paste0(var.name, " <- 6"), "tmp.R")
#source that script file
source("tmp.R")
#remove the script file for tidiness
file.remove("tmp.R")
x
will be changed to 6, and if the variable name was anything other than "x"
, that variable will similarly have been changed to 6.
To add it as a dependency do the following:
first you need to add 2 columns to datagrid. you may do it at design time. see Columns property. then add rows as much as you need.
this.dataGridView1.Rows.Add("1", "XX");
The following statement appends the value to the element with the id of response
$('#response').append(total);
This makes it look like you are concatenating the strings, but you aren't, you're actually appending them to the element
change that to
$('#response').text(total);
You need to change the drop event so that it replaces the value of the element with the total, you also need to keep track of what the total is, I suggest something like the following
$(function() {
var data = [];
var total = 0;
$( "#draggable1" ).draggable();
$( "#draggable2" ).draggable();
$( "#draggable3" ).draggable();
$("#droppable_box").droppable({
drop: function(event, ui) {
var currentId = $(ui.draggable).attr('id');
data.push($(ui.draggable).attr('id'));
if(currentId == "draggable1"){
var myInt1 = parseFloat($('#MealplanCalsPerServing1').val());
}
if(currentId == "draggable2"){
var myInt2 = parseFloat($('#MealplanCalsPerServing2').val());
}
if(currentId == "draggable3"){
var myInt3 = parseFloat($('#MealplanCalsPerServing3').val());
}
if ( typeof myInt1 === 'undefined' || !myInt1 ) {
myInt1 = parseInt(0);
}
if ( typeof myInt2 === 'undefined' || !myInt2){
myInt2 = parseInt(0);
}
if ( typeof myInt3 === 'undefined' || !myInt3){
myInt3 = parseInt(0);
}
total += parseFloat(myInt1 + myInt2 + myInt3);
$('#response').text(total);
}
});
$('#myId').click(function(event) {
$.post("process.php", ({ id: data }), function(return_data, status) {
alert(data);
//alert(total);
});
});
});
I moved the var total = 0;
statement out of the drop event and changed the assignment statment from this
total = parseFloat(myInt1 + myInt2 + myInt3);
to this
total += parseFloat(myInt1 + myInt2 + myInt3);
Here is a working example http://jsfiddle.net/axrwkr/RCzGn/
You want to do the following:
ALTER TRIGGER [dbo].[tr_SCHEDULE_Modified]
ON [dbo].[SCHEDULE]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
IF (UPDATE(QtyToRepair))
BEGIN
UPDATE SCHEDULE SET modified = GETDATE()
, ModifiedUser = SUSER_NAME()
, ModifiedHost = HOST_NAME()
FROM SCHEDULE S
INNER JOIN Inserted I ON S.OrderNo = I.OrderNo AND S.PartNumber = I.PartNumber
WHERE S.QtyToRepair <> I.QtyToRepair
END
END
Please note that this trigger will fire each time you update the column no matter if the value is the same or not.
REPLACE INTO
pros:
cons:
too slow.
auto-increment key will CHANGE(increase by 1) if there is entry matches unique key
or primary key
, because it deletes the old entry then insert new one.
INSERT IGNORE
pros:
cons:
auto-increment key will not change if there is entry matches unique key
or primary key
but auto-increment index will increase by 1
some other errors/warnings will be ignored such as data conversion error.
INSERT ... ON DUPLICATE KEY UPDATE
pros:
cons:
looks relatively complex if you just want to insert not update.
auto-increment key will not change if there is entry matches unique key
or primary key
but auto-increment index will increase by 1
unique key
or primary key
?As mentioned in the comment below by @toien: "auto-increment column will be effected depends on innodb_autoinc_lock_mode
config after version 5.1" if you are using innodb
as your engine, but this also effects concurrency, so it needs to be well considered before used. So far I'm not seeing any better solution.
If you are on Windows, you can use the CreateThreadpoolTimer function to schedule a callback without needing to worry about thread management and without blocking the current thread.
template<typename T>
static void __stdcall timer_fired(PTP_CALLBACK_INSTANCE, PVOID context, PTP_TIMER timer)
{
CloseThreadpoolTimer(timer);
std::unique_ptr<T> callable(reinterpret_cast<T*>(context));
(*callable)();
}
template <typename T>
void call_after(T callable, long long delayInMs)
{
auto state = std::make_unique<T>(std::move(callable));
auto timer = CreateThreadpoolTimer(timer_fired<T>, state.get(), nullptr);
if (!timer)
{
throw std::runtime_error("Timer");
}
ULARGE_INTEGER due;
due.QuadPart = static_cast<ULONGLONG>(-(delayInMs * 10000LL));
FILETIME ft;
ft.dwHighDateTime = due.HighPart;
ft.dwLowDateTime = due.LowPart;
SetThreadpoolTimer(timer, &ft, 0 /*msPeriod*/, 0 /*msWindowLength*/);
state.release();
}
int main()
{
auto callback = []
{
std::cout << "in callback\n";
};
call_after(callback, 1000);
std::cin.get();
}
change the data type to another one which uses less memory works. For me, I change the data type to numpy.uint8:
data['label'] = data['label'].astype(np.uint8)
private static ISheet GetFileStream(string fullFilePath)
{
var fileExtension = Path.GetExtension(fullFilePath);
string sheetName;
ISheet sheet = null;
switch (fileExtension)
{
case ".xlsx":
using (var fs = new FileStream(fullFilePath, FileMode.Open, FileAccess.Read))
{
var wb = new XSSFWorkbook(fs);
sheetName = wb.GetSheetAt(0).SheetName;
sheet = (XSSFSheet) wb.GetSheet(sheetName);
}
break;
case ".xls":
using (var fs = new FileStream(fullFilePath, FileMode.Open, FileAccess.Read))
{
var wb = new HSSFWorkbook(fs);
sheetName = wb.GetSheetAt(0).SheetName;
sheet = (HSSFSheet) wb.GetSheet(sheetName);
}
break;
}
return sheet;
}
private static DataTable GetRequestsDataFromExcel(string fullFilePath)
{
try
{
var sh = GetFileStream(fullFilePath);
var dtExcelTable = new DataTable();
dtExcelTable.Rows.Clear();
dtExcelTable.Columns.Clear();
var headerRow = sh.GetRow(0);
int colCount = headerRow.LastCellNum;
for (var c = 0; c < colCount; c++)
dtExcelTable.Columns.Add(headerRow.GetCell(c).ToString());
var i = 1;
var currentRow = sh.GetRow(i);
while (currentRow != null)
{
var dr = dtExcelTable.NewRow();
for (var j = 0; j < currentRow.Cells.Count; j++)
{
var cell = currentRow.GetCell(j);
if (cell != null)
switch (cell.CellType)
{
case CellType.Numeric:
dr[j] = DateUtil.IsCellDateFormatted(cell)
? cell.DateCellValue.ToString(CultureInfo.InvariantCulture)
: cell.NumericCellValue.ToString(CultureInfo.InvariantCulture);
break;
case CellType.String:
dr[j] = cell.StringCellValue;
break;
case CellType.Blank:
dr[j] = string.Empty;
break;
}
}
dtExcelTable.Rows.Add(dr);
i++;
currentRow = sh.GetRow(i);
}
return dtExcelTable;
}
catch (Exception e)
{
throw;
}
}
Add ID current
for active/current page:
<div class="menuBar">
<ul>
<li id="current"><a href="index.php">HOME</a></li>
<li><a href="two.php">PORTFOLIO</a></li>
<li><a href="three.php">ABOUT</a></li>
<li><a href="four.php">CONTACT</a></li>
<li><a href="five.php">SHOP</a></li>
</ul>
#current a { color: #ff0000; }
There is no such thing for HashMaps, but you can create an ImmutableMap with a builder:
final Map<String, Integer> m = ImmutableMap.<String, Integer>builder().
put("a", 1).
put("b", 2).
build();
And if you need a mutable map, you can just feed that to the HashMap constructor.
final Map<String, Integer> m = Maps.newHashMap(
ImmutableMap.<String, Integer>builder().
put("a", 1).
put("b", 2).
build());
In openCV whenever you try to display an oversized image or image bigger than your display resolution you get the cropped display. It's a default behaviour.
In order to view the image in the window of your choice openCV encourages to use named window. Please refer to namedWindow documentation
The function namedWindow creates a window that can be used as a placeholder for images and trackbars. Created windows are referred to by their names.
cv.namedWindow(name, flags=CV_WINDOW_AUTOSIZE)
where each window is related to image container by the name arg, make sure to use same name
eg:
import cv2
frame = cv2.imread('1.jpg')
cv2.namedWindow("Display 1")
cv2.resizeWindow("Display 1", 300, 300)
cv2.imshow("Display 1", frame)
This works for me
sed '/^all:/ s/$/ anotherthing/' file
The first part is a pattern to find and the second part is an ordinary sed's substitution using $
for the end of a line.
If you want to change the file during the process, use -i
option
sed -i '/^all:/ s/$/ anotherthing/' file
Or you can redirect it to another file
sed '/^all:/ s/$/ anotherthing/' file > output
A little bit late, but you can request a higher quote here: https://support.google.com/youtube/contact/yt_api_form
I haven't studied yet, when Maven does which look-up, but to get stable and reproducible builds, I strongly recommend not to access Maven Respositories directly but to use a Maven Repository Manager such as Nexus.
Here is the tutorial how to set up your settings file:
http://books.sonatype.com/nexus-book/reference/maven-sect-single-group.html
I had a similar problem. I wished to colour a complex drawable background for a view based on a color (int) value. I succeeded by using the code:
ColorStateList csl = new ColorStateList(new int[][]{{}}, new int[]{color});
textView.setBackgroundTintList(csl);
Where color is an int value representing the colour required. This represents the simple xml ColorStateList:
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:color="color here"/>
</selector>
Hope this helps.
The best way around browsercaches is to append a random number to the path of the js file.
Example in pseudo code:
// generate a random number
int i = Random.Next();
echo "<script src='a.js?'" + i + "></script>";
This will make sure your browser always reloads the file, because it thinks it's a different file because of the random number in the url.
The server will always return the file and ignore what comes after the '?'.
Also if you run pytest
within your virtual environment make sure pytest
module is installed within your virtual environment. Activate your virtual env and run pip install pytest
.
ssh-keygen isn't a windows executable.
You can use PuttyGen (http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html) for example to create a key
This is how I did it.
from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--disable-extensions')
chrome = webdriver.Chrome(chrome_options=chrome_options)
Using 'now()' as default value automatically generates time-stamp.
My answer is very similar to the one from @biscoop, but I am going to elaborate a bit as it may apply to the question or to other people.
I had a .xls that was an extraction from one of our webapps. The Excel connection would not work (error message: "no tables or views could be loaded"). As a side note, when opening the file, there would be a warning stating that the file was from an online source and that the content needed activation.
I tried to save the same file as an .xlsx and it worked. I tried to save the same file with another name as an .xls and it worked too. So as a last test I only opened the source .xls file, clicking save and the connection worked.
Short answer: just try and see if opening the file and saving does the trick.
const params = new URLSearchParams(location.search)
params.delete('key_to_delete')
console.log(params.toString())
There's no need to do this in two commits, you can add the file and mark it executable in a single commit:
C:\Temp\TestRepo>touch foo.sh
C:\Temp\TestRepo>git add foo.sh
C:\Temp\TestRepo>git ls-files --stage
100644 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 0 foo.sh
As you note, after adding, the mode is 0644 (ie, not executable). However, we can mark it as executable before committing:
C:\Temp\TestRepo>git update-index --chmod=+x foo.sh
C:\Temp\TestRepo>git ls-files --stage
100755 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 0 foo.sh
And now the file is mode 0755 (executable).
C:\Temp\TestRepo>git commit -m"Executable!"
[master (root-commit) 1f7a57a] Executable!
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100755 foo.sh
And now we have a single commit with a single executable file.
type in Terminal:
$ mvn --version
then get following result:
Apache Maven 3.0.5 (r01de14724cdef164cd33c7c8c2fe155faf9602da; 2013-02-19 16:51:28+0300)
Maven home: /opt/local/share/java/maven3
Java version: 1.6.0_65, vendor: Apple Inc.
Java home: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Default locale: ru_RU, platform encoding: MacCyrillic
OS name: "mac os x", version: "10.9.4", arch: "x86_64", family: "mac"
here in second line we have:
Maven home: /opt/local/share/java/maven3
type this path into field on configuration dialog. That's all to fix!
Atomic collections are accessible by $
Recursive collections are not. Rather the [[ ]]
is used
Browse[1]> is.atomic(list())
[1] FALSE
Browse[1]> is.atomic(data.frame())
[1] FALSE
Browse[1]> is.atomic(class(list(foo="bar")))
[1] TRUE
Browse[1]> is.atomic(c(" lang "))
[1] TRUE
R can be funny sometimes
a = list(1,2,3)
b = data.frame(a)
d = rbind("?",c(b))
e = exp(1)
f = list(d)
print(data.frame(c(list(f,e))))
X1 X2 X3 X2.71828182845905
1 ? ? ? 2.718282
2 1 2 3 2.718282
Bundle was failing to install json -v '1.8.1' and deleting my Gemfile.lock and running bundle again solved this issue for me.
I already have used Reportlab in one project.
You set the CSS to :
#elementID {
background: black url(http://www.electrictoolbox.com/images/rangitoto-3072x200.jpg) center no-repeat;
height: 200px;
}
It centers the image, but does not scale it.
In newer browsers you can use the background-size
property and do:
#elementID {
height: 200px;
width: 100%;
background: black url(http://www.electrictoolbox.com/images/rangitoto-3072x200.jpg) no-repeat;
background-size: 100% 100%;
}
Other than that, a regular image is one way to do it, but then it's not really a background image.
?
In EDIT 2:
while((line = bufferedReader.readLine()) != null)
{
sb.append(line); //append the lines to the string
sb.append('\n'); //append new line
} //end while
you are reading the text file, and appending a newline to it. Don't append newline, which will not show a newline in some simple-minded Windows editors like Notepad. Instead append the OS-specific line separator string using:
sb.append(System.lineSeparator());
(for Java 1.7 and 1.8)
or
sb.append(System.getProperty("line.separator"));
(Java 1.6 and below)
Alternatively, later you can use String.replaceAll()
to replace "\n"
in the string built in the StringBuffer with the OS-specific newline character:
String updatedText = text.replaceAll("\n", System.lineSeparator())
but it would be more efficient to append it while you are building the string, than append '\n'
and replace it later.
Finally, as a developer, if you are using notepad for viewing or editing files, you should drop it, as there are far more capable tools like Notepad++, or your favorite Java IDE.
I couldn't think of a way to do this efficiently either but I came up with this. It works, for the limited uses below.
shrug
<?php
function varName( $v ) {
$trace = debug_backtrace();
$vLine = file( __FILE__ );
$fLine = $vLine[ $trace[0]['line'] - 1 ];
preg_match( "#\\$(\w+)#", $fLine, $match );
print_r( $match );
}
$foo = "knight";
$bar = array( 1, 2, 3 );
$baz = 12345;
varName( $foo );
varName( $bar );
varName( $baz );
?>
// Returns
Array
(
[0] => $foo
[1] => foo
)
Array
(
[0] => $bar
[1] => bar
)
Array
(
[0] => $baz
[1] => baz
)
It works based on the line that called the function, where it finds the argument you passed in. I suppose it could be expanded to work with multiple arguments but, like others have said, if you could explain the situation better, another solution would probably work better.
I've created a custom PagerAdapters library to change items in PagerAdapters dynamically.
You can change items dynamically like following by using this library.
@Override
protected void onCreate(Bundle savedInstanceState) {
/** ... **/
adapter = new MyStatePagerAdapter(getSupportFragmentManager()
, new String[]{"1", "2", "3"});
((ViewPager)findViewById(R.id.view_pager)).setAdapter(adapter);
adapter.add("4");
adapter.remove(0);
}
class MyPagerAdapter extends ArrayViewPagerAdapter<String> {
public MyPagerAdapter(String[] data) {
super(data);
}
@Override
public View getView(LayoutInflater inflater, ViewGroup container, String item, int position) {
View v = inflater.inflate(R.layout.item_page, container, false);
((TextView) v.findViewById(R.id.item_txt)).setText(item);
return v;
}
}
Thils library also support pages created by Fragments.
CultureInfo us = new CultureInfo("en-US");
TotalAmount.ToString("N", us)
I have at least one situation where the data is not automatically cleaned up, which would eventually lead to "Out of Memory" errors. In a UserForm I had:
Public mainPicture As StdPicture
...
mainPicture = LoadPicture(PAGE_FILE)
When UserForm was destroyed (after Unload Me
) the memory allocated for the data loaded in the mainPicture
was not being de-allocated. I had to add an explicit
mainPicture = Nothing
in the terminate event.
You need to encode your parameter's values before concatenating them to URL.
Backslash \
is special character which have to be escaped as %5C
Escaping example:
String paramValue = "param\\with\\backslash";
String yourURLStr = "http://host.com?param=" + java.net.URLEncoder.encode(paramValue, "UTF-8");
java.net.URL url = new java.net.URL(yourURLStr);
The result is http://host.com?param=param%5Cwith%5Cbackslash
which is properly formatted url string.
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).
This code:
from scipy.stats import linregress
linregress(x,y) #x and y are arrays or lists.
gives out a list with the following:
slope : float
slope of the regression line
intercept : float
intercept of the regression line
r-value : float
correlation coefficient
p-value : float
two-sided p-value for a hypothesis test whose null hypothesis is that the slope is zero
stderr : float
Standard error of the estimate
Instant
and LocalDateTime
are two entirely different animals: One represents a moment, the other does not.
Instant
represents a moment, a specific point in the timeline.LocalDateTime
represents a date and a time-of-day. But lacking a time zone or offset-from-UTC, this class cannot represent a moment. It represents potential moments along a range of about 26 to 27 hours, the range of all time zones around the globe. A LocalDateTime
value is inherently ambiguous.
LocalDateTime
is rather date/clock representation including time-zones for humans.
Your statement is incorrect: A LocalDateTime
has no time zone. Having no time zone is the entire point of that class.
To quote that class’ doc:
This class does not store or represent a time-zone. Instead, it is a description of the date, as used for birthdays, combined with the local time as seen on a wall clock. It cannot represent an instant on the time-line without additional information such as an offset or time-zone.
So Local…
means “not zoned, no offset”.
Instant
An Instant
is a moment on the timeline in UTC, a count of nanoseconds since the epoch of the first moment of 1970 UTC (basically, see class doc for nitty-gritty details). Since most of your business logic, data storage, and data exchange should be in UTC, this is a handy class to be used often.
Instant instant = Instant.now() ; // Capture the current moment in UTC.
OffsetDateTime
The class OffsetDateTime
class represents a moment as a date and time with a context of some number of hours-minutes-seconds ahead of, or behind, UTC. The amount of offset, the number of hours-minutes-seconds, is represented by the ZoneOffset
class.
If the number of hours-minutes-seconds is zero, an OffsetDateTime
represents a moment in UTC the same as an Instant
.
ZoneOffset
The ZoneOffset
class represents an offset-from-UTC, a number of hours-minutes-seconds ahead of UTC or behind UTC.
A ZoneOffset
is merely a number of hours-minutes-seconds, nothing more. A zone is much more, having a name and a history of changes to offset. So using a zone is always preferable to using a mere offset.
ZoneId
A time zone is represented by the ZoneId
class.
A new day dawns earlier in Paris than in Montréal, for example. So we need to move the clock’s hands to better reflect noon (when the Sun is directly overhead) for a given region. The further away eastward/westward from the UTC line in west Europe/Africa the larger the offset.
A time zone is a set of rules for handling adjustments and anomalies as practiced by a local community or region. The most common anomaly is the all-too-popular lunacy known as Daylight Saving Time (DST).
A time zone has the history of past rules, present rules, and rules confirmed for the near future.
These rules change more often than you might expect. Be sure to keep your date-time library's rules, usually a copy of the 'tz' database, up to date. Keeping up-to-date is easier than ever now in Java 8 with Oracle releasing a Timezone Updater Tool.
Specify a proper time zone name in the format of Continent/Region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 2-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
Time Zone = Offset + Rules of Adjustments
ZoneId z = ZoneId.of( “Africa/Tunis” ) ;
ZonedDateTime
Think of ZonedDateTime
conceptually as an Instant
with an assigned ZoneId
.
ZonedDateTime = ( Instant + ZoneId )
To capture the current moment as seen in the wall-clock time used by the people of a particular region (a time zone):
ZonedDateTime zdt = ZonedDateTime.now( z ) ; // Pass a `ZoneId` object such as `ZoneId.of( "Europe/Paris" )`.
Nearly all of your backend, database, business logic, data persistence, data exchange should all be in UTC. But for presentation to users you need to adjust into a time zone expected by the user. This is the purpose of the ZonedDateTime
class and the formatter classes used to generate String representations of those date-time values.
ZonedDateTime zdt = instant.atZone( z ) ;
String output = zdt.toString() ; // Standard ISO 8601 format.
You can generate text in localized format using DateTimeFormatter
.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( Locale.CANADA_FRENCH ) ;
String outputFormatted = zdt.format( f ) ;
mardi 30 avril 2019 à 23 h 22 min 55 s heure de l’Inde
LocalDate
, LocalTime
, LocalDateTime
The "local" date time classes, LocalDateTime
, LocalDate
, LocalTime
, are a different kind of critter. The are not tied to any one locality or time zone. They are not tied to the timeline. They have no real meaning until you apply them to a locality to find a point on the timeline.
The word “Local” in these class names may be counter-intuitive to the uninitiated. The word means any locality, or every locality, but not a particular locality.
So for business apps, the "Local" types are not often used as they represent just the general idea of a possible date or time not a specific moment on the timeline. Business apps tend to care about the exact moment an invoice arrived, a product shipped for transport, an employee was hired, or the taxi left the garage. So business app developers use Instant
and ZonedDateTime
classes most commonly.
So when would we use LocalDateTime
? In three situations:
Notice that none of these three cases involve a single certain specific point on the timeline, none of these are a moment.
Sometimes we want to represent a certain time-of-day on a certain date, but want to apply that into multiple localities across time zones.
For example, "Christmas starts at midnight on the 25th of December 2015" is a LocalDateTime
. Midnight strikes at different moments in Paris than in Montréal, and different again in Seattle and in Auckland.
LocalDate ld = LocalDate.of( 2018 , Month.DECEMBER , 25 ) ;
LocalTime lt = LocalTime.MIN ; // 00:00:00
LocalDateTime ldt = LocalDateTime.of( ld , lt ) ; // Christmas morning anywhere.
Another example, "Acme Company has a policy that lunchtime starts at 12:30 PM at each of its factories worldwide" is a LocalTime
. To have real meaning you need to apply it to the timeline to figure the moment of 12:30 at the Stuttgart factory or 12:30 at the Rabat factory or 12:30 at the Sydney factory.
Another situation to use LocalDateTime
is for booking future events (ex: Dentist appointments). These appointments may be far enough out in the future that you risk politicians redefining the time zone. Politicians often give little forewarning, or even no warning at all. If you mean "3 PM next January 23rd" regardless of how the politicians may play with the clock, then you cannot record a moment – that would see 3 PM turn into 2 PM or 4 PM if that region adopted or dropped Daylight Saving Time, for example.
For appointments, store a LocalDateTime
and a ZoneId
, kept separately. Later, when generating a schedule, on-the-fly determine a moment by calling LocalDateTime::atZone( ZoneId )
to generate a ZonedDateTime
object.
ZonedDateTime zdt = ldt.atZone( z ) ; // Given a date, a time-of-day, and a time zone, determine a moment, a point on the timeline.
If needed, you can adjust to UTC. Extract an Instant
from the ZonedDateTime
.
Instant instant = zdt.toInstant() ; // Adjust from some zone to UTC. Same moment, same point on the timeline, different wall-clock time.
Some people might use LocalDateTime
in a situation where the time zone or offset is unknown.
I consider this case inappropriate and unwise. If a zone or offset is intended but undetermined, you have bad data. That would be like storing a price of a product without knowing the intended currency (dollars, pounds, euros, etc.). Not a good idea.
For completeness, here is a table of all the possible date-time types, both modern and legacy in Java, as well as those defined by the SQL standard. This might help to place the Instant
& LocalDateTime
classes in a larger context.
Notice the odd choices made by the Java team in designing JDBC 4.2. They chose to support all the java.time times… except for the two most commonly used classes: Instant
& ZonedDateTime
.
But not to worry. We can easily convert back and forth.
Converting Instant
.
// Storing
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
myPreparedStatement.setObject( … , odt ) ;
// Retrieving
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
Instant instant = odt.toInstant() ;
Converting ZonedDateTime
.
// Storing
OffsetDateTime odt = zdt.toOffsetDateTime() ;
myPreparedStatement.setObject( … , odt ) ;
// Retrieving
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = odt.atZone( z ) ;
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
To delete all derived data and the module cache in /var/folders
use this little ruby script.
derivedDataFolder = Dir.glob(Dir.home + "/Library/Developer/Xcode/DerivedData/*")
moduleCache = Dir.glob("/var/folders/**/com.apple.DeveloperTools*")
FileUtils.rm_rf derivedDataFolder + moduleCache
This just solved a fatal error: malformed or corrupted AST file: 'Unable to load module "/var/folders/
error for me.
You can find the min/max index and value at the same time if you enumerate the items in the list, but perform min/max on the original values of the list. Like so:
import operator
min_index, min_value = min(enumerate(values), key=operator.itemgetter(1))
max_index, max_value = max(enumerate(values), key=operator.itemgetter(1))
This way the list will only be traversed once for min (or max).
Just stumbled upon this and thought I would suggest my solution. I typically like to use the built in functionality of assigning a range to an multi-dim array (I guess it's also the JS Programmer in me).
I frequently write code like this:
Sub arrayBuilder()
myarray = Range("A1:D4")
'unlike most VBA Arrays, this array doesn't need to be declared and will be automatically dimensioned
For i = 1 To UBound(myarray)
For j = 1 To UBound(myarray, 2)
Debug.Print (myarray(i, j))
Next j
Next i
End Sub
Assigning ranges to variables is a very powerful way to manipulate data in VBA.
Try below code. Worked in my case. Hope this helps!
select id,total_Hour,
(coalesce(weekday_1,0)+coalesce(weekday_2,0)+coalesce(weekday_3,0)) as weekday_Listing_Hrs,
(coalesce(weekend_1,0)+coalesce(weekend_2,0)+coalesce(weekend_3,0)) as weekend_Listing_Hrs
from
select *,
listing_duration_Hour-(coalesce(weekday_1,0)+coalesce(weekday_2,0)+coalesce(weekday_3,0)+coalesce(weekend_1,0)+coalesce(weekend_2,0)) as weekend_3
from
(
select * ,
case when date(Start_Date) = date(End_Date) and weekday(Start_Date) in (0,1,2,3,4)
then timestampdiff(hour,Start_Date,End_Date)
when date(Start_Date) != date(End_Date) and weekday(Start_Date) in (0,1,2,3,4)
then 24-timestampdiff(hour,date(Start_Date),Start_Date)
end as weekday_1,
case when date(Start_Date) != date(End_Date) and weekday(End_Date) in (0,1,2,3,4)
then timestampdiff(hour,date(End_Date),End_Date)
end as weekday_2,
case when date(Start_Date) != date(End_Date) then
(5*(DATEDIFF(date(End_Date),adddate(date(Start_Date),+1)) DIV 7) +
MID('0123455501234445012333450122234501101234000123450',7 * WEEKDAY(adddate(date(Start_Date),+1))
+ WEEKDAY(date(End_Date)) + 1, 1))* 24 end as weekday_3,
case when date(Start_Date) = date(End_Date) and weekday(Start_Date) in (5,6)
then timestampdiff(hour,Start_Date,End_Date)
when date(Start_Date) != date(End_Date) and weekday(Start_Date) in (5,6)
then 24-timestampdiff(hour,date(Start_Date),Start_Date)
end as weekend_1,
case when date(Start_Date) != date(End_Date) and weekday(End_Date) in (5,6)
then timestampdiff(hour,date(End_Date),End_Date)
end as weekend_2
from
TABLE_1
)
There is a pure CSS solution I'm currently using.
Add a body ID (or class) identifying your pages and your menu items, then use something like:
HTML:
<html>
<body id="body_questions">
<ul class="menu">
<li id="questions">Question</li>
<li id="tags">Tags</li>
<li id="users">Users</li>
</ul>
...
</body>
</html>
CSS:
.menu li:hover,
#body_questions #questions,
#body_tags #tags,
#body_users #users {
background-color: #f90;
}
Just use Kotlin!
val list = listOf(user1, user2, user3)
val maxDate = list.maxBy { it.date }?.date
You need additional plugin for this.
take a look at this plugin
os.path
works in a funny way. It looks like os
should be a package with a submodule path
, but in reality os
is a normal module that does magic with sys.modules
to inject os.path
. Here's what happens:
When Python starts up, it loads a bunch of modules into sys.modules
. They aren't bound to any names in your script, but you can access the already-created modules when you import them in some way.
sys.modules
is a dict in which modules are cached. When you import a module, if it already has been imported somewhere, it gets the instance stored in sys.modules
.os
is among the modules that are loaded when Python starts up. It assigns its path
attribute to an os-specific path module.
It injects sys.modules['os.path'] = path
so that you're able to do "import os.path
" as though it was a submodule.
I tend to think of os.path
as a module I want to use rather than a thing in the os
module, so even though it's not really a submodule of a package called os
, I import it sort of like it is one and I always do import os.path
. This is consistent with how os.path
is documented.
Incidentally, this sort of structure leads to a lot of Python programmers' early confusion about modules and packages and code organization, I think. This is really for two reasons
If you think of os
as a package and know that you can do import os
and have access to the submodule os.path
, you may be surprised later when you can't do import twisted
and automatically access twisted.spread
without importing it.
It is confusing that os.name
is a normal thing, a string, and os.path
is a module. I always structure my packages with empty __init__.py
files so that at the same level I always have one type of thing: a module/package or other stuff. Several big Python projects take this approach, which tends to make more structured code.
It means it's searching for a function that needs to be completed.
else if(val == sorted[mid]) return mid;
so, remove the if() part and modify the code or add an else() at the end which returns an int.
The event IDs to look for in pre-Vista Windows are 528, 538, and 680. 528 usually stands for successful unlock of workstation.
The codes for newer Windows versions differ, see below answers for more infos.
Use the code below:
using Newtonsoft.Json;
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(ds.Tables[0]);
Issue: 'id1' is missing in props validation, eslintreact/prop-types
<div id={props.id1} >
...
</div>
Below solution worked, in a function component:
let { id1 } = props;
<div id={id1} >
...
</div>
Hope that helps.
I don't know of any out-of-the-box way to achieve this. As you say, this is not how SharePoint lists are intended used. It might work to create a custom site column displaying the path to the document, as this might be used in a filter. Have never tried it, though.
If you give each of these instances a class you can use
$('.yourClass').upload()
I'm still not sure what caused that extra space at the top, but I found that deleting the UITableView with the space and replacing it with a new one took the space away.
I must have dragged a UIView in there accidentally, but I couldn't select it so I couldn't delete.
Imperative programming style was practiced in web development from 2005 all the way to 2013.
With imperative programming, we wrote out code that listed exactly what our application should do, step by step.
The functional programming style produces abstraction through clever ways of combining functions.
There is mention of declarative programming in the answers and regarding that I will say that declarative programming lists out some rules that we are to follow. We then provide what we refer to as some initial state to our application and we let those rules kind of define how the application behaves.
Now, these quick descriptions probably don’t make a lot of sense, so lets walk through the differences between imperative and declarative programming by walking through an analogy.
Imagine that we are not building software, but instead we bake pies for a living. Perhaps we are bad bakers and don’t know how to bake a delicious pie the way we should.
So our boss gives us a list of directions, what we know as a recipe.
The recipe will tell us how to make a pie. One recipe is written in an imperative style like so:
The declarative recipe would do the following:
1 cup of flour, 1 egg, 1 cup of sugar - initial State
Rules
So imperative approaches are characterized by step by step approaches. You start with step one and go to step 2 and so on.
You eventually end up with some end product. So making this pie, we take these ingredients mix them, put it in a pan and in the oven and you got your end product.
In a declarative world, its different.In the declarative recipe we would separate our recipe into two separate parts, start with one part that lists the initial state of the recipe, like the variables. So our variables here are the quantities of our ingredients and their type.
We take the initial state or initial ingredients and apply some rules to them.
So we take the initial state and pass them through these rules over and over again until we get a ready to eat rhubarb strawberry pie or whatever.
So in a declarative approach, we have to know how to properly structure these rules.
So the rules we might want to examine our ingredients or state, if mixed, put them in a pan.
With our initial state, that doesn’t match because we haven’t yet mixed our ingredients.
So rule 2 says, if they not mixed then mix them in a bowl. Okay yeah this rule applies.
Now we have a bowl of mixed ingredients as our state.
Now we apply that new state to our rules again.
So rule 1 says if ingredients are mixed place them in a pan, okay yeah now rule 1 does apply, lets do it.
Now we have this new state where the ingredients are mixed and in a pan. Rule 1 is no longer relevant, rule 2 does not apply.
Rule 3 says if the ingredients are in a pan, place them in the oven, great that rule is what applies to this new state, lets do it.
And we end up with a delicious hot apple pie or whatever.
Now, if you are like me, you may be thinking, why are we not still doing imperative programming. This makes sense.
Well, for simple flows yes, but most web applications have more complex flows that cannot be properly captured by imperative programming design.
In a declarative approach, we may have some initial ingredients or initial state like textInput=“”
, a single variable.
Maybe text input starts off as an empty string.
We take this initial state and apply it to a set of rules defined in your application.
If a user enters text, update text input. Well, right now that doesn’t apply.
If template is rendered, calculate the widget.
Well, none of this applies so the program will just wait around for an event to happen.
So at some point a user updates the text input and then we might apply rule number 1.
We may update that to “abcd”
So we just updated our text and textInput updates, rule number 2 does not apply, rule number 3 says if text input is update, which just occurred, then re render the template and then we go back to rule 2 thats says if template is rendered, calculate the widget, okay lets calculate the widget.
In general, as programmers, we want to strive for more declarative programming designs.
Imperative seems more clear and obvious, but a declarative approach scales very nicely for larger applications.
Those who are facing this problem: Don't panic.
Short answer:
Restart your router, and this problem will be fixed. (But if your restart button is not working, you need to do a nine-step process to do the restart. Hitting the restart button is just one of them.)
Long answer: Let's learn how to restart the router.
telnet 192.168.1.1
Run these commands:
mount_root ## this remounts your partitions from read-only to read/write mode
firstboot ## This will reset your router after reboot
reboot -f ## And force reboot
Log in the web interface using web browser.
link to see the official failsafe mode.
It's now builtin in MySQL 8.0 and MariaDB 10.2:
SELECT
itemID, COUNT(*) as ordercount,
ROW_NUMBER OVER (PARTITION BY itemID ORDER BY rank DESC) as rank
FROM orders
GROUP BY itemID ORDER BY rank DESC
On my PC, xcopy and robocopy need also the path to them, i.e. C:\Windows\System32\xcopy.exe
That's why I use simply "copy": copy /y ....\Folder1\File.txt ....\Folder2\
go to the AndroidManifest.xml and replace
android:theme="@style/AppTheme"
by
android:theme="@android:style/Theme.Holo.Light.DarkActionBar"
SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE IN ('FUNCTION','PROCEDURE','PACKAGE')
The column STATUS tells you whether the object is VALID or INVALID. If it is invalid, you have to try a recompile, ORACLE can't tell you if it will work before.
Convert ArrayList to JsonArray : Like these [{"title":"value1"}, {"title":"value2"}]
Example below :
Model class having one param title and override toString method
class Model(
var title: String,
var id: Int = -1
){
override fun toString(): String {
return "{\"title\":\"$title\"}"
}
}
create List of model class and print toString
var list: ArrayList<Model>()
list.add("value1")
list.add("value2")
Log.d(TAG, list.toString())
and Here is your output
[{"title":"value1"}, {"title":"value2"}]
echo -e "YOURPASSWORD\n" | sudo -S yourcommand
I got this error today whilst trying to initiate a slide effect on a div. Thanks to the answer from 'I Hate Lazy' above (which I've upvoted), I went looking for a custom jQuery UI script, and you can in fact build your own file directly on the jQuery ui website http://jqueryui.com/download/. All you have to do is mark the effect(s) that you're looking for and then download.
I was looking for the slide effect. So I first unchecked all the checkboxes, then clicked on the 'slide effect' checkbox and the page automatically then checks those other components necessary to make the slide effect work. Very simple.
easeOutBounce is an easing effect, for which you'll need to check the 'Effects Core' checkbox.
I've made a mistake in the last my post. This is working example for how to pass additional argument in callback function:
function custom_func(p1,p2) {
$.post(AJAX_FILE_PATH,{op:'dosomething',p1:p1},
function(data){
return function(){
alert(data);
alert(p2);
}(data,p2)
}
);
return false;
}
You'll want to include double quotes (") before and after the imageUrl like this:
$('myOjbect').css('background-image', 'url("' + imageUrl + '")');
This way, if the image has spaces it will still be set as a property.
Your constructor is expecting one parameter (data). You're not passing it in the call. I guess you wanted to initialise a field in the object. That would look like this:
class DHT:
def __init__(self):
self.data = {}
self.data['one'] = '1'
self.data['two'] = '2'
self.data['three'] = '3'
def showData(self):
print(self.data)
if __name__ == '__main__':
DHT().showData()
Or even just:
class DHT:
def __init__(self):
self.data = {'one': '1', 'two': '2', 'three': '3'}
def showData(self):
print(self.data)
Use asymptote instead!
This is what it can look like:
https://asymptote.sourceforge.io/gallery/3Dgraphs/helix.html
This is the code: https://asymptote.sourceforge.io/gallery/3Dgraphs/helix.asy
Asymptote can also read in data files.
And the full gallery: https://asymptote.sourceforge.io/gallery/index.html
To use asymptote from within Python:
https://ctan.org/tex-archive/graphics/asymptote/base/asymptote.py
Nobody mentioned it, but Putty scp (pscp) has a -pw option for password.
Documentation can be found here: https://the.earth.li/~sgtatham/putty/0.67/htmldoc/Chapter5.html#pscp
Basically, window event may not be assigned to MVVM. In general, the Close button show a Dialog box to ask the user "save : yes/no/cancel", and this may not be achieved by the MVVM.
You may keep the OnClosing event handler, where you call the Model.Close.CanExecute() and set the boolean result in the event property. So after the CanExecute() call if true, OR in the OnClosed event, call the Model.Close.Execute()
In SQL Server 2008 you can use Change Data Capture for this. Details of how to set it up on a table are here http://msdn.microsoft.com/en-us/library/cc627369.aspx
This is impossible to answer and has been brought up many many times before. Do a search, read those threads, then pick the framework you and your team have experience with.
The top answer doesn't work for PHP7, because it has wrong encoding, but I could figure the right encoding out with the other answers. This code also sends authentication cookies, which you probably want when dealing with e.g. PHP forums:
julia = function(juliacode) {
fetch('julia.php', {
method: "POST",
credentials: "include", // send cookies
headers: {
'Accept': 'application/json, text/plain, */*',
//'Content-Type': 'application/json'
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" // otherwise $_POST is empty
},
body: "juliacode=" + encodeURIComponent(juliacode)
})
.then(function(response) {
return response.json(); // .text();
})
.then(function(myJson) {
console.log(myJson);
});
}
In most of the general cases 'Length' and 'Count' are used.
Array:
int[] myArray = new int[size];
int noOfElements = myArray.Length;
Typed List Array:
List <int> myArray = new List<int>();
int noOfElements = myArray.Count;
Some of the answers above don't account for folder names with periods. (folder.mp3
is a valid folder name). You should make sure the "file" isn't actually a folder before checking the extension.
Checking the extension of a file:
import os
file_path = "C:/folder/file.mp3"
if os.path.isfile(file_path):
file_extension = os.path.splitext(file_path)[1]
if file_extension.lower() == ".mp3":
print("It's an mp3")
if file_extension.lower() == ".flac":
print("It's a flac")
Output:
It's an mp3
Checking the extension of all files in a folder:
import os
directory = "C:/folder"
for file in os.listdir(directory):
file_path = os.path.join(directory, file)
if os.path.isfile(file_path):
file_extension = os.path.splitext(file_path)[1]
print(file, "ends in", file_extension)
Output:
abc.txt ends in .txt
file.mp3 ends in .mp3
song.flac ends in .flac
Comparing file extension against multiple types:
import os
file_path = "C:/folder/file.mp3"
if os.path.isfile(file_path):
file_extension = os.path.splitext(file_path)[1]
if file_extension.lower() in {'.mp3', '.flac', '.ogg'}:
print("It's a music file")
elif file_extension.lower() in {'.jpg', '.jpeg', '.png'}:
print("It's an image file")
Output:
It's a music file
According to my test,
implements OnItemClickListener -> works.
setOnItemClickListener -> works.
ListView is clickable by default (API 19)
The important thing is, "click" only works to TextView (if you choose simple_list_item_1.xml as item). That means if you provide text data for the ListView, "click" works when you click on text area. Click on empty area does not trigger "click event".
TL;DR:
The ActionListener
s (there can be multiple) execute in the order they were registered BEFORE the action
Long Answer:
A business action
typically invokes an EJB service and if necessary also sets the final result and/or navigates to a different view
if that is not what you are doing an actionListener
is more appropriate i.e. for when the user interacts with the components, such as h:commandButton
or h:link
they can be handled by passing the name of the managed bean method in actionListener
attribute of a UI Component or to implement an ActionListener
interface and pass the implementation class name to actionListener
attribute of a UI Component.
the squeel
gem provides an incredibly easy way to accomplish this (prior to this I used something like @coloradoblue's method):
names = ["Kroger", "Walmart", "Target", "Aldi"]
matching_stores = Grocery.where{name.like_any(names)}
As I understood if you are using standard currency system values then its super easy to count the minimum number of coins just by a single loop. Just always consume the max coin value and if it not possible check for the next option. But if you have a system like you have coins such as 1,2,3,4 then its not working. I guess the whole idea of having coins as 1,2,5,10,25 is to make computation easy for humans.
Though there are already many good advice, for my environment(Windows 7, using PowerShell) and the last version available of node.js ( v8.1.2 ) all the above did not worked, except when I followed brunowego settings.
So check your settings with :
npm config list
Settings behind a proxy:
npm config set registry http://registry.npmjs.org/
npm config set http-proxy http://username:password@ip:port
npm config set https-proxy http://username:password@ip:port
npm config set proxy http://username:password@ip:port
npm set strict-ssl false
Hope this will save time to someone
?? No, Nesting an html button
in an html a
(or vice-versa) is not valid html
If you’re not opposed to jquery, this can be done in one line:
jQuery 1.7+
$("#myEl").off()
jQuery < 1.7
$('#myEl').replaceWith($('#myEl').clone());
Here’s an example:
First you need to get rid of all newline characters in all your text nodes. Then you can use an identity transform to output your DOM tree. Look at the javadoc for TransformerFactory#newTransformer()
.
\s
means "one space", and \s+
means "one or more spaces".
But, because you're using the /g
flag (replace all occurrences) and replacing with the empty string, your two expressions have the same effect.
Use this -
create table dummy_table_name as select * from source_table_name;
This will create the new table with existing data available on source_table_name
.
I was getting this error once and took many of the approaches here.
My issues was that I had two app.listen(3000);
calls in the same app.js script. The first app.listen() succeeded where the second threw the error.
Another useful command I came across that helped me debug was sudo fuser -k 3000/tcp
which will kill any rogue processes you might have started (some processes may restart, e.g. if run with forever.js, but it was useful for me).
If there is no vertical scrolling then you can use position:absolute
and height:100%
declared on html and body elements.
Another option is to use viewport height units, see Make div 100% height of browser window
Absolute position Example:
html, body {_x000D_
height:100%;_x000D_
position: absolute;_x000D_
background-color:red;_x000D_
}_x000D_
.button{_x000D_
height:50%;_x000D_
background-color:white;_x000D_
}
_x000D_
<div class="button">BUTTON</div>
_x000D_
html, body {min-height:100vh;background:gray;_x000D_
}_x000D_
.col-100vh {_x000D_
height:100vh;_x000D_
}_x000D_
.col-50vh {_x000D_
height:50vh;_x000D_
}_x000D_
#mmenu_screen--information{_x000D_
background:teal;_x000D_
}_x000D_
#mmenu_screen--book{_x000D_
background:blue;_x000D_
}_x000D_
.mmenu_screen--direktaction{_x000D_
background:red;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div id="mmenu_screen" class="col-100vh container-fluid main_container">_x000D_
_x000D_
<div class="row col-100vh">_x000D_
<div class="col-xs-6 col-100vh">_x000D_
_x000D_
<div class="col-50vh col-xs-12" id="mmenu_screen--book">_x000D_
BOOKING BUTTON_x000D_
</div>_x000D_
_x000D_
<div class="col-50vh col-xs-12" id="mmenu_screen--information">_x000D_
INFO BUTTON_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
<div class="col-100vh col-xs-6 mmenu_screen--direktaction">_x000D_
DIRECT ACTION BUTTON_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
I've seen it used as a slight performance hack for a "dynamic type" pointer (in the section "Under the Hood"):
But here is the tricky trick I used to get fast performance for small types: if the value being held can fit inside of a void*, I don't actually bother allocating a new object, I force it into the pointer itself using placement new.
args should be tuple.
eg:
args = ('A','B')
args = ('A',) # in case of single
You can do this in Javascript
.
var time = new Date();
console.log(time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds());
At present it returns 15:5:18
. Note that if any of the values are less than 10, they will display using only one digit, not two.
Check this in JSFiddle
Updates:
For prefixed 0's try
var time = new Date();
console.log(
("0" + time.getHours()).slice(-2) + ":" +
("0" + time.getMinutes()).slice(-2) + ":" +
("0" + time.getSeconds()).slice(-2));
Make sure you installed sudo apt-get install android-tools-adb Now check sudo adb It will show help of adb
Now please kill/start adb use following commands -
sudo adb kill-server sudo adb start-server
Lastly, sudo adb devices
Hopefully this will work !!!
1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,
2) AbstractTableModel should be useful, where is in the JTable
required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel
,
3) consider using DefaultTableModel
, (if you are not sure about how to works) instead of AbstractTableModel
,
could be generated from simple code:
import javax.swing.*;
import javax.swing.table.*;
public class TableCheckBox extends JFrame {
private static final long serialVersionUID = 1L;
private JTable table;
public TableCheckBox() {
Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
Object[][] data = {
{"Buy", "IBM", new Integer(1000), new Double(80.50), false},
{"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
{"Sell", "Apple", new Integer(3000), new Double(7.35), true},
{"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model) {
private static final long serialVersionUID = 1L;
/*@Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}*/
@Override
public Class getColumnClass(int column) {
switch (column) {
case 0:
return String.class;
case 1:
return String.class;
case 2:
return Integer.class;
case 3:
return Double.class;
default:
return Boolean.class;
}
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TableCheckBox frame = new TableCheckBox();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
});
}
}
On newer browsers, you can use:
<input type="text" name="country_code"
pattern="[A-Za-z]" title="Three letter country code">
You can use regular expressions to restrict the input fields.
in visual 2019, Open Options to show all enter image description here
and multi select: keep Ctrl + Alt
then click position you want
or, keep Shift + Alt
then click position to multi select multi line from start to end line clicked
You can change the highlight color in several ways.
Change the selectionStyle property of your cell. If you change it to UITableViewCellSelectionStyleGray
, it will be gray.
Change the selectedBackgroundView
property. Actually what creates the blue gradient is a view. You can create a view and draw what ever you like, and use the view as the background of your table view cells.
Confirm that you have the correct email address before sending out emails. If someone gives the wrong email address on sign-up, beat them over the head about it ASAP.
Always include clear "how to unsubscribe" information in EVERY email. Do not require the user to login to unsubscribe, it should be a unique url for 1-click unsubscribe.
This will prevent people from marking your mails as spam because "unsubscribing" is too hard.
The execution of maven command required pom.xml file that contains information about the project and configuration details used by Maven to build the project. It contains default values for most projects.
Make sure that porject should contains pom.xml at the root level.
With python 3 you can use the pathlib
module (pathlib.PurePath
for example):
>>> import pathlib
>>> path = pathlib.PurePath('/folderA/folderB/folderC/folderD/')
>>> path.name
'folderD'
If you want the last folder name where a file is located:
>>> path = pathlib.PurePath('/folderA/folderB/folderC/folderD/file.py')
>>> path.parent.name
'folderD'
String methodName= "...";
String[] args = {};
Method[] methods = clazz.getMethods();
for (Method m : methods) {
if (methodName.equals(m.getName())) {
// for static methods we can use null as instance of class
m.invoke(null, new Object[] {args});
break;
}
}
The short answer is, you cannot search commit messages directly on github.com the website. For the time being we recommend the local git grep
solution others on this thread have proposed.
At one point in time GitHub did offer a git grep
style search over commit messages for a single repository. Unfortunately, this approach exposed a denial of service that could render a file server inaccessible. For this reason, we removed git grep
searching.
Current back-of-the envelope estimates puts the number of commits in GitHub somewhere around the 80 billion mark. Although Google engineers laugh behind our backs, this is a rather large number of documents to store in ElasticSearch. We'd love to make this dataset searchable, but it is not a trivial project.
I used this code and it worked for me on Chrome, Firefox and IE.
<select onmousedown="if(this.options.length>5){this.size=5;}" onchange="this.blur()" onblur="this.size=0;">_x000D_
<option>option1</option>_x000D_
<option>option2</option>_x000D_
<option>option3</option>_x000D_
<option>option4</option>_x000D_
<option>option5</option>_x000D_
<option>option6</option>_x000D_
<option>option7</option>_x000D_
</select>
_x000D_
Though there are already quite a few answers, I thought my answer might help some who have exactly the same problem as mine. In my case, the problem is caused by the following permissions added per the suggestion of an ad network:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
The consequence of the above permissions is that the following features are added automatically:
android.hardware.LOCATION
android.hardware.location.GPS
android.hardware.location.NETWORK
The reason is that "Google Play attempts to discover an application's implied feature requirements by examining other elements declared in the manifest file, specifically, elements." Two of my testing devices do not have the above features, so the app became incompatible with them. Removing those permissions solved the problem immediately.
To eliminate the need to repeatedly press F5 in an IE tab while developing a website, use ReloadIt.
For each webpage displayed in IE, you can configure a filename, a directory, or a set of them. If any change occurs in any of those configured paths, ReloadIt refreshes the IE tab. A simple tool. It just works.
This will reload everything, not just javascript.
You may try to install Package Control first by following simple instructions available at Installation Guide (which is like 1. Open the Console, 2. Paste the code).
Then please check Package Docs Control Usage for Basic Functionality:
Package Control is driven by the Command Pallete. To open the pallete, press Ctrl+Shift+P (Win, Linux) or CMD+Shift+P (OS X). All Package Control commands begin with Package Control:, so start by typing Package.
The command pallete will now show a number of commands. Most users will be interested in the following:
Install Package
Show a list of all available packages that are available for install. This will include all of the packages from the default channel, plus any from repositories you have added.
Here is one that works better for me (LINQPad version):
DateTime d;
DateTime.TryParseExact(
"2010-08-20T15:00:00Z",
@"yyyy-MM-dd\THH:mm:ss\Z",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal,
out d);
d.ToString()
produces
true
8/20/2010 8:00:00 AM
With TortoiseSVN I just move the file on disk.
When I come to commit my changes I select the missing file and the new one and select "Repair move" from the right click menu:
This means I can let my IDE move round files and use it refactoring tools without losing history.
Something like this should do it too :
$last = $wpdb->get_row("SHOW TABLE STATUS LIKE 'table_name'");
$lastid = $last->Auto_increment;
cart.push({"element":{ id: id, quantity: quantity }});
You should execute sh -c echo $PWD
; generally sh -c
will execute shell commands.
(In fact, system(foo)
is defined as execl("sh", "sh", "-c", foo, NULL)
and thus works for shell built-ins.)
If you just want the value of PWD
, use getenv
, though.
The use of "closed" vs. "open" reflects whether or not we are locked in to using a certain position or data structure (this is an extremely vague description, but hopefully the rest helps).
For instance, the "open" in "open addressing" tells us the index (aka. address) at which an object will be stored in the hash table is not completely determined by its hash code. Instead, the index may vary depending on what's already in the hash table.
The "closed" in "closed hashing" refers to the fact that we never leave the hash table; every object is stored directly at an index in the hash table's internal array. Note that this is only possible by using some sort of open addressing strategy. This explains why "closed hashing" and "open addressing" are synonyms.
Contrast this with open hashing - in this strategy, none of the objects are actually stored in the hash table's array; instead once an object is hashed, it is stored in a list which is separate from the hash table's internal array. "open" refers to the freedom we get by leaving the hash table, and using a separate list. By the way, "separate list" hints at why open hashing is also known as "separate chaining".
In short, "closed" always refers to some sort of strict guarantee, like when we guarantee that objects are always stored directly within the hash table (closed hashing). Then, the opposite of "closed" is "open", so if you don't have such guarantees, the strategy is considered "open".
You need to write it this way
<div
className="player"
style={{ position: "absolute" }}
onKeyDown={this.onKeyPressed}
tabIndex="0"
>
If onKeyPressed
is not bound to this
, then try to rewrite it using arrow function or bind it in the component constructor
.
Same everyday problem.
I just created a simple vc project to solve this problem.
It copies the file as Base64 encoded data directly to the clipboard, and then this can be pasted into the PuTTY console and decoded on the remote side.
This solution is for relatively small files (relative to the connection speed to your remote console).
Download clip_b64.exe
and place it in the SendTo folder (or a .lnk
shortcut to it). To open this folder, in the address bar of the explorer, enter shell:sendto
or %appdata%\Microsoft\Windows\SendTo
.
You may need to install VC 2017 redist to run it, or use the statically linked clip_b64s.exe
execution.
In the File Explorer, right-click the file you are transferring to open the context menu, then go to the "Send To" section and select Clip_B64
from the list.
Run the shell command base64 -d > file-name-you-want
and right-click in the console (or press Shift + Insert
) to place the clipboard content in it, and then press Ctrl + D
to finish.
voila
You can simply hide the <td>
tag content by just including a style attribute: style = "display:none"
For e.g
<td style = "display:none" >
<p> I'm invisible </p>
</td>
There are a few ways to convert String
to long
:
1)
long l = Long.parseLong("200");
String numberAsString = "1234";
long number = Long.valueOf(numberAsString).longValue();
String numberAsString = "1234";
Long longObject = new Long(numberAsString);
long number = longObject.longValue();
We can shorten to:
String numberAsString = "1234";
long number = new Long(numberAsString).longValue();
Or just
long number = new Long("1234").longValue();
String numberAsString = "1234";
DecimalFormat decimalFormat = new DecimalFormat("#");
try {
long number = decimalFormat.parse(numberAsString).longValue();
System.out.println("The number is: " + number);
} catch (ParseException e) {
System.out.println(numberAsString + " is not a valid number.");
}
Put this in a file and make it executable:
#!/bin/bash
start=`grep -n $1 < $3 | head -n1 | cut -d: -f1; exit ${PIPESTATUS[0]}`
if [ ${PIPESTATUS[0]} -ne 0 ]; then
echo "couldn't find start pattern!" 1>&2
exit 1
fi
stop=`tail -n +$start < $3 | grep -n $2 | head -n1 | cut -d: -f1; exit ${PIPESTATUS[1]}`
if [ ${PIPESTATUS[0]} -ne 0 ]; then
echo "couldn't find end pattern!" 1>&2
exit 1
fi
stop=$(( $stop + $start - 1))
sed "$start,$stop!d" < $3
Execute the file with arguments (NOTE that the script does not handle spaces in arguments!):
To use with your example, use arguments: 1234 5555 myfile.txt
Includes lines with starting and stopping pattern.
var data = {
"items": [{
"id": 1,
"category": "cat1"
}, {
"id": 2,
"category": "cat2"
}, {
"id": 3,
"category": "cat1"
}]
};
var returnedData = $.grep(data.items, function (element, index) {
return element.id == 1;
});
alert(returnedData[0].id + " " + returnedData[0].category);
The returnedData is returning an array of objects, so you can access it by array index.
You can simple add this code to script file
//Database Connection
$host = 'localhost';
$db_name = 'your_database_name';
$db_user = 'your_database_user_name';
$db_pass = 'your_database_user_password';
$con = mysql_connect($host,$db_user,$db_pass);
if(!$con) { echo "Cannot connect to the database ";die();}
mysql_select_db($db_name);
$result=mysql_query('show tables');
while($tables = mysql_fetch_array($result)) {
foreach ($tables as $key => $value) {
mysql_query("ALTER TABLE $value CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci");
}
}
echo "The collation of your database has been successfully changed!";
PyLibTiff worked better for me than PIL, which as of December 2020 still doesn't support color images with more than 8 bits per color.
from libtiff import TIFF
tif = TIFF.open('filename.tif') # open tiff file in read mode
# read an image in the currect TIFF directory as a numpy array
image = tif.read_image()
# read all images in a TIFF file:
for image in tif.iter_images():
pass
tif = TIFF.open('filename.tif', mode='w')
tif.write_image(image)
You can install PyLibTiff with
pip3 install numpy libtiff
The readme of PyLibTiff also mentions the tifffile
library but I haven't tried it.
history.pushState(null, null, location.href);
window.onpopstate = function () {
history.go(1);
};
If you literally want a one line equivalent to the commands in your original question, you could alias:
mongo --eval "db.getSiblingDB('admin').shutdownServer()"
It seems that the good-old ENVIRON
awk built-in hash is not mentioned at all. An example of its usage:
$ X=Solaris awk 'BEGIN{print ENVIRON["X"], ENVIRON["TERM"]}'
Solaris rxvt
just use this:
<script>
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["1","2","3","4","5","6","7","8","9","10","11",],
datasets: [{
label: 'YOUR LABEL',
backgroundColor: [
"#566573",
"#99a3a4",
"#dc7633",
"#f5b041",
"#f7dc6f",
"#82e0aa",
"#73c6b6",
"#5dade2",
"#a569bd",
"#ec7063",
"#a5754a"
],
data: [12, 19, 3, 17, 28, 24, 7, 2,4,14,6],
},]
},
//HERE COMES THE AXIS Y LABEL
options : {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'probability'
}
}]
}
}
});
</script>
Check out the Programmatically Displaying the Settings Page
startActivity(context, new Intent(Settings.ACTION_SETTINGS), /*options:*/ null);
In general, you use the predefined constant Settings.ACTION__SETTINGS
. The full list can be found here
Found the flex magic.
Here's an example of how to do a fixed header and a scrollable content. Code:
<!DOCTYPE html>
<html style="height: 100%">
<head>
<meta charset=utf-8 />
<title>Holy Grail</title>
<!-- Reset browser defaults -->
<link rel="stylesheet" href="reset.css">
</head>
<body style="display: flex; height: 100%; flex-direction: column">
<div>HEADER<br/>------------
</div>
<div style="flex: 1; overflow: auto">
CONTENT - START<br/>
<script>
for (var i=0 ; i<1000 ; ++i) {
document.write(" Very long content!");
}
</script>
<br/>CONTENT - END
</div>
</body>
</html>
* The advantage of the flex solution is that the content is independent of other parts of the layout. For example, the content doesn't need to know height of the header.
For a full Holy Grail implementation (header, footer, nav, side, and content), using flex display, go to here.
$(document).ready(function(){
$("input[type=search]").attr("placeholder","this is a test");
});
The problem is that you're trying to print an unicode character to a possibly non-unicode terminal. You need to encode it with the 'replace
option before printing it, e.g. print ch.encode(sys.stdout.encoding, 'replace')
.
Declare where display: flex;
was given Element.
align-items: center;
You could try changing the: SizeMode property of the PictureBox.
You could also set your image as the BackGroundImage of the PictureBox and try changing the BackGroundImageLayout to the correct mode.
<?php if( $_product->getTypeId() == 'simple' ): ?>
//your code for simple products only
<?php endif; ?>
<?php if( $_product->getTypeId() == 'grouped' ): ?>
//your code for grouped products only
<?php endif; ?>
So on. It works! Magento 1.6.1, place in the view.phtml
You're sending JSON-formatted data to a server which isn't expecting that format. You already provided the format that the server needs, so you'll need to format it yourself which is pretty simple.
var data = '"title='+title+'" "text='+text+'" "file='+file+'"';
$http.post(uploadUrl, data)
return RedirectToAction("ProductImageManager","Index", new { id=id });
Here is an invalid parameters order, should be an action first
AND
ensure your routing table is correct
What you're looking for is the function strlcpy()
which does terminate always the string with 0 and initializes the buffer. It also is able to detect overflows. Only problem, it's not (really) portable and is present only on some systems (BSD, Solaris). The problem with this function is that it opens another can of worms as can be seen by the discussions on
http://en.wikipedia.org/wiki/Strlcpy
My personal opinion is that it is vastly more useful than strncpy()
and strcpy()
. It has better performance and is a good companion to snprintf()
. For platforms which do not have it, it is relatively easy to implement.
(for the developement phase of a application I substitute these two function (snprintf()
and strlcpy()
) with a trapping version which aborts brutally the program on buffer overflows or truncations. This allows to catch quickly the worst offenders. Especially if you work on a codebase from someone else.
EDIT: strlcpy()
can be implemented easily:
size_t strlcpy(char *dst, const char *src, size_t dstsize)
{
size_t len = strlen(src);
if(dstsize) {
size_t bl = (len < dstsize-1 ? len : dstsize-1);
((char*)memcpy(dst, src, bl))[bl] = 0;
}
return len;
}
Linq With Or Condition by using Lambda expression you can do as below
DataTable dtEmp = new DataTable();
dtEmp.Columns.Add("EmpID", typeof(int));
dtEmp.Columns.Add("EmpName", typeof(string));
dtEmp.Columns.Add("Sal", typeof(decimal));
dtEmp.Columns.Add("JoinDate", typeof(DateTime));
dtEmp.Columns.Add("DeptNo", typeof(int));
dtEmp.Rows.Add(1, "Rihan", 10000, new DateTime(2001, 2, 1), 10);
dtEmp.Rows.Add(2, "Shafi", 20000, new DateTime(2000, 3, 1), 10);
dtEmp.Rows.Add(3, "Ajaml", 25000, new DateTime(2010, 6, 1), 10);
dtEmp.Rows.Add(4, "Rasool", 45000, new DateTime(2003, 8, 1), 20);
dtEmp.Rows.Add(5, "Masthan", 22000, new DateTime(2001, 3, 1), 20);
var res2 = dtEmp.AsEnumerable().Where(emp => emp.Field<int>("EmpID")
== 1 || emp.Field<int>("EmpID") == 2);
foreach (DataRow row in res2)
{
Label2.Text += "Emplyee ID: " + row[0] + " & Emplyee Name: " + row[1] + ", ";
}
An easy fix for this is to float your H1 element left:
.centercol h1{
background: #F2EFE9;
border-left: 3px solid #C6C1B8;
color: #006BB6;
display: block;
float: left;
font-weight: normal;
font-size: 18px;
padding: 3px 3px 3px 6px;
}
I have put together a simple jsfiddle example that shows the effect of the "float: left" style on the width of your H1 element for anyone looking for a more generic answer:
ClickOnce applications DO reside in a subdirectory of C:\Documents & Settings. They don't have "clean" installation directories because the local files are essentially "temporarily" downloaded to allow the application to run on the local PC and execution of the application is controlled from the ClickOnce server that they are deployed on depending on publishing settings (Checking for updates, version requirements, etc).
I already did it using Lotus Notus
and PHP
.
This solution works if you have access to the mail server or you can request something to the mail server
Administrator:
1) Create a group in the mail server
: Sales Department
2) Assign to the group
the accounts you need to be in the group
3) Assign an internet address to the group: [email protected]
4) Create your PHP script using the mail function:
$to = "[email protected]";
mail($to, $subject, $message, $headers);
It worked for me and all the accounts included in the group receive the mail.
The best of the lucks.
Don't forget to take into consideration the global flag in your regexp :
var reg = /abc/g;
!!'abcdefghi'.match(reg); // => true
!!'abcdefghi'.match(reg); // => true
reg.test('abcdefghi'); // => true
reg.test('abcdefghi'); // => false <=
This is because Regexp keeps track of the lastIndex when a new match is found.
You can't according to the PHP manual:
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
This is because cookies are sent in response headers to the browser and the browser must then send them back with the next request. This is why they are only available on the second page load.
But you can work around it by also setting $_COOKIE
when you call setcookie()
:
if(!isset($_COOKIE['lg'])) {
setcookie('lg', 'ro');
$_COOKIE['lg'] = 'ro';
}
echo $_COOKIE['lg'];
If by easy you mean a lines of code that are easy to decipher but per chance inefficient?
string[] lines = System.IO.File.RealAllLines($filename);
int cnt = lines.Count();
That's probably the quickest way to know how many lines.
You could also do (depending on if you are buffering it in)
#for large files
while (...reads into buffer){
string[] lines = Regex.Split(buffer,System.Enviorment.NewLine);
}
There are other numerous ways but one of the above is probably what you'll go with.
const obj = { id: 1, name: 'Neel' };_x000D_
let str = '';_x000D_
str = Object.entries(obj).map(([key, val]) => `${key}=${val}`).join('&');_x000D_
console.log(str);
_x000D_
Pulling may have created local change.
Add your untracked file:
git add .
Stash changes.
git stash
Drop local changes.
git stash drop
Pull with sudo permission
sudo git pull remote branch
Disclaimer: I'm not a MySQL expert ... but this is my understanding of the issues.
I think TEXT is stored outside the mysql row, while I think VARCHAR is stored as part of the row. There is a maximum row length for mysql rows .. so you can limit how much other data you can store in a row by using the VARCHAR.
Also due to VARCHAR forming part of the row, I suspect that queries looking at that field will be slightly faster than those using a TEXT chunk.
To get the height between the layout guides you just do
let guide = view.safeAreaLayoutGuide
let height = guide.layoutFrame.size.height
So full frame height = 812.0
, safe area height = 734.0
Below is the example where the green view has frame of guide.layoutFrame
I ran into this error after my client PC crashed, the jest --watch
command I was running on the server persisted, and I tried to run jest --watch
again.
The addition to /etc/sysctl.conf
described in the answers above worked around this issue, but it was also important to find my old process via ps aux | grep node
and kill
it.
Uffh. Don't you think this is the simplest solution?
char inputChar = '|';
int freq = "|fd|fdfd|f dfd|fd".replaceAll("[^" + inputChar +"]", "").length();
System.out.println("freq " + freq);
change the code to the following
<%! List eList = (ArrayList)session.getAttribute("empList");%>
....
<table>
<%
for(int i=0; i<eList.length;i++){%>
<tr>
<td><%= ((Employee)eList[i]).getEid() %></td>
<td><%= ((Employee)eList[i]).getEname() %></td>
</tr>
<%}%>
</table>
Use the built-in sp_msforeachtable stored procedure.
To disable all constraints:
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT ALL";
To enable all constraints:
EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL";
To drop all the tables:
EXEC sp_msforeachtable "DROP TABLE ?";
To begin with, it would be best to understand the measure of information
.
measure
the information?When something unlikely happens, we say it's a big news. Also, when we say something predictable, it's not really interesting. So to quantify this interesting-ness
, the function should satisfy
one bit
of information.One natural measure that satisfy the constraints is
I(X) = -log_2(p)
where p is the probability of the event X
. And the unit is in bit
, the same bit computer uses. 0 or 1.
Fair coin flip :
How much information can we get from one coin flip?
Answer : -log(p) = -log(1/2) = 1 (bit)
If a meteor strikes the Earth tomorrow, p=2^{-22}
then we can get 22 bits of information.
If the Sun rises tomorrow, p ~ 1
then it is 0 bit of information.
So if we take expectation on the interesting-ness
of an event Y
, then it is the entropy.
i.e. entropy is an expected value of the interesting-ness of an event.
H(Y) = E[ I(Y)]
More formally, the entropy is the expected number of bits of an event.
Y = 1 : an event X occurs with probability p
Y = 0 : an event X does not occur with probability 1-p
H(Y) = E[I(Y)] = p I(Y==1) + (1-p) I(Y==0)
= - p log p - (1-p) log (1-p)
Log base 2 for all log.
Here is the perfect method:
Please note that Environment.NewLine works on on Microsoft platforms.
In addition to the above, you need to add \r and \n in a separate function!
Here is the code which will support whether you type on Linux, Windows, or Mac:
var stringTest = "\r Test\nThe Quick\r\n brown fox";
Console.WriteLine("Original is:");
Console.WriteLine(stringTest);
Console.WriteLine("-------------");
stringTest = stringTest.Trim().Replace("\r", string.Empty);
stringTest = stringTest.Trim().Replace("\n", string.Empty);
stringTest = stringTest.Replace(Environment.NewLine, string.Empty);
Console.WriteLine("Output is : ");
Console.WriteLine(stringTest);
Console.ReadLine();
git reset HEAD^
then the modified files should show up.
You could move the modified files into a new branch
use,
git checkout -b newbranch
git checkout commit -m "files modified"
git push origin newbranch
git checkout master
then you should be on a clean branch, and your changes should be stored in newbranch. You could later just merge this change into the master branch
Here is my version using the BuildConfig
class:
Intent marketIntent = new Intent(Intent.ACTION_VIEW, uri);
marketIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
marketIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
}
try {
startActivity(marketIntent);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + BuildConfig.APPLICATION_ID)));
}
I'm not quite sure if you mean 'can i use sqlite (websql) in chrome' or 'can i use sqlite (websql) in firefox', so I'll answer both:
Note that WebSQL is not a full-access pipe into an .sqlite database. It's WebSQL. You will not be able to run some specific queries like VACUUM
It's awesome for Create / Read / Update / Delete though. I made a little library that helps with all the annoying nitty gritty like creating tables and querying and a provides a little ORM/ActiveRecord pattern with relations and all and a huge stack of examples that should get you started in no-time, you can check that here
Also, be aware that if you want to build a FireFox extension: Their extension format is about to change. Make sure you want to invest the time twice.
While the WebSQL spec has been deprecated for years, even now in 2017 still does not look like it will be be removed from Chrome for the foreseeable time. They are tracking usage statistics and there are still a large number of chrome extensions and websites out there in the real world implementing the spec.
You can try as follows:
/*
* Remove the directory and its content (all files and subdirectories).
* @param string $dir the directory name
*/
function rmrf($dir) {
foreach (glob($dir) as $file) {
if (is_dir($file)) {
rmrf("$file/*");
rmdir($file);
} else {
unlink($file);
}
}
}
You can use reindex
which can be used for both axis:
df
# 0 1 2 3 4 mean
# 0 0.943825 0.202490 0.071908 0.452985 0.678397 0.469921
# 1 0.745569 0.103029 0.268984 0.663710 0.037813 0.363821
# 2 0.693016 0.621525 0.031589 0.956703 0.118434 0.484254
# 3 0.284922 0.527293 0.791596 0.243768 0.629102 0.495336
# 4 0.354870 0.113014 0.326395 0.656415 0.172445 0.324628
# 5 0.815584 0.532382 0.195437 0.829670 0.019001 0.478415
# 6 0.944587 0.068690 0.811771 0.006846 0.698785 0.506136
# 7 0.595077 0.437571 0.023520 0.772187 0.862554 0.538182
# 8 0.700771 0.413958 0.097996 0.355228 0.656919 0.444974
# 9 0.263138 0.906283 0.121386 0.624336 0.859904 0.555009
df.reindex(['mean', *range(5)], axis=1)
# mean 0 1 2 3 4
# 0 0.469921 0.943825 0.202490 0.071908 0.452985 0.678397
# 1 0.363821 0.745569 0.103029 0.268984 0.663710 0.037813
# 2 0.484254 0.693016 0.621525 0.031589 0.956703 0.118434
# 3 0.495336 0.284922 0.527293 0.791596 0.243768 0.629102
# 4 0.324628 0.354870 0.113014 0.326395 0.656415 0.172445
# 5 0.478415 0.815584 0.532382 0.195437 0.829670 0.019001
# 6 0.506136 0.944587 0.068690 0.811771 0.006846 0.698785
# 7 0.538182 0.595077 0.437571 0.023520 0.772187 0.862554
# 8 0.444974 0.700771 0.413958 0.097996 0.355228 0.656919
# 9 0.555009 0.263138 0.906283 0.121386 0.624336 0.859904
Video tag supports only video formats (like mp4 etc). Youtube does not expose its raw video files - it only exposes the unique id of the video. Since that id does not correspond to the actual file, video tag cannot be used.
If you do get hold of the actual source file using one of the youtube download sites or soft wares, you will be able to use the video tag. But even then, the url of the actual source will cease to work after a set time. So your video also will work only till then.
If you are using Sql Server Management Studio, you can create your own schema by browsing to Databases - Your Database - Security - Schemas.
To create one using a script is as easy as (for example):
CREATE SCHEMA [EnterSchemaNameHere] AUTHORIZATION [dbo]
You can use them to logically group your tables, for example by creating a schema for "Financial" information and another for "Personal" data. Your tables would then display as:
Financial.BankAccounts Financial.Transactions Personal.Address
Rather than using the default schema of dbo.
While only a few lines are required to plot multiple/overlapping histograms in ggplot2, the results are't always satisfactory. There needs to be proper use of borders and coloring to ensure the eye can differentiate between histograms.
The following functions balance border colors, opacities, and superimposed density plots to enable the viewer to differentiate among distributions.
Single histogram:
plot_histogram <- function(df, feature) {
plt <- ggplot(df, aes(x=eval(parse(text=feature)))) +
geom_histogram(aes(y = ..density..), alpha=0.7, fill="#33AADE", color="black") +
geom_density(alpha=0.3, fill="red") +
geom_vline(aes(xintercept=mean(eval(parse(text=feature)))), color="black", linetype="dashed", size=1) +
labs(x=feature, y = "Density")
print(plt)
}
Multiple histogram:
plot_multi_histogram <- function(df, feature, label_column) {
plt <- ggplot(df, aes(x=eval(parse(text=feature)), fill=eval(parse(text=label_column)))) +
geom_histogram(alpha=0.7, position="identity", aes(y = ..density..), color="black") +
geom_density(alpha=0.7) +
geom_vline(aes(xintercept=mean(eval(parse(text=feature)))), color="black", linetype="dashed", size=1) +
labs(x=feature, y = "Density")
plt + guides(fill=guide_legend(title=label_column))
}
Usage:
Simply pass your data frame into the above functions along with desired arguments:
plot_histogram(iris, 'Sepal.Width')
plot_multi_histogram(iris, 'Sepal.Width', 'Species')
The extra parameter in plot_multi_histogram is the name of the column containing the category labels.
We can see this more dramatically by creating a dataframe with many different distribution means:
a <-data.frame(n=rnorm(1000, mean = 1), category=rep('A', 1000))
b <-data.frame(n=rnorm(1000, mean = 2), category=rep('B', 1000))
c <-data.frame(n=rnorm(1000, mean = 3), category=rep('C', 1000))
d <-data.frame(n=rnorm(1000, mean = 4), category=rep('D', 1000))
e <-data.frame(n=rnorm(1000, mean = 5), category=rep('E', 1000))
f <-data.frame(n=rnorm(1000, mean = 6), category=rep('F', 1000))
many_distros <- do.call('rbind', list(a,b,c,d,e,f))
Passing data frame in as before (and widening chart using options):
options(repr.plot.width = 20, repr.plot.height = 8)
plot_multi_histogram(many_distros, 'n', 'category')
You can achieve this using a meta tag
as follows:
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
I've been trying to achieve something really simple and failed miserably, probably I'm stupid.
Anyway, if you have a script/Dockerfile
which download a python package zip file (e.g. from GitHub) and you then want to install it you can use the file:///
prefix to install it as shown in the following example:
$ wget https://example.com/mypackage.zip
$ echo "${MYPACKAGE_MD5} mypackage.zip" | md5sum --check -
$ pip install file:///.mypackage.zip
NOTE: I know you could install the package straight away using pip install https://example.com/mypackage.zip
but in my case I wanted to verify the checksum (never paranoid enough) and I failed miserably when trying to use the various options that pip provides/the #md5
fragment.
It's been surprisingly frustrating to do something so simple directly with pip
. I just wanted to pass a checksum and have pip
verify that the zip was matching before installing it.
I was probably doing something very stupid but in the end I gave up and opted for this. I hope it helps others trying to do something similar.
Action method needs to return FileResult with either a stream, byte[], or virtual path of the file. You will also need to know the content-type of the file being downloaded. Here is a sample (quick/dirty) utility method. Sample video link How to download files using asp.net core
[Route("api/[controller]")]
public class DownloadController : Controller
{
[HttpGet]
public async Task<IActionResult> Download()
{
var path = @"C:\Vetrivel\winforms.png";
var memory = new MemoryStream();
using (var stream = new FileStream(path, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
var ext = Path.GetExtension(path).ToLowerInvariant();
return File(memory, GetMimeTypes()[ext], Path.GetFileName(path));
}
private Dictionary<string, string> GetMimeTypes()
{
return new Dictionary<string, string>
{
{".txt", "text/plain"},
{".pdf", "application/pdf"},
{".doc", "application/vnd.ms-word"},
{".docx", "application/vnd.ms-word"},
{".png", "image/png"},
{".jpg", "image/jpeg"},
...
};
}
}
Do it like this:
$("#elem").get(0).style.width= "100px!important";
If you are serious about maintaining interoperability with other JVM languages (e.g. Java) then the best option is to write Java enums. Those work transparently from both Scala and Java code, which is more than can be said for scala.Enumeration
or case objects. Let's not have a new enumerations library for every new hobby project on GitHub, if it can be avoided!
You could just do ...
(.*?)\.txt
essentially the shadow is the box shape just offset behind the actual box. in order to hide portions of the shadow, you need to create additional divs and set their z-index above the shadowed box so that the shadow is not visible.
If you'd like to have extremely specific control over your shadows, build them as images and created container divs with the right amount of padding and margins.. then use the png fix to make sure the shadows render properly in all browsers
Another solution without using any height but still fills 100% available height. Checkout this e.g on the codepen. http://codepen.io/gauravshankar/pen/PqoLLZ
For this html and body should have 100% height. This height is equal to the viewport height.
Make inner div position absolute and give top and bottom 0. This fills the div to available height. (height equal to body.)
html code:
<head></head>
<body>
<div></div>
</body>
</html>
css code:
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
position: relative;
}
html {
background-color: red;
}
body {
background-color: green;
}
body> div {
position: absolute;
background-color: teal;
width: 300px;
top: 0;
bottom: 0;
}
Hi you can use following rules on your htaccess file:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
If it is only a bootstrap icon. Note that icons are under text or rather typography. Just add the text color class like this. E.g text-primary, text-info and so on and so forth to the icon class:
<i class="icon features-icon icons8-collaboration-2 text-primary"></i>
<i class="icon features-icon icons8-collaboration-2 text-secondary"></i>
Although @BrianHart 's answer is correct, if you are connecting from a remote host, you'll also need to allow remote hosts to connect to the MySQL/MariaDB database.
My article describes the full instructions to connect to a MySQL/MariaDB database in Oracle SQL Developer:
To find the version of the java in the classfiles I used:
javap -verbose <classname>
which announces the version at the start as
minor version: 0
major version: 49
which corresponds to Java 1.5
These two commands should do it:
:set autoindent
:set cindent
For bonus points put them in a file named .vimrc located in your home directory on linux
For some frequently used movements and actions, I have defined the following mappings. This saves a keystroke compared to the CTRL+O combination and since I need them frequently, they pay off in the long run.
inoremap <A-$> <C-o>$
inoremap <A-^> <C-o>^
inoremap <A-h> <Left>
inoremap <A-l> <Right>
inoremap <A-O> <C-O>O
inoremap <A-o> <C-o>o
In your layout. Your Texto should not contain (android:text=...). I would remove this line. Either keep the Java string OR the (android:text=...)
If you are getting these type of errors when running mongod from command line or running mongodb server,
then follow these steps,
To address the question more generally...
Keep in mind that using synchronized on methods is really just shorthand (assume class is SomeClass):
synchronized static void foo() {
...
}
is the same as
static void foo() {
synchronized(SomeClass.class) {
...
}
}
and
synchronized void foo() {
...
}
is the same as
void foo() {
synchronized(this) {
...
}
}
You can use any object as the lock. If you want to lock subsets of static methods, you can
class SomeClass {
private static final Object LOCK_1 = new Object() {};
private static final Object LOCK_2 = new Object() {};
static void foo() {
synchronized(LOCK_1) {...}
}
static void fee() {
synchronized(LOCK_1) {...}
}
static void fie() {
synchronized(LOCK_2) {...}
}
static void fo() {
synchronized(LOCK_2) {...}
}
}
(for non-static methods, you would want to make the locks be non-static fields)
Server-side functions are on the server-side, client-side functions reside on the client.
What you can do is you have to set hidden form variable and submit the form, then on page use Page_Load
handler you can access value of variable and call the server method.
You might need to set permissions at the database level that allows your schema owner to restore the dump.
You can also just enter the website and:
The same limitation applies here: the folder must contain at least one file inside it.
Once you have cloned the repo, you have everything: you can then hg up branchname
or hg up tagname
to update your working copy.
UP: hg up
is a shortcut of hg update
, which also has hg checkout
alias for people with git
habits.
Try:
Type type = Type.GetType(inputString); //target type
object o = Activator.CreateInstance(type); // an instance of target type
YourType your = (YourType)o;
Jon Skeet is right as usually :)
Update: You can specify assembly containing target type in various ways, as Jon mentioned, or:
YourType your = (YourType)Activator.CreateInstance("AssemblyName", "NameSpace.MyClass");
Run this command in your terminal:
$ java -version
java version "1.8.0_181"
Java(TM) SE Runtime Environment (build 1.8.0_181-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)
Cristians-MacBook-Air:~ fa$
There is no difference between them.
If you don't specify a value for any of the half-dozen properties that background
is a shorthand for, then it is set to its default value. none
and transparent
are the defaults.
One explicitly sets the background-image
to none
and implicitly sets the background-color
to transparent
. The other is the other way around.
Java 5+ has all the tools you need for this kind of thing. You will want to:
ExecutorService
;ExecutorService
;BlockingQueue
.I say "if necessary" for (3) because from my experience it's an unnecessary step. All you do is submit new tasks to the consumer executor service. So:
final ExecutorService producers = Executors.newFixedThreadPool(100);
final ExecutorService consumers = Executors.newFixedThreadPool(100);
while (/* has more work */) {
producers.submit(...);
}
producers.shutdown();
producers.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
consumers.shutdown();
consumers.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
So the producers
submit directly to consumers
.