In direct opposition to my other answer, this following function is probably safe, even with multi-byte characters.
// replace any non-ascii character with its hex code.
function escape($value) {
$return = '';
for($i = 0; $i < strlen($value); ++$i) {
$char = $value[$i];
$ord = ord($char);
if($char !== "'" && $char !== "\"" && $char !== '\\' && $ord >= 32 && $ord <= 126)
$return .= $char;
else
$return .= '\\x' . dechex($ord);
}
return $return;
}
I'm hoping someone more knowledgeable than myself can tell me why the code above won't work ...
Here my two cents, which permits casting up and down, and adds customizable precision:
def convertFloatToDecimal(f=0.0, precision=2):
'''
Convert a float to string of decimal.
precision: by default 2.
If no arg provided, return "0.00".
'''
return ("%." + str(precision) + "f") % f
def formatFileSize(size, sizeIn, sizeOut, precision=0):
'''
Convert file size to a string representing its value in B, KB, MB and GB.
The convention is based on sizeIn as original unit and sizeOut
as final unit.
'''
assert sizeIn.upper() in {"B", "KB", "MB", "GB"}, "sizeIn type error"
assert sizeOut.upper() in {"B", "KB", "MB", "GB"}, "sizeOut type error"
if sizeIn == "B":
if sizeOut == "KB":
return convertFloatToDecimal((size/1024.0), precision)
elif sizeOut == "MB":
return convertFloatToDecimal((size/1024.0**2), precision)
elif sizeOut == "GB":
return convertFloatToDecimal((size/1024.0**3), precision)
elif sizeIn == "KB":
if sizeOut == "B":
return convertFloatToDecimal((size*1024.0), precision)
elif sizeOut == "MB":
return convertFloatToDecimal((size/1024.0), precision)
elif sizeOut == "GB":
return convertFloatToDecimal((size/1024.0**2), precision)
elif sizeIn == "MB":
if sizeOut == "B":
return convertFloatToDecimal((size*1024.0**2), precision)
elif sizeOut == "KB":
return convertFloatToDecimal((size*1024.0), precision)
elif sizeOut == "GB":
return convertFloatToDecimal((size/1024.0), precision)
elif sizeIn == "GB":
if sizeOut == "B":
return convertFloatToDecimal((size*1024.0**3), precision)
elif sizeOut == "KB":
return convertFloatToDecimal((size*1024.0**2), precision)
elif sizeOut == "MB":
return convertFloatToDecimal((size*1024.0), precision)
Add TB
, etc, as you wish.
I had a similar problem when I needed to make multiple sql queries. The problem was that some queries did not return the result and I wanted to print that result. And there was a mistake. As already written, there are several solutions.
if cursor.description is None:
# No recordset for INSERT, UPDATE, CREATE, etc
pass
else:
# Recordset for SELECT
As well as:
exist = cursor.fetchone()
if exist is None:
... # does not exist
else:
... # exists
One of the solutions is:
The try
and except
block lets you handle the error
/exceptions
. The finally
block lets you execute code, regardless of the result of the try
and except
blocks.
So the presented problem can be solved by using it.
s = """ set current query acceleration = enable;
set current GET_ACCEL_ARCHIVE = yes;
SELECT * FROM TABLE_NAME;"""
query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
print(f"Executing SQL statements ====> {sql} <=====")
cursor.execute(sql)
print(f"SQL ====> {sql} <===== was executed successfully")
try:
print("\n****************** RESULT ***********************")
for result in cursor.fetchall():
print(result)
print("****************** END RESULT ***********************\n")
except Exception as e:
print(f"SQL: ====> {sql} <==== doesn't have output!\n")
# print(str(e))
output:
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!
Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!
Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====
****************** RESULT ***********************
---------- DATA ----------
****************** END RESULT ***********************
The example above only presents a simple use as an idea that could help with your solution. Of course, you should also pay attention to other errors, such as the correctness of the query, etc.
How about programmatically modifying the size attribute on the input?
Semantically (imo), this solution is better than the accepted solution because it still uses input fields for user input but it does introduce a little bit of jQuery. Soundcloud does something similar to this for their tagging.
<input size="1" />
$('input').on('keydown', function(evt) {
var $this = $(this),
size = parseInt($this.attr('size'), 10),
isValidKey = (evt.which >= 65 && evt.which <= 90) || // a-zA-Z
(evt.which >= 48 && evt.which <= 57) || // 0-9
evt.which === 32;
if ( evt.which === 8 && size > 0 ) {
// backspace
$this.attr('size', size - 1);
} else if ( isValidKey ) {
// all other keystrokes
$this.attr('size', size + 1);
}
});
Here is explained how to do it and why it works so: http://cocoathings.blogspot.com/2013/03/how-to-make-uibutton-text-left-or-right.html
Imagine d.getId is a Long, then wrap like this:
BigInteger l = BigInteger.valueOf(d.getId());
Please try this:
byte[] decodedString = Base64.decode(person_object.getPhoto(),Base64.NO_WRAP);
InputStream inputStream = new ByteArrayInputStream(decodedString);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
user_image.setImageBitmap(bitmap);
Anticipating that I already had the answer, which is that there is no built-in worksheet function that returns the background color of a cell, I decided to review this article, in case I was wrong. I was amused to notice a citation to the very same MVP article that I used in the course of my ongoing research into colors in Microsoft Excel.
While I agree that, in the purest sense, color is not data, it is meta-data, and it has uses as such. To that end, I shall attempt to develop a function that returns the color of a cell. If I succeed, I plan to put it into an add-in, so that I can use it in any workbook, where it will join a growing legion of other functions that I think Microsoft left out of the product.
Regardless, IMO, the ColorIndex property is virtually useless, since there is essentially no connection between color indexes and the colors that can be selected in the standard foreground and background color pickers. See Color Combinations: Working with Colors in Microsoft Office and the associated binary workbook, Color_Combinations Workbook.
i had the same issue, but I just typed export
on top and erased the default one on the bottom. Scroll down and check the comments.
import React, { Component } from "react";
export class Counter extends Component { // type this
export default Counter; // this is eliminated
Whenever you create child class object then that object has all the features of parent class. Here Super() is the facilty for accession parent.
If you write super() at that time parents's default constructor is called. same if you write super.
this keyword refers the current object same as super key word facilty for accessing parents.
the one easy way to do it is to open Excel create sheet containing test data you want to export then say to excel save as xml open the xml see the xml format excel is expecting and generate it by head replacing the test data with export data
@lan this is xml fo a simle execel file with one column value i genereted with office 2003 this format is for office 2003 and above
<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">
<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
<Author>Dancho</Author>
<LastAuthor>Dancho</LastAuthor>
<Created>2010-02-05T10:15:54Z</Created>
<Company>cc</Company>
<Version>11.9999</Version>
</DocumentProperties>
<ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
<WindowHeight>13800</WindowHeight>
<WindowWidth>24795</WindowWidth>
<WindowTopX>480</WindowTopX>
<WindowTopY>105</WindowTopY>
<ProtectStructure>False</ProtectStructure>
<ProtectWindows>False</ProtectWindows>
</ExcelWorkbook>
<Styles>
<Style ss:ID="Default" ss:Name="Normal">
<Alignment ss:Vertical="Bottom"/>
<Borders/>
<Font/>
<Interior/>
<NumberFormat/>
<Protection/>
</Style>
</Styles>
<Worksheet ss:Name="Sheet1">
<Table ss:ExpandedColumnCount="1" ss:ExpandedRowCount="6" x:FullColumns="1"
x:FullRows="1">
<Row>
<Cell><Data ss:Type="String">Value1</Data></Cell>
</Row>
<Row>
<Cell><Data ss:Type="String">Value2</Data></Cell>
</Row>
<Row>
<Cell><Data ss:Type="String">Value3</Data></Cell>
</Row>
<Row>
<Cell><Data ss:Type="String">Value4</Data></Cell>
</Row>
<Row>
<Cell><Data ss:Type="String">Value5</Data></Cell>
</Row>
<Row>
<Cell><Data ss:Type="String">Value6</Data></Cell>
</Row>
</Table>
<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
<Selected/>
<Panes>
<Pane>
<Number>3</Number>
<ActiveRow>5</ActiveRow>
</Pane>
</Panes>
<ProtectObjects>False</ProtectObjects>
<ProtectScenarios>False</ProtectScenarios>
</WorksheetOptions>
</Worksheet>
<Worksheet ss:Name="Sheet2">
<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
<ProtectObjects>False</ProtectObjects>
<ProtectScenarios>False</ProtectScenarios>
</WorksheetOptions>
</Worksheet>
<Worksheet ss:Name="Sheet3">
<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
<ProtectObjects>False</ProtectObjects>
<ProtectScenarios>False</ProtectScenarios>
</WorksheetOptions>
</Worksheet>
</Workbook>
To specify any additional asset folder I've used this with my Gradle. This adds moreAssets
, a folder in the project root, to the assets.
android {
sourceSets {
main.assets.srcDirs += '../moreAssets'
}
}
You can do like below to achieve your result:
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
....
....
#use filter with plot
#or
fg=sns.factorplot('Retailer country', data=df1[(df1['Retailer country']=='United States') | (df1['Retailer country']=='France')], kind='count')
fg.set_xlabels('Retailer country')
plt.show()
#also
#and
fg=sns.factorplot('Retailer country', data=df1[(df1['Retailer country']=='United States') & (df1['Year']=='2013')], kind='count')
fg.set_xlabels('Retailer country')
plt.show()
You will have to assign both left
and right
property 0
value for margin: auto
to center the logo.
So in this case:
#logo {
background:red;
height:50px;
position:absolute;
width:50px;
left: 0;
right: 0;
margin: 0 auto;
}
You might also want to set position: relative
for #header
.
This works because, setting left
and right
to zero will horizontally stretch the absolutely positioned element. Now magic happens when margin
is set to auto
. margin
takes up all the extra space(equally on each side) leaving the content to its specified width
. This results in content becoming center aligned.
Since the add-ons don't work anymore, the most helpful set of tools I've found is using Visual Studio/IE because you can set breakpoints in your JS and inspect your data that way. Of course Chrome and Firefox have much better dev tools in general. Also, good ol' console.log() has been super helpful!
You just need to override the method for back button. You can leave the method empty if you want so that nothing will happen when you press back button. Please have a look at the code below:
@Override
public void onBackPressed()
{
// Your Code Here. Leave empty if you want nothing to happen on back press.
}
You don't need the executable for setuptools.
You can download the source code, unpack it, traverse to the downloaded directory and run python setup.py install
in the command prompt
The answer to this question has changed over the years. The current answer is here at the top, followed by the various answers over the years in chronological order:
You can use fs.existsSync()
:
const fs = require("fs"); // Or `import fs from "fs";` with ESM
if (fs.existsSync(path)) {
// Do something
}
It was deprecated for several years, but no longer is. From the docs:
Note that
fs.exists()
is deprecated, butfs.existsSync()
is not. (The callback parameter tofs.exists()
accepts parameters that are inconsistent with other Node.js callbacks.fs.existsSync()
does not use a callback.)
You've specifically asked for a synchronous check, but if you can use an asynchronous check instead (usually best with I/O), use fs.promises.access
if you're using async
functions or fs.access
(since exists
is deprecated) if not:
In an async
function:
try {
await fs.promises.access("somefile");
// The check succeeded
} catch (error) {
// The check failed
}
Or with a callback:
fs.access("somefile", error => {
if (!error) {
// The check succeeded
} else {
// The check failed
}
});
Here are the historical answers in chronological order:
stat
/statSync
or lstat
/lstatSync
)exists
/existsSync
)exists
/existsSync
, so we're probably back to stat
/statSync
or lstat
/lstatSync
)fs.access(path, fs.F_OK, function(){})
/ fs.accessSync(path, fs.F_OK)
, but note that if the file/directory doesn't exist, it's an error; docs for fs.stat
recommend using fs.access
if you need to check for existence without opening)fs.exists()
is still deprecated but fs.existsSync()
is no longer deprecated. So you can safely use it now.You can use statSync
or lstatSync
(docs link), which give you an fs.Stats
object. In general, if a synchronous version of a function is available, it will have the same name as the async version with Sync
at the end. So statSync
is the synchronous version of stat
; lstatSync
is the synchronous version of lstat
, etc.
lstatSync
tells you both whether something exists, and if so, whether it's a file or a directory (or in some file systems, a symbolic link, block device, character device, etc.), e.g. if you need to know if it exists and is a directory:
var fs = require('fs');
try {
// Query the entry
stats = fs.lstatSync('/the/path');
// Is it a directory?
if (stats.isDirectory()) {
// Yes it is
}
}
catch (e) {
// ...
}
...and similarly, if it's a file, there's isFile
; if it's a block device, there's isBlockDevice
, etc., etc. Note the try/catch
; it throws an error if the entry doesn't exist at all.
If you don't care what the entry is and only want to know whether it exists, you can use path.existsSync
(or with latest, fs.existsSync
) as noted by user618408:
var path = require('path');
if (path.existsSync("/the/path")) { // or fs.existsSync
// ...
}
It doesn't require a try/catch
but gives you no information about what the thing is, just that it's there. path.existsSync
was deprecated long ago.
Side note: You've expressly asked how to check synchronously, so I've used the xyzSync
versions of the functions above. But wherever possible, with I/O, it really is best to avoid synchronous calls. Calls into the I/O subsystem take significant time from a CPU's point of view. Note how easy it is to call lstat
rather than lstatSync
:
// Is it a directory?
lstat('/the/path', function(err, stats) {
if (!err && stats.isDirectory()) {
// Yes it is
}
});
But if you need the synchronous version, it's there.
The below answer from a couple of years ago is now a bit out of date. The current way is to use fs.existsSync
to do a synchronous check for file/directory existence (or of course fs.exists
for an asynchronous check), rather than the path
versions below.
Example:
var fs = require('fs');
if (fs.existsSync(path)) {
// Do something
}
// Or
fs.exists(path, function(exists) {
if (exists) {
// Do something
}
});
And here we are in 2015 and the Node docs now say that fs.existsSync
(and fs.exists
) "will be deprecated". (Because the Node folks think it's dumb to check whether something exists before opening it, which it is; but that's not the only reason for checking whether something exists!)
So we're probably back to the various stat
methods... Until/unless this changes yet again, of course.
Don't know how long it's been there, but there's also fs.access(path, fs.F_OK, ...)
/ fs.accessSync(path, fs.F_OK)
. And at least as of October 2016, the fs.stat
documentation recommends using fs.access
to do existence checks ("To check if a file exists without manipulating it afterwards, fs.access()
is recommended."). But note that the access not being available is considered an error, so this would probably be best if you're expecting the file to be accessible:
var fs = require('fs');
try {
fs.accessSync(path, fs.F_OK);
// Do something
} catch (e) {
// It isn't accessible
}
// Or
fs.access(path, fs.F_OK, function(err) {
if (!err) {
// Do something
} else {
// It isn't accessible
}
});
You can use fs.existsSync()
:
if (fs.existsSync(path)) {
// Do something
}
It was deprecated for several years, but no longer is. From the docs:
Note that
fs.exists()
is deprecated, butfs.existsSync()
is not. (The callback parameter tofs.exists()
accepts parameters that are inconsistent with other Node.js callbacks.fs.existsSync()
does not use a callback.)
You don't need to have static
in function definition
Just pick up the TDM-GCC 64x package. (It constains both the 32 and 64 bit versions of the MinGW toolchain and comes within a neat installer.) More importantly, it contains something called the "winpthread" library.
It comprises of the pthread.h
header, libwinpthread.a
, libwinpthread.dll.a
static libraries for both 32-bit and 64-bit and the required .dlls libwinpthread-1.dll
and libwinpthread_64-1.dll
(this, as of 01-06-2016).
You'll need to link to the libwinpthread.a
library during build. Other than that, your code can be the same as for native Pthread code on Linux. I've so far successfully used it to compile a few basic Pthread programs in 64-bit on windows.
Alternatively, you can use the following library which wraps the windows threading API into the pthreads API: pthreads-win32.
The above two seem to be the most well known ways for this.
Hope this helps.
z = (x == y ? 1 : 2);
is equivalent to
if (x == y)
z = 1;
else
z = 2;
except, of course, it's shorter.
It should also be mentioned that <span>
tags allow inside them -- block-level items negate MD natively inside them unless you configure them not to do so, but in-line styles natively allow MD within them. As such, I often do something akin to...
This is a superfluous paragraph thing.
<span class="class-red">And thus I delve into my topic, Lorem ipsum lollipop bubblegum.</span>
And thus with that I conclude.
I am not 100% sure if this is universal but seems to be the case in all MD editors I've used.
You can write this
class Human {
private firstName : string;
private lastName : string;
constructor (
public FirstName?:string,
public LastName?:string) {
}
get FirstName() : string {
console.log("Get FirstName : ", this.firstName);
return this.firstName;
}
set FirstName(value : string) {
console.log("Set FirstName : ", value);
this.firstName = value;
}
get LastName() : string {
console.log("Get LastName : ", this.lastName);
return this.lastName;
}
set LastName(value : string) {
console.log("Set LastName : ", value);
this.lastName = value;
}
}
Since the string is not complex, no need to add RegEx strings. A simple match will do the trick
$line = "----start----Hello World----end----"
$line -match "Hello World"
$matches[0]
Hello World
$result = $matches[0]
$result
Hello World
If your coordinates are stored as complex numbers you can use cmath
What do you mean by impacts? Content will flow around a float. That's how they work.
If you want it to appear above your design, try setting:
z-index: 10;
position: absolute;
right: 0;
top: 0;
Try this, using the prototype.js
library:
string.escapeHTML();
In case of Mac OS X Maverick when MySQL is installed via Homebrew it's located at /usr/local/opt/mysql/my.cnf
Don't transform to string and compare. This is not good for perfomance.
In the junit, inside Corematchers, there's a matcher for this => hasItems
List<Integer> yourList = Arrays.asList(1,2,3,4)
assertThat(yourList, CoreMatchers.hasItems(1,2,3,4,5));
This is the better way that I know of to check elements in a list.
You have to define your TASK_CAT
column first and then set foreign key on it.
private static final String TASK_TABLE_CREATE = "create table "
+ TASK_TABLE + " ("
+ TASK_ID + " integer primary key autoincrement, "
+ TASK_TITLE + " text not null, "
+ TASK_NOTES + " text not null, "
+ TASK_DATE_TIME + " text not null,"
+ TASK_CAT + " integer,"
+ " FOREIGN KEY ("+TASK_CAT+") REFERENCES "+CAT_TABLE+"("+CAT_ID+"));";
More information you can find on sqlite foreign keys doc.
^https?://
You might have to escape the forward slashes though, depending on context.
If you want to run the same command on multiple instances you can do this :
for i in c1 dm1 dm2 ds1 ds2 gtm_m gtm_sl; do docker exec -it $i /bin/bash -c "service sshd start"; done
In addition to the aforementioned std::div family of functions, there is also the std::remquo family of functions, return the rem-ainder and getting the quo-tient via a passed-in pointer.
[Edit:] It looks like std::remquo doesn't really return the quotient after all.
If you want to see dependencies on project and all subprojects use in your top-level build.gradle:
subprojects {
task listAllDependencies(type: DependencyReportTask) {}
}
Then call gradle:
gradle listAllDependencies
I came here looking for making an input that's actually multiple lines. Turns out I didn't want an input, I wanted a textarea. You can set height or line-height as other answers specify, but it'll still just be one line of a textbox. If you want actual multiple lines, use a textarea instead. The following is an example of a 3-row textarea with a width of 500px (should be a good part of the page, not necessary to set this and will have to change it based on your requirements).
<textarea name="roleExplanation" style="width: 500px" rows="3">This role is for facility managers and holds the highest permissions in the application.</textarea>
print(os.path.join(os.path.dirname(__file__)))
You can also use this way
This is not a function of Maven; it's a function of the compiler. Look closely; the information you're looking for is most likely in the following line.
In my understanding, Get-Content eliminates ALL newlines/carriage returns when it rolls your text file through the pipeline. To do multiline regexes, you have to re-combine your string array into one giant string. I do something like:
$text = [string]::Join("`n", (Get-Content test.txt))
[regex]::Replace($text, "t`n", "ting`na ", "Singleline")
Clarification: small files only folks! Please don't try this on your 40 GB log file :)
Well when you are writing a c program and want the output log to stay instead of flickering away you only need to import the stdlib.h header file and type "system("PAUSE");" at the place you want the output screen to halt.Look at the example here.The following simple c program prints the product of 5 and 6 i.e 30 to the output window and halts the output window.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,b,c;
a=5;b=6;
c=a*b;
printf("%d",c);
system("PAUSE");
return 0;
}
Hope this helped.
Based on @carlosfigueira 's answer, I looked further into WebClient's methods and found UploadValues, which is exactly what I want:
Using client As New Net.WebClient
Dim reqparm As New Specialized.NameValueCollection
reqparm.Add("param1", "somevalue")
reqparm.Add("param2", "othervalue")
Dim responsebytes = client.UploadValues(someurl, "POST", reqparm)
Dim responsebody = (New Text.UTF8Encoding).GetString(responsebytes)
End Using
The key part is this:
client.UploadValues(someurl, "POST", reqparm)
It sends whatever verb I type in, and it also helps me create a properly url encoded form data, I just have to supply the parameters as a namevaluecollection.
The solution is to use JS to horizontally scroll the top div so that it matches the bottom div.
You must be very careful to make sure the top and bottom are exactly the same sizes, for example you might need to make the TD and TH use fixed widths.
Here is a fiddle https://jsfiddle.net/jdhenckel/yzjhk08h/5/
The important parts: CSS use
.head {
overflow-x: hidden;
overflow-y: scroll;
width: 500px;
}
.lower {
overflow-x: auto;
overflow-y: scroll;
width: 500px;
height: 400px;
}
Notice overflow-y
must be the same on both head and lower.
And the Javascript...
var head = document.querySelector('.head');
var lower = document.querySelector('.lower');
lower.addEventListener('scroll', function (e) {
console.log(lower.scrollLeft);
head.scrollLeft = lower.scrollLeft;
});
i don't know of a simple css(2.1 standard)-only solution for circles, but for squares you can do easily:
.squared {
border: 2x solid black;
}
then, use the following html code:
<img src="…" alt="an image " class="squared" />
Simply put, you need to rewrite all of your database connections and queries.
You are using mysql_*
functions which are now deprecated and will be removed from PHP in the future. So you need to start using MySQLi or PDO instead, just as the error notice warned you.
A basic example of using PDO (without error handling):
<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$result = $db->exec("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')");
$insertId = $db->lastInsertId();
?>
A basic example of using MySQLi (without error handling):
$db = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
$result = $db->query("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')");
Here's a handy little PDO tutorial to get you started. There are plenty of others, and ones about the PDO alternative, MySQLi.
To make values empty you can do the following:
$("#element").val('');
To get the selected value you can do:
var value = $("#element").val();
Where #element
is the id of the element you wish to select.
best answer written by Dmitri Korotkevitch:
Speaking of the installation, SQL Server 2008 allows you to set authentication mode (Windows or SQL Server) during the installation process. You will be forced to choose the strong password for sa user in the case if you choose sql server authentication mode during setup.
If you install SQL Server with Windows Authentication mode and want to change it, you need to do 2 different things:
Go to SQL Server Properties/Security tab and change the mode to SQL Server authentication mode
Go to security/logins, open SA login properties
a. Uncheck "Enforce password policy" and "Enforce password expiration" check box there if you decide to use weak password
b. Assign password to SA user
c. Open "Status" tab and enable login.
I don't need to mention that every action from above would violate security best practices that recommend to use windows authentication mode, have sa login disabled and use strong passwords especially for sa login.
This function is identical to the post function, only it fetches get data:
$this->input->get()
You could use an asymmetrical border to make curves with CSS.
border-radius: 50%/100px 100px 0 0;
.box {_x000D_
width: 500px; _x000D_
height: 100px; _x000D_
border: solid 5px #000;_x000D_
border-color: #000 transparent transparent transparent;_x000D_
border-radius: 50%/100px 100px 0 0;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
The compiler is allowed to make one implicit conversion to resolve the parameters to a function. What this means is that the compiler can use constructors callable with a single parameter to convert from one type to another in order to get the right type for a parameter.
Here's an example class with a constructor that can be used for implicit conversions:
class Foo
{
public:
// single parameter constructor, can be used as an implicit conversion
Foo (int foo) : m_foo (foo)
{
}
int GetFoo () { return m_foo; }
private:
int m_foo;
};
Here's a simple function that takes a Foo
object:
void DoBar (Foo foo)
{
int i = foo.GetFoo ();
}
and here's where the DoBar
function is called:
int main ()
{
DoBar (42);
}
The argument is not a Foo
object, but an int
. However, there exists a constructor for Foo
that takes an int
so this constructor can be used to convert the parameter to the correct type.
The compiler is allowed to do this once for each parameter.
Prefixing the explicit
keyword to the constructor prevents the compiler from using that constructor for implicit conversions. Adding it to the above class will create a compiler error at the function call DoBar (42)
. It is now necessary to call for conversion explicitly with DoBar (Foo (42))
The reason you might want to do this is to avoid accidental construction that can hide bugs.
Contrived example:
MyString(int size)
class with a constructor that constructs a string of the given size. You have a function print(const MyString&)
, and you call print(3)
(when you actually intended to call print("3")
). You expect it to print "3", but it prints an empty string of length 3 instead.After execute the thread, add these two line of code, and that will solve the issue.
Looper.loop();
Looper.myLooper().quit();
From the YouTube help:
You will automatically be opted into showing ads on embedded videos if you've associated your YouTube and AdSense accounts and have enabled your videos for embedding.
If you don't want to show overlay ads on your embedded videos, you can opt your videos out of showing overlay ads, though this will also disable overlay ads on your videos on YouTube.com. You may also disable your videos for embedding.
https://support.google.com/youtube/answer/132596?hl=en
Another technical solution could be to use a custom video player, and streamline the youtube video with that one. Have not tried but guess that the ads cannot be displayed in a custom player. However, could be forbidden.
Here are two ways two achieve it.
WAY 1: As you have to split two numbers by a special character you can use regex
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TrialClass
{
public static void main(String[] args)
{
Pattern p = Pattern.compile("[0-9]+");
Matcher m = p.matcher("004-034556");
while(m.find())
{
System.out.println(m.group());
}
}
}
WAY 2: Using the string split method
public class TrialClass
{
public static void main(String[] args)
{
String temp = "004-034556";
String [] arrString = temp.split("-");
for(String splitString:arrString)
{
System.out.println(splitString);
}
}
}
//Convert input format 19-FEB-16 01.00.00.000000000 PM to 2016-02-19 01.00.000 PM
SimpleDateFormat inFormat = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.SSSSSSSSS aaa");
Date today = new Date();
Date d1 = inFormat.parse("19-FEB-16 01.00.00.000000000 PM");
SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd hh.mm.ss.SSS aaa");
System.out.println("Out date ="+outFormat.format(d1));
If you're on Windows:
Go to your php.ini file and remove the ;
mark from the beginning of the following line:
;extension=php_curl.dll
After you have saved the file you must restart your HTTP server software (e.g. Apache) before this can take effect.
For Ubuntu 13.0 and above, simply use the debundled package. In a terminal type the following to install it and do not forgot to restart server.
sudo apt-get install php-curl
Or if you're using the old PHP5
sudo apt-get install php5-curl
or
sudo apt-get install php5.6-curl
Then restart apache to activate the package with
sudo service apache2 restart
I think you have to use the GetValueOrDefault-Methode. The behaviour with ToString("yy...") is not defined if the instance is null.
dt2.GetValueOrDefault().ToString("yyy...");
From Laravel 5.6 you can use whereDate:
$users = Users::where('status_id', 'active')
->whereDate( 'created_at', '>', now()->subDays(30))
->get();
You also have whereMonth / whereDay / whereYear / whereTime
if you want php you can count the array and just make an if statement like
if((int)count($_FILES['i_dont_know_whats_coming_next'] > 2)
echo "error message";
To select the node's contents call:
window.getSelection().selectAllChildren(
document.getElementById(id)
);
This works on all modern browsers including IE9+ (in standards mode).
function select(id) {_x000D_
window.getSelection()_x000D_
.selectAllChildren(_x000D_
document.getElementById("target-div") _x000D_
);_x000D_
}
_x000D_
#outer-div { padding: 1rem; background-color: #fff0f0; }_x000D_
#target-div { padding: 1rem; background-color: #f0fff0; }_x000D_
button { margin: 1rem; }
_x000D_
<div id="outer-div">_x000D_
<div id="target-div">_x000D_
Some content for the _x000D_
<br>Target DIV_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<button onclick="select(id);">Click to SELECT Contents of #target-div</button>
_x000D_
The original answer below is obsolete since window.getSelection().addRange(range);
has been deprecated
All of the examples above use:
var range = document.createRange();
range.selectNode( ... );
but the problem with that is that it selects the Node itself including the DIV tag etc.
To select the Node's text as per the OP question you need to call instead:
range.selectNodeContents( ... )
So the full snippet would be:
function selectText( containerid ) {
var node = document.getElementById( containerid );
if ( document.selection ) {
var range = document.body.createTextRange();
range.moveToElementText( node );
range.select();
} else if ( window.getSelection ) {
var range = document.createRange();
range.selectNodeContents( node );
window.getSelection().removeAllRanges();
window.getSelection().addRange( range );
}
}
It's much simpler than all that:
while(str.Contains(" ")) str = str.Replace(" ", " ");
Any class that can be serialized (i.e. implements Serializable
) should declare that UID and it must be changed whenever anything changes that affects the serialization (additional fields, removed fields, change of field order, ...). The field's value is checked during deserialization and if the value of the serialized object does not equal the value of the class in the current VM, an exception is thrown.
Note that this value is special in that it is serialized with the object even though it is static, for the reasons described above.
Run top then press OpEnter. Now processes should be sorted by their swap usage.
Here is an update as my original answer does not provide an exact answer to the problem as pointed out in the comments. From the htop FAQ:
It is not possible to get the exact size of used swap space of a process. Top fakes this information by making SWAP = VIRT - RES, but that is not a good metric, because other stuff such as video memory counts on VIRT as well (for example: top says my X process is using 81M of swap, but it also reports my system as a whole is using only 2M of swap. Therefore, I will not add a similar Swap column to htop because I don't know a reliable way to get this information (actually, I don't think it's possible to get an exact number, because of shared pages).
The perfect solution which works undoubtedly is to just add these packages to your app:
https://mvnrepository.com/artifact/org.slf4j/slf4j-api/1.7.2
http://archive.apache.org/dist/logging/log4j/1.2.16/
after adding so you may encounter following WARNING which you can simply ignore!
SLF4J: No SLF4J providers were found.
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#noProviders for further details.
There are few things to set up so your link in the browser will look like http://yourdomain.com/path
and these are your angular config + server side
1) AngularJS
$routeProvider
.when('/path', {
templateUrl: 'path.html',
});
$locationProvider
.html5Mode(true);
2) server side, just put .htaccess
inside your root folder and paste this
RewriteEngine On
Options FollowSymLinks
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /#/$1 [L]
More interesting stuff to read about html5 mode in angularjs and the configuration required per different environment https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode Also this question might help you $location / switching between html5 and hashbang mode / link rewriting
Here is a pure CSS (no images) cross-browser solution based on Martin's Custom Checkboxes and Radio Buttons with CSS3 LINK: http://martinivanov.net/2012/12/21/imageless-custom-checkboxes-and-radio-buttons-with-css3-revisited/
Here is a jsFiddle: http://jsfiddle.net/DJRavine/od26wL6n/
I have tested this on the following browsers:
label,_x000D_
input[type="radio"] + span,_x000D_
input[type="radio"] + span::before,_x000D_
label,_x000D_
input[type="checkbox"] + span,_x000D_
input[type="checkbox"] + span::before_x000D_
{_x000D_
display: inline-block;_x000D_
vertical-align: middle;_x000D_
}_x000D_
_x000D_
label *,_x000D_
label *_x000D_
{_x000D_
cursor: pointer;_x000D_
}_x000D_
_x000D_
input[type="radio"],_x000D_
input[type="checkbox"]_x000D_
{_x000D_
opacity: 0;_x000D_
position: absolute;_x000D_
}_x000D_
_x000D_
input[type="radio"] + span,_x000D_
input[type="checkbox"] + span_x000D_
{_x000D_
font: normal 11px/14px Arial, Sans-serif;_x000D_
color: #333;_x000D_
}_x000D_
_x000D_
label:hover span::before,_x000D_
label:hover span::before_x000D_
{_x000D_
-moz-box-shadow: 0 0 2px #ccc;_x000D_
-webkit-box-shadow: 0 0 2px #ccc;_x000D_
box-shadow: 0 0 2px #ccc;_x000D_
}_x000D_
_x000D_
label:hover span,_x000D_
label:hover span_x000D_
{_x000D_
color: #000;_x000D_
}_x000D_
_x000D_
input[type="radio"] + span::before,_x000D_
input[type="checkbox"] + span::before_x000D_
{_x000D_
content: "";_x000D_
width: 12px;_x000D_
height: 12px;_x000D_
margin: 0 4px 0 0;_x000D_
border: solid 1px #a8a8a8;_x000D_
line-height: 14px;_x000D_
text-align: center;_x000D_
_x000D_
-moz-border-radius: 100%;_x000D_
-webkit-border-radius: 100%;_x000D_
border-radius: 100%;_x000D_
_x000D_
background: #f6f6f6;_x000D_
background: -moz-radial-gradient(#f6f6f6, #dfdfdf);_x000D_
background: -webkit-radial-gradient(#f6f6f6, #dfdfdf);_x000D_
background: -ms-radial-gradient(#f6f6f6, #dfdfdf);_x000D_
background: -o-radial-gradient(#f6f6f6, #dfdfdf);_x000D_
background: radial-gradient(#f6f6f6, #dfdfdf);_x000D_
}_x000D_
_x000D_
input[type="radio"]:checked + span::before,_x000D_
input[type="checkbox"]:checked + span::before_x000D_
{_x000D_
color: #666;_x000D_
}_x000D_
_x000D_
input[type="radio"]:disabled + span,_x000D_
input[type="checkbox"]:disabled + span_x000D_
{_x000D_
cursor: default;_x000D_
_x000D_
-moz-opacity: .4;_x000D_
-webkit-opacity: .4;_x000D_
opacity: .4;_x000D_
}_x000D_
_x000D_
input[type="checkbox"] + span::before_x000D_
{_x000D_
-moz-border-radius: 2px;_x000D_
-webkit-border-radius: 2px;_x000D_
border-radius: 2px;_x000D_
}_x000D_
_x000D_
input[type="radio"]:checked + span::before_x000D_
{_x000D_
content: "\2022";_x000D_
font-size: 30px;_x000D_
margin-top: -1px;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:checked + span::before_x000D_
{_x000D_
content: "\2714";_x000D_
font-size: 12px;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
input[class="blue"] + span::before_x000D_
{_x000D_
border: solid 1px blue;_x000D_
background: #B2DBFF;_x000D_
background: -moz-radial-gradient(#B2DBFF, #dfdfdf);_x000D_
background: -webkit-radial-gradient(#B2DBFF, #dfdfdf);_x000D_
background: -ms-radial-gradient(#B2DBFF, #dfdfdf);_x000D_
background: -o-radial-gradient(#B2DBFF, #dfdfdf);_x000D_
background: radial-gradient(#B2DBFF, #dfdfdf);_x000D_
}_x000D_
input[class="blue"]:checked + span::before_x000D_
{_x000D_
color: darkblue;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
input[class="red"] + span::before_x000D_
{_x000D_
border: solid 1px red;_x000D_
background: #FF9593;_x000D_
background: -moz-radial-gradient(#FF9593, #dfdfdf);_x000D_
background: -webkit-radial-gradient(#FF9593, #dfdfdf);_x000D_
background: -ms-radial-gradient(#FF9593, #dfdfdf);_x000D_
background: -o-radial-gradient(#FF9593, #dfdfdf);_x000D_
background: radial-gradient(#FF9593, #dfdfdf);_x000D_
}_x000D_
input[class="red"]:checked + span::before_x000D_
{_x000D_
color: darkred;_x000D_
}
_x000D_
<label><input type="radio" checked="checked" name="radios-01" /><span>checked radio button</span></label>_x000D_
<label><input type="radio" name="radios-01" /><span>unchecked radio button</span></label>_x000D_
<label><input type="radio" name="radios-01" disabled="disabled" /><span>disabled radio button</span></label>_x000D_
_x000D_
<br/>_x000D_
_x000D_
<label><input type="radio" checked="checked" name="radios-02" class="blue" /><span>checked radio button</span></label>_x000D_
<label><input type="radio" name="radios-02" class="blue" /><span>unchecked radio button</span></label>_x000D_
<label><input type="radio" name="radios-02" disabled="disabled" class="blue" /><span>disabled radio button</span></label>_x000D_
_x000D_
<br/>_x000D_
_x000D_
<label><input type="radio" checked="checked" name="radios-03" class="red" /><span>checked radio button</span></label>_x000D_
<label><input type="radio" name="radios-03" class="red" /><span>unchecked radio button</span></label>_x000D_
<label><input type="radio" name="radios-03" disabled="disabled" class="red" /><span>disabled radio button</span></label>_x000D_
_x000D_
<br/>_x000D_
_x000D_
<label><input type="checkbox" checked="checked" name="checkbox-01" /><span>selected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-02" /><span>unselected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-03" disabled="disabled" /><span>disabled checkbox</span></label>_x000D_
_x000D_
<br/>_x000D_
_x000D_
<label><input type="checkbox" checked="checked" name="checkbox-01" class="blue" /><span>selected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-02" class="blue" /><span>unselected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-03" disabled="disabled" class="blue" /><span>disabled checkbox</span></label>_x000D_
_x000D_
<br/>_x000D_
_x000D_
<label><input type="checkbox" checked="checked" name="checkbox-01" class="red" /><span>selected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-02" class="red" /><span>unselected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-03" disabled="disabled" class="red" /><span>disabled checkbox</span></label>
_x000D_
Actually, that one liner doesn't work for windows xp since the ver contains xp in the string. Instead of 5.1 which you want, you would get [Version.5 because of the added token.
I modified the command to look like this:
for /f "tokens=4-6 delims=[. " %%i in ('ver') do set VERSION=%%i.%%j
This will output Version.5 for xp systems which you can use to indentify said system inside a batch file. Sadly, this means the command cannot differentiate between 32bit
and 64bit
build since it doesn't read the .2 from 5.2 that denotes 64bit
XP.
You could make it assign %%k
that token but doing so would make this script not detect windows vista, 7, or 8 properly as they have one token less in their ver string. Hope this helps!
Check out startOfDay([offset]). That gets what you are looking for without the pesky time constraints and its built in as of 4.3.x. It also has variants like endOfDay, startOfWeek, startOfMonth, etc.
It works with just this:
.slideContainer {
white-space: nowrap;
}
.slide {
display: inline-block;
width: 600px;
white-space: normal;
}
I did originally have float : left;
and that prevented it from working correctly.
Thanks for posting this solution.
2 ways:-
1st one Custom Query
@Modifying
@Query("delete from User where firstName = :firstName")
void deleteUsersByFirstName(@Param("firstName") String firstName);
2nd one JPA Query by method
List<User> deleteByLastname(String lastname);
When you go with query by method (2nd way) it will first do a get call
select * from user where last_name = :firstName
Then it will load it in a List Then it will call delete id one by one
delete from user where id = 18
delete from user where id = 19
First fetch list of object, then for loop to delete id one by one
But, the 1st option (custom query),
It's just a single query It will delete wherever the value exists.
Go through this link too https://www.baeldung.com/spring-data-jpa-deleteby
Or you can use the ^M+^J shortcut also. All a matter of preference. the "CTRL-CHAR" codes are translated by the compiler.
MyString := 'Hello,' + ^M + ^J + 'world!';
You can take the + away between the ^M and ^J, but then you will get a warning by the compiler (but it will still compile fine).
Apart of directly writing HTML on the PrintWriter obtained from the response (which is the standard way of outputting HTML from a Servlet), you can also include an HTML fragment contained in an external file by using a RequestDispatcher:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("HTML from an external file:");
request.getRequestDispatcher("/pathToFile/fragment.html")
.include(request, response);
out.close();
}
In Chrome, window.onload is different from <body onload="">
, whereas they are the same in both Firefox(version 35.0) and IE (version 11).
You could explore that by the following snippet:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!--import css here-->
<!--import js scripts here-->
<script language="javascript">
function bodyOnloadHandler() {
console.log("body onload");
}
window.onload = function(e) {
console.log("window loaded");
};
</script>
</head>
<body onload="bodyOnloadHandler()">
Page contents go here.
</body>
</html>
And you will see both "window loaded"(which comes firstly) and "body onload" in Chrome console. However, you will see just "body onload" in Firefox and IE. If you run "window.onload.toString()
" in the consoles of IE & FF, you will see:
"function onload(event) { bodyOnloadHandler() }"
which means that the assignment "window.onload = function(e)..." is overwritten.
Iterate over the grep results with a while/read loop. Like:
grep pattern filename.txt | while read -r line ; do
echo "Matched Line: $line"
# your code goes here
done
You can try put in a shortcut to the site and tell the .bat file to open that.
start Google.HTML
exit
Public Declare Function GetUserName Lib "advapi32.dll"
Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
....
Dim strLen As Long
Dim strtmp As String * 256
Dim strUserName As String
strLen = 255
GetUserName strtmp, strLen
strUserName = Trim$(TrimNull(strtmp))
Turns out question has been asked before: How can I get the currently logged-in windows user in Access VBA?
You don't need the date
validator. It doesn't support dd/mm/yyyy format, and that's why you are getting "Please enter a valid date" message for input like 13/01/2014. You already have the dateITA
validator, which uses dd/mm/yyyy format as you need.
Just like the date
validator, your code for dateGreaterThan
and dateLessThan
calls new Date
for input string and has the same issue parsing dates. You can use a function like this to parse the date:
function parseDMY(value) {
var date = value.split("/");
var d = parseInt(date[0], 10),
m = parseInt(date[1], 10),
y = parseInt(date[2], 10);
return new Date(y, m - 1, d);
}
You can use finds null separated output option with read to iterate over directory structures safely.
#!/bin/bash
find . -type f -print0 | while IFS= read -r -d $'\0' file;
do echo "$file" ;
done
So for your case
#!/bin/bash
find . -maxdepth 1 -type f -print0 | while IFS= read -r -d $'\0' file; do
for ((i=0; i<=3; i++)); do
./MyProgram.exe "$file" 'Logs/'"`basename "$file"`""$i"'.txt'
done
done
additionally
#!/bin/bash
while IFS= read -r -d $'\0' file; do
for ((i=0; i<=3; i++)); do
./MyProgram.exe "$file" 'Logs/'"`basename "$file"`""$i"'.txt'
done
done < <(find . -maxdepth 1 -type f -print0)
will run the while loop in the current scope of the script ( process ) and allow the output of find to be used in setting variables if needed
int32
and time.Duration
are different types. You need to convert the int32
to a time.Duration
, such as time.Sleep(time.Duration(rand.Int31n(1000)) * time.Millisecond)
.
Just set the background of the canvas to transparent.
#canvasID{
background:transparent;
}
The current C++ standard does not have hash maps, but the coming C++0x standard does, and these are already supported by g++ in the shape of "unordered maps":
#include <unordered_map>
#include <iostream>
#include <string>
using namespace std;
int main() {
unordered_map <string, int> m;
m["foo"] = 42;
cout << m["foo"] << endl;
}
In order to get this compile, you need to tell g++ that you are using C++0x:
g++ -std=c++0x main.cpp
These maps work pretty much as std::map does, except that instead of providing a custom operator<()
for your own types, you need to provide a custom hash function - suitable functions are provided for types like integers and strings.
Notice the repetition of Book
in Booknumber (int), Booktitle (string), Booklanguage (string), Bookprice (int)
- it screams for a class type.
class Book {
int number;
String title;
String language;
int price;
}
Now you can simply have:
Book[] books = new Books[3];
If you want arrays, you can declare it as object array an insert Integer
and String
into it:
Object books[3][4]
Per your pastebin, you need to add the proxy.tkk.com
certificate to the truststore.
IEnumerable and IEnumerator (and their generic counterparts IEnumerable<T> and IEnumerator<T>) are base interfaces of iterator implementations in .Net Framework Class Libray collections.
IEnumerable is the most common interface you would see in the majority of the code out there. It enables the foreach loop, generators (think yield) and because of its tiny interface, it's used to create tight abstractions. IEnumerable depends on IEnumerator.
IEnumerator, on the other hand, provides a slightly lower level iteration interface. It's referred to as the explicit iterator which gives the programmer more control over the iteration cycle.
IEnumerable is a standard interface that enables iterating over collections that supports it (in fact, all collection types I can think of today implements IEnumerable). Compiler support allows language features like foreach
. In general terms, it enables this implicit iterator implementation.
foreach (var value in list)
Console.WriteLine(value);
I think foreach
loop is one of the main reasons for using IEnumerable interfaces. foreach
has a very succinct syntax and very easy to understand compared to classic C style for loops where you need to check the various variables to see what it was doing.
Probably a lesser known feature is that IEnumerable also enables generators in C# with the use of yield return
and yield break
statements.
IEnumerable<Thing> GetThings() {
if (isNotReady) yield break;
while (thereIsMore)
yield return GetOneMoreThing();
}
Another common scenario in practice is using IEnumerable to provide minimalistic abstractions. Because it is a minuscule and read-only interface, you are encouraged to expose your collections as IEnumerable (rather than List for example). That way you are free to change your implementation without breaking your client's code (change List to a LinkedList for instance).
One behaviour to be aware of is that in streaming implementations (e.g. retrieving data row by row from a database, instead of loading all the results in memory first) you cannot iterate over the collection more than once. This is in contrast to in-memory collections like List, where you can iterate multiple times without problems. ReSharper, for example, has a code inspection for Possible multiple enumeration of IEnumerable.
IEnumerator, on the other hand, is the behind the scenes interface which makes IEnumerble-foreach-magic work. Strictly speaking, it enables explicit iterators.
var iter = list.GetEnumerator();
while (iter.MoveNext())
Console.WriteLine(iter.Current);
In my experience IEnumerator is rarely used in common scenarios due to its more verbose syntax and slightly confusing semantics (at least to me; e.g. MoveNext() returns a value as well, which the name doesn't suggest at all).
I only used IEnumerator in particular (slightly lower level) libraries and frameworks where I was providing IEnumerable interfaces. One example is a data stream processing library which provided series of objects in a foreach
loop even though behind the scenes data was collected using various file streams and serialisations.
Client code
foreach(var item in feed.GetItems())
Console.WriteLine(item);
Library
IEnumerable GetItems() {
return new FeedIterator(_fileNames)
}
class FeedIterator: IEnumerable {
IEnumerator GetEnumerator() {
return new FeedExplicitIterator(_stream);
}
}
class FeedExplicitIterator: IEnumerator {
DataItem _current;
bool MoveNext() {
_current = ReadMoreFromStream();
return _current != null;
}
DataItem Current() {
return _current;
}
}
Step 1
yarn add @angular/material @angular/cdk @angular/animations
Step 2 - Create a new file( /myApp/src/app/material.module.ts ) that includes all the material UI modules (there is no shortcut, you have to include individual modules one by one)
import { NgModule } from '@angular/core';
import {
MatButtonModule,
MatMenuModule,
MatToolbarModule,
MatIconModule,
MatCardModule
} from '@angular/material';
@NgModule({
imports: [
MatButtonModule,
MatMenuModule,
MatToolbarModule,
MatIconModule,
MatCardModule
],
exports: [
MatButtonModule,
MatMenuModule,
MatToolbarModule,
MatIconModule,
MatCardModule
]
})
export class MaterialModule {}
Step 3 - Import and add that newly created module to your app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { MaterialModule } from './material.module'; // material module imported
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
MaterialModule // MAteria module added
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
No, a view is static. One thing you can do (depending on the version of SQl server) is index a view.
In your example (querying only one table), an indexed view has no benefit to simply querying the table with an index on it, but if you are doing a lot of joins on tables with join conditions, an indexed view can greatly improve performance.
Inside file strings.xml
define a String resource like this:
<string name="string_to_format">Amount: %1$f for %2$d days%3$s</string>
Inside your code (assume it inherits from Context) simply do the following:
String formattedString = getString(R.string.string_to_format, floatVar, decimalVar, stringVar);
(In comparison to the answer from LocalPCGuy or Giovanny Farto M. the String.format method is not needed.)
numpy has a great tool for this task ("numpy.reshape") link to reshape documentation
a = [[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]
[ 8 9]
[10 11]
[12 13]
[14 15]
[16 17]]
`numpy.reshape(a,(3,3))`
you can also use the "-1" trick
`a = a.reshape(-1,3)`
the "-1" is a wild card that will let the numpy algorithm decide on the number to input when the second dimension is 3
so yes.. this would also work:
a = a.reshape(3,-1)
and this:
a = a.reshape(-1,2)
would do nothing
and this:
a = a.reshape(-1,9)
would change the shape to (2,9)
You can use a "quote wall" to separate the formatted string part from the regular string part.
From:
print(f"{Hello} {42}")
to
print("{Hello}"f" {42}")
A clearer example would be
string = 10
print(f"{string} {word}")
Output:
NameError: name 'word' is not defined
Now, add the quote wall like so:
string = 10
print(f"{string}"" {word}")
Output:
10 {word}
I like the selected answer (Charles Duffy), but be careful if you are in a symlinked dir and you want the name of the target dir. Unfortunately I don't think it can be done in a single parameter expansion expression, perhaps I'm mistaken. This should work:
target_PWD=$(readlink -f .)
echo ${target_PWD##*/}
To see this, an experiment:
cd foo
ln -s . bar
echo ${PWD##*/}
reports "bar"
To show the leading directories of a path (without incurring a fork-exec of /usr/bin/dirname):
echo ${target_PWD%/*}
This will e.g. transform foo/bar/baz -> foo/bar
And here is the non jQuery answer.
Fiddle: http://jsfiddle.net/J7m7m/7/
function changeText(value) {
document.getElementById('count').value = 500 * value;
}
HTML slight modification:
Product price: $500
<br>
Total price: $500
<br>
<input type="button" onclick="changeText(2)" value="2
Qty">
<input type="button" class="mnozstvi_sleva" value="4
Qty" onClick="changeText(4)">
<br>
Total <input type="text" id="count" value="1"/>
EDIT: It is very clear that this is a non-desired way as pointed out below (I had it coming). So in essence, this is how you would do it in plain old javascript. Most people would suggest you to use jQuery (other answer has the jQuery version) for good reason.
Is this what you want:
>>> d={'a':1,'b':2,'c':3}
>>> default_val=99
>>> for k in d:
... d[k]=default_val
...
>>> d
{'a': 99, 'b': 99, 'c': 99}
>>>
>>> d={'a':1,'b':2,'c':3}
>>> from collections import defaultdict
>>> d=defaultdict(lambda:99,d)
>>> d
defaultdict(<function <lambda> at 0x03D21630>, {'a': 1, 'c': 3, 'b': 2})
>>> d[3]
99
You can use any attribute as selector with [attribute_name=value]
.
$('td[name=tcol1]').hide();
If you are using sagemath cloud version, you can simply go to the left corner,
select File --> Download as --> Pdf via LaTeX (.pdf)
Check the screenshot if you want.
Screenshot Convert ipynb to pdf
If it dosn't work for any reason, you can try another way.
select File --> Print Preview and then on the preview
right click --> Print and then select save as pdf.
You need to make the call to setDate separately from the initialization call. So to create the datepicker and set the date in one go:
$("#mydate").datepicker().datepicker("setDate", new Date());
Why it is like this I do not know. If anyone did, that would be interesting information.
If the above solutions don't work on ubuntu/linux then you can try this
sudo fuser -k -n tcp port
Run it several times to kill processes on your port of choosing. port could be 3000 for example. You would have killed all the processes if you see no output after running the command
CGRect rect = label.frame;
rect.size = [label.text sizeWithAttributes:@{NSFontAttributeName : [UIFont fontWithName:label.font.fontName size:label.font.pointSize]}];
label.frame = rect;
if you wish to make it dynamically with an animation:
view.animate()
.rotation(180)
.start();
THATS IT
this is the solution you need, you can use the errorPlacement
method to override where to put the error message
$('form').validate({
rules: {
firstname: {
minlength: 3,
maxlength: 15,
required: true
},
lastname: {
minlength: 3,
maxlength: 15,
required: true
}
},
errorPlacement: function(error, element) {
error.insertAfter('.form-group'); //So i putted it after the .form-group so it will not include to your append/prepend group.
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
}
});
it's works for me like magic. Cheers
Please find this example code, You could use hidden form with POST to send data to that your URL like below:
function open_win()
{
var ChatWindow_Height = 650;
var ChatWindow_Width = 570;
window.open("Live Chat", "chat", "height=" + ChatWindow_Height + ", width = " + ChatWindow_Width);
//Hidden Form
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "http://localhost:8080/login");
form.setAttribute("target", "chat");
//Hidden Field
var hiddenField1 = document.createElement("input");
var hiddenField2 = document.createElement("input");
//Login ID
hiddenField1.setAttribute("type", "hidden");
hiddenField1.setAttribute("id", "login");
hiddenField1.setAttribute("name", "login");
hiddenField1.setAttribute("value", "PreethiJain005");
//Password
hiddenField2.setAttribute("type", "hidden");
hiddenField2.setAttribute("id", "pass");
hiddenField2.setAttribute("name", "pass");
hiddenField2.setAttribute("value", "Pass@word$");
form.appendChild(hiddenField1);
form.appendChild(hiddenField2);
document.body.appendChild(form);
form.submit();
}
If you are working with character variables (note that stringsAsFactors
is false here) you can use replace:
junk <- data.frame(x <- rep(LETTERS[1:4], 3), y <- letters[1:12], stringsAsFactors = FALSE)
colnames(junk) <- c("nm", "val")
junk$nm <- replace(junk$nm, junk$nm == "B", "b")
junk
# nm val
# 1 A a
# 2 b b
# 3 C c
# 4 D d
# ...
Have you tried:
ifconfig 10:35978f0 down
As the physical interface is 10
and the virtual aspect is after the colon :
.
See also https://www.cyberciti.biz/faq/linux-command-to-remove-virtual-interfaces-or-network-aliases/
Here is some code which extends Object with rad(deg)
, deg(rad)
and also two more useful functions: getAngle(point1,point2)
and getDistance(point1,point2)
where a point needs to have a x
and y
property.
Object.prototype.rad = (deg) => Math.PI/180 * deg;
Object.prototype.deg = (rad) => 180/Math.PI * rad;
Object.prototype.getAngle = (point1, point2) => Math.atan2(point1.y - point2.y, point1.x - point2.x);
Object.prototype.getDistance = (point1, point2) => Math.sqrt(Math.pow(point1.x-point2.x, 2) + Math.pow(point1.y-point2.y, 2));
Quite simply the number is the precision of the timestamp, the fraction of a second held in the column:
SQL> create table t23
2 (ts0 timestamp(0)
3 , ts3 timestamp(3)
4 , ts6 timestamp(6)
5 )
6 /
Table created.
SQL> insert into t23 values (systimestamp, systimestamp, systimestamp)
2 /
1 row created.
SQL> select * from t23
2 /
TS0
---------------------------------------------------------------------------
TS3
---------------------------------------------------------------------------
TS6
---------------------------------------------------------------------------
24-JAN-12 05.57.12 AM
24-JAN-12 05.57.12.003 AM
24-JAN-12 05.57.12.002648 AM
SQL>
If we don't specify a precision then the timestamp defaults to six places.
SQL> alter table t23 add ts_def timestamp;
Table altered.
SQL> update t23
2 set ts_def = systimestamp
3 /
1 row updated.
SQL> select * from t23
2 /
TS0
---------------------------------------------------------------------------
TS3
---------------------------------------------------------------------------
TS6
---------------------------------------------------------------------------
TS_DEF
---------------------------------------------------------------------------
24-JAN-12 05.57.12 AM
24-JAN-12 05.57.12.003 AM
24-JAN-12 05.57.12.002648 AM
24-JAN-12 05.59.27.293305 AM
SQL>
Note that I'm running on Linux so my TIMESTAMP
column actually gives me precision to six places i.e. microseconds. This would also be the case on most (all?) flavours of Unix. On Windows the limit is three places i.e. milliseconds. (Is this still true of the most modern flavours of Windows - citation needed).
As might be expected, the documentation covers this. Find out more.
"when you create timestamp(9) this gives you nanos right"
Only if the OS supports it. As you can see, my OEL appliance does not:
SQL> alter table t23 add ts_nano timestamp(9)
2 /
Table altered.
SQL> update t23 set ts_nano = systimestamp(9)
2 /
1 row updated.
SQL> select * from t23
2 /
TS0
---------------------------------------------------------------------------
TS3
---------------------------------------------------------------------------
TS6
---------------------------------------------------------------------------
TS_DEF
---------------------------------------------------------------------------
TS_NANO
---------------------------------------------------------------------------
24-JAN-12 05.57.12 AM
24-JAN-12 05.57.12.003 AM
24-JAN-12 05.57.12.002648 AM
24-JAN-12 05.59.27.293305 AM
24-JAN-12 08.28.03.990557000 AM
SQL>
(Those trailing zeroes could be a coincidence but they aren't.)
It is known Chrome problem. According to Chrome and Chromium bug trackers there is no universal solution for this. This problem is not related with server type and version, it is right in Chrome.
Setting Content-Encoding
header to identity
solved this problem to me.
identity | Indicates the identity function (i.e. no compression, nor modification).
So, I can suggest, that in some cases Chrome can not perform gzip compress correctly.
I prefer to use case + than
number = 10
case number
when 1...8 then # ...
when 8...15 then # ...
when 15.. then # ...
end
sed 's/^.\{,5\}//' file.dat
worked like a charm for me
An initial reaction to this would be to ask and ensure that the two object files are being linked together. This is done at the compile stage by compiling both files at the same time:
gcc -o programName a.c b.c
Or if you want to compile separately, it would be:
gcc -c a.c
gcc -c b.c
gcc -o programName a.o b.o
When you say "in you package folder," do you mean your local app files? If so you can get a list of them using the Context.fileList() method. Just iterate through and look for your file. That's assuming you saved the original file with Context.openFileOutput().
Sample code (in an Activity):
public void onCreate(...) {
super.onCreate(...);
String[] files = fileList();
for (String file : files) {
if (file.equals(myFileName)) {
//file exits
}
}
}
Because of double print function. I suggest you to use return
instead of print
inside the function definition.
def lyrics():
return "The very first line"
print(lyrics())
OR
def lyrics():
print("The very first line")
lyrics()
The error you're getting is that self.adj
doesn't already have a key 0
. You're trying to append to a list that doesn't exist yet.
Consider using a defaultdict
instead, replacing this line (in __init__
):
self.adj = {}
with this:
self.adj = defaultdict(list)
You'll need to import at the top:
from collections import defaultdict
Now rather than raise a KeyError
, self.adj[0].append(edge)
will create a list automatically to append to.
For the allowed characters you can use
^[a-zA-Z0-9~@#$^*()_+=[\]{}|\\,.?: -]*$
to validate a complete string that should consist of only allowed characters. Note that -
is at the end (because otherwise it'd be a range) and a few characters are escaped.
For the invalid characters you can use
[<>'"/;`%]
to check for them.
To combine both into a single regex you can use
^(?=[a-zA-Z0-9~@#$^*()_+=[\]{}|\\,.?: -]*$)(?!.*[<>'"/;`%])
but you'd need a regex engine that allows lookahead.
I had the same error message, but in my case, nothing above didn't fix the problem. The solution was in "label". You need to add 'mat-label' and to put your input inside 'label' tags also. Solution of my problem is in the snippet below:
<mat-label>
Username
</mat-label>
<label>
<input
matInput
type="text"
placeholder="Your username"
formControlName="username"/>
</label>
Forcing a fixed number of characters is a bad idea. It doesn't improve the quality of the password. Worse, it reduces the number of possible passwords, so that hacking by bruteforcing becomes easier.
To generate a random word consisting of alphanumeric characters, use:
var randomstring = Math.random().toString(36).slice(-8);
Math.random() // Generate random number, eg: 0.123456
.toString(36) // Convert to base-36 : "0.4fzyo82mvyr"
.slice(-8);// Cut off last 8 characters : "yo82mvyr"
Documentation for the Number.prototype.toString
and string.prototype.slice
methods.
You want to know if the column is null
select * from foo where bar is null
If you want to check for some value not equal to something and the column also contains null values you will not get the columns with null in it
does not work:
select * from foo where bar <> 'value'
does work:
select * from foo where bar <> 'value' or bar is null
in Oracle (don't know on other DBMS) some people use this
select * from foo where NVL(bar,'n/a') <> 'value'
if I read the answer from tdammers correctly then in MS SQL Server this is like that
select * from foo where ISNULL(bar,'n/a') <> 'value'
in my opinion it is a bit of a hack and the moment 'value' becomes a variable the statement tends to become buggy if the variable contains 'n/a'.
Add an observer for the contentSize property on the table view, and adjust the frame size accordingly
[your_tableview addObserver:self forKeyPath:@"contentSize" options:0 context:NULL];
then in the callback:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
CGRect frame = your_tableview.frame;
frame.size = your_tableview.contentSize;
your_tableview.frame = frame;
}
Hope this will help you.
Array slicing like in Python (From the rebash library):
array_slice() {
local __doc__='
Returns a slice of an array (similar to Python).
From the Python documentation:
One way to remember how slices work is to think of the indices as pointing
between elements, with the left edge of the first character numbered 0.
Then the right edge of the last element of an array of length n has
index n, for example:
```
+---+---+---+---+---+---+
| 0 | 1 | 2 | 3 | 4 | 5 |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
```
>>> local a=(0 1 2 3 4 5)
>>> echo $(array.slice 1:-2 "${a[@]}")
1 2 3
>>> local a=(0 1 2 3 4 5)
>>> echo $(array.slice 0:1 "${a[@]}")
0
>>> local a=(0 1 2 3 4 5)
>>> [ -z "$(array.slice 1:1 "${a[@]}")" ] && echo empty
empty
>>> local a=(0 1 2 3 4 5)
>>> [ -z "$(array.slice 2:1 "${a[@]}")" ] && echo empty
empty
>>> local a=(0 1 2 3 4 5)
>>> [ -z "$(array.slice -2:-3 "${a[@]}")" ] && echo empty
empty
>>> [ -z "$(array.slice -2:-2 "${a[@]}")" ] && echo empty
empty
Slice indices have useful defaults; an omitted first index defaults to
zero, an omitted second index defaults to the size of the string being
sliced.
>>> local a=(0 1 2 3 4 5)
>>> # from the beginning to position 2 (excluded)
>>> echo $(array.slice 0:2 "${a[@]}")
>>> echo $(array.slice :2 "${a[@]}")
0 1
0 1
>>> local a=(0 1 2 3 4 5)
>>> # from position 3 (included) to the end
>>> echo $(array.slice 3:"${#a[@]}" "${a[@]}")
>>> echo $(array.slice 3: "${a[@]}")
3 4 5
3 4 5
>>> local a=(0 1 2 3 4 5)
>>> # from the second-last (included) to the end
>>> echo $(array.slice -2:"${#a[@]}" "${a[@]}")
>>> echo $(array.slice -2: "${a[@]}")
4 5
4 5
>>> local a=(0 1 2 3 4 5)
>>> echo $(array.slice -4:-2 "${a[@]}")
2 3
If no range is given, it works like normal array indices.
>>> local a=(0 1 2 3 4 5)
>>> echo $(array.slice -1 "${a[@]}")
5
>>> local a=(0 1 2 3 4 5)
>>> echo $(array.slice -2 "${a[@]}")
4
>>> local a=(0 1 2 3 4 5)
>>> echo $(array.slice 0 "${a[@]}")
0
>>> local a=(0 1 2 3 4 5)
>>> echo $(array.slice 1 "${a[@]}")
1
>>> local a=(0 1 2 3 4 5)
>>> array.slice 6 "${a[@]}"; echo $?
1
>>> local a=(0 1 2 3 4 5)
>>> array.slice -7 "${a[@]}"; echo $?
1
'
local start end array_length length
if [[ $1 == *:* ]]; then
IFS=":"; read -r start end <<<"$1"
shift
array_length="$#"
# defaults
[ -z "$end" ] && end=$array_length
[ -z "$start" ] && start=0
(( start < 0 )) && let "start=(( array_length + start ))"
(( end < 0 )) && let "end=(( array_length + end ))"
else
start="$1"
shift
array_length="$#"
(( start < 0 )) && let "start=(( array_length + start ))"
let "end=(( start + 1 ))"
fi
let "length=(( end - start ))"
(( start < 0 )) && return 1
# check bounds
(( length < 0 )) && return 1
(( start < 0 )) && return 1
(( start >= array_length )) && return 1
# parameters start with $1, so add 1 to $start
let "start=(( start + 1 ))"
echo "${@: $start:$length}"
}
alias array.slice="array_slice"
I just went through the same problem. And found out once you have a syntax or any type of error in you javascript, the whole file don't get loaded so you cannot use any of the other functions at all.
Just Simple Set the style attribute of ID:
To Show the hidden div
<div id="xyz" style="display:none">
...............
</div>
//In JavaScript
document.getElementById('xyz').style.display ='block'; // to hide
To hide the shown div
<div id="xyz">
...............
</div>
//In JavaScript
document.getElementById('xyz').style.display ='none'; // to display
After looking at sp_who, Oracle does not have that ability per se. Oracle has at least 8 processes running which run the db. Like RMON etc.
You can ask the DB which queries are running as that just a table query. Look at the V$ tables.
Quick Example:
SELECT sid,
opname,
sofar,
totalwork,
units,
elapsed_seconds,
time_remaining
FROM v$session_longops
WHERE sofar != totalwork;
Just move to the new branch. The uncommited changes get carried over.
git checkout -b ABC_1
git commit -m <message>
This can be achieved with the onresize property of the GlobalEventHandlers interface in JavaScript, by assigning a function to the onresize property, like so:
window.onresize = functionRef;
The following code snippet demonstrates this, by console logging the innerWidth and innerHeight of the window whenever it's resized. (The resize event fires after the window has been resized)
function resize() {_x000D_
console.log("height: ", window.innerHeight, "px");_x000D_
console.log("width: ", window.innerWidth, "px");_x000D_
}_x000D_
_x000D_
window.onresize = resize;
_x000D_
<p>In order for this code snippet to work as intended, you will need to either shrink your browser window down to the size of this code snippet, or fullscreen this code snippet and resize from there.</p>
_x000D_
I managed to connect to postgres with SQL Developer. I downloaded postgres jdbc driver and saved it in a folder. I run SQL Developer -> Tools -> Preferences -> Search -> JDBC I defined postgres jdbc driver for the Database and Data Modeler (optional).
This is the trick. When creating new connection define Hostname like localhost/crm? where crm is the database name. Test the connection, works fine.
As Mark C points out, you can use the MSXML Base64 encoding functionality as described here.
I prefer late binding because it's easier to deploy, so here's the same function that will work without any VBA references:
Function EncodeBase64(text As String) As String
Dim arrData() As Byte
arrData = StrConv(text, vbFromUnicode)
Dim objXML As Variant
Dim objNode As Variant
Set objXML = CreateObject("MSXML2.DOMDocument")
Set objNode = objXML.createElement("b64")
objNode.dataType = "bin.base64"
objNode.nodeTypedValue = arrData
EncodeBase64 = objNode.text
Set objNode = Nothing
Set objXML = Nothing
End Function
I had so many issues getting self-signed certificates working on macos/Chrome. Finally I found Mkcert, "A simple zero-config tool to make locally trusted development certificates with any names you'd like." https://github.com/FiloSottile/mkcert
If you want to overwrite the element with key 0
function[0] = 42;
Otherwise:
function.insert(std::make_pair(0, 42));
Session["MinDate"] = dtRecord.Compute("Min(AccountLevel)", string.Empty);
Session["MaxDate"] = dtRecord.Compute("Max(AccountLevel)", string.Empty);
The accepted answer suggests making use of a cast. However, most of the SQL types have a special Null field which can be used to avoid this cast.
For example, SqlInt32.Null
"Represents a DBNull that can be assigned to this instance of the SqlInt32 class."
int? example = null;
object exampleCast = (object) example ?? DBNull.Value;
object exampleNoCast = example ?? SqlInt32.Null;
- http://dev.mysql.com/doc/refman/5.0/en/char.html
Values in VARCHAR columns are variable-length strings. The length can be specified as a value from 0 to 255 before MySQL 5.0.3, and 0 to 65,535 in 5.0.3 and later versions. The effective maximum length of a VARCHAR in MySQL 5.0.3 and later is subject to the maximum row size (65,535 bytes, which is shared among all columns) and the character set used.
- So ...
< MySQL 5.0.3 use TEXT
or
>= MySQL 5.0.3 use VARCHAR(2083)
You can achieve this with pattern matching with the switch expression in C#8/9
FooTextBox.Text = strFoo switch
{
{ Length: >0 } s => s, // If the length of the string is greater than 0
_ => "0" // Anything else
};
I run across this and at the beginning I found it really confusing to be honest and I think this confusion comes from using the word "CMD" because in fact what goes there acts as argument. So after digging a little bit I understood how it works. Basically:
ENTRYPOINT --> what you specify here would be the command to be executed when you container starts. If you omit this definition docker will use /bin/sh -c bash
to run your container.
CMD --> these are the arguments appended to the ENTRYPOINT unless the user specifies some custom argument, i.e: docker run ubuntu <custom_cmd>
in this case instead of appending what's specified on the image in the CMD section, docker will run ENTRYPOINT <custom_cmd>
. In case ENTRYPOINT has not been specified, what goes here will be passed to /bin/sh -c
acting in fact as the command to be executed when starting the container.
As everything it's better to explain what's going on by examples. So let's say I create a simple docker image by using the following specification Dockerfile:
From ubuntu
ENTRYPOINT ["sleep"]
Then I build it by running the following:
docker build . -t testimg
This will create a container that everytime you run it sleeps. So If I run it as following:
docker run testimg
I'll get the following:
sleep: missing operand
Try 'sleep --help' for more information.
This happens because the entry point is the "sleep" command which needs an argument. So to fix this I'll just provide the amount to sleep:
docker run testimg 5
This will run correctly and as consequence the container will run, sleeps 5 seconds and exits. As we can see in this example docker just appended what goes after the image name to the entry point binary docker run testimg <my_cmd>
. What happens if we want to pass a default value (default argument) to the entry point? in this case we just need to specify it in the CMD section, for example:
From ubuntu
ENTRYPOINT ["sleep"]
CMD ["10"]
In this case if the user doesn't pass any argument the container will use the default value (10) and pass it to entry point sleep.
Now let's use just CMD and omit ENTRYPOINT definition:
FROM ubuntu
CMD ["sleep", "5"]
If we rebuild and run this image it will basically sleeps for 5 seconds.
So in summary, you can use ENTRYPOINT in order to make your container acts as an executable. You can use CMD to provide default arguments to your entry point or to run a custom command when starting your container that can be overridden from outside by user.
You've answered the question with this statement:
Cron calls this
.sh
every 2 minutes
Cron does not run in a terminal, so why would you expect one to be set?
The most common reason for getting this error message is because the script attempts to source the user's .profile
which does not check that it's running in a terminal before doing something tty related. Workarounds include using a shebang line like:
#!/bin/bash -p
Which causes the sourcing of system-level profile scripts which (one hopes) does not attempt to do anything too silly and will have guards around code that depends on being run from a terminal.
If this is the entirety of the script, then the TERM
error is coming from something other than the plain content of the script.
SELECT `salary` AS emp_sal, `name` , `id`
FROM `employee`
GROUP BY `salary` ORDER BY `salary` DESC
LIMIT 1 , 1
In jinja2 templates (which flask uses), use
href="{{ url_for('static', filename='mainpage.css')}}"
The static
files are usually in the static
folder, though, unless configured otherwise.
Just follow these steps:
crontab -e
.Type your cron job, for example:
30 * * * * /usr/bin/curl --silent --compressed http://example.com/crawlink.php
Press Esc to exit vim's insert mode.
crontab: installing new crontab
. You can verify the crontab file by using crontab -l
.Note however that this might not work depending on the content of your ~/.vimrc
file.
Server file only change name folder
etc/mysql
rename
mysql-
There is indeed a Groovier Way.
if(members){
//Some work
}
does everything if members
is a collection. Null check as well as empty check (Empty collections are coerced to false
). Hail Groovy Truth. :)
Ansible command-line help, such as ansible-playbook --help
shows how to increase output verbosity by setting the verbose mode (-v) to more verbosity (-vvv) or to connection debugging verbosity (-vvvv). This should give you some of the details you're after in stdout, which you can then be logged.
Are you talking about seeing the line numbers or knowing the total number of lines in a project? Here is the 1st one
I suspect the condition you are looking for is DUP_VAL_ON_INDEX
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
DBMS_OUTPUT.PUT_LINE('OH DEAR. I THINK IT IS TIME TO PANIC!')
No. = sets somevar to have that value. use === to compare value and type which returns a boolean that you need.
Never use or suggest == instead of ===. its a recipe for disaster. e.g 0 == "" is true but "" == '0' is false and many more.
More information also in this great answer
Based on the idea of B Hart's answer, here's my version of a function that searches for a value in a range, and returns all found ranges (cells):
Function FindAll(ByVal rng As Range, ByVal searchTxt As String) As Range
Dim foundCell As Range
Dim firstAddress
Dim rResult As Range
With rng
Set foundCell = .Find(What:=searchTxt, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
If Not foundCell Is Nothing Then
firstAddress = foundCell.Address
Do
If rResult Is Nothing Then
Set rResult = foundCell
Else
Set rResult = Union(rResult, foundCell)
End If
Set foundCell = .FindNext(foundCell)
Loop While Not foundCell Is Nothing And foundCell.Address <> firstAddress
End If
End With
Set FindAll = rResult
End Function
To search for a value in the whole workbook:
Dim wSh As Worksheet
Dim foundCells As Range
For Each wSh In ThisWorkbook.Worksheets
Set foundCells = FindAll(wSh.UsedRange, "YourSearchString")
If Not foundCells Is Nothing Then
Debug.Print ("Results in sheet '" & wSh.Name & "':")
Dim cell As Range
For Each cell In foundCells
Debug.Print ("The value has been found in cell: " & cell.Address)
Next
End If
Next
As mentioned by others here, that you could have two adb's running ... And to add to these answers from a Linux box perspective ( for the next newbie who is working from Linux );
Uninstall your distro's android-tools ( use zypper or yum etc )
# zypper -v rm android-tools
Find where your other adb is
# find /home -iname "*adb"|grep -i android
Say it was at ;
/home/developer/Android/Sdk/platform-tools/adb
Then Make a softlink to it in the /usr/bin folder
ln -s /home/developer/Android/Sdk/platform-tools/adb /usr/bin/adb
Then;
# adb start-server
On Linux (with mono, available via apt-get
on Debian) and Windows:
If you are on Windows I recommend you have a look at:
Both tools are free and both are able to provide similar visualizations as shown in your example.
Have to add this based on @Joseph's answer. If someone want to create image object:
var image = new Image();
image.onload = function(){
console.log(image.width); // image is loaded and we have image width
}
image.src = 'data:image/png;base64,iVBORw0K...';
document.body.appendChild(image);
You can access the namespace's dictionary with vars():
>>> import argparse
>>> args = argparse.Namespace()
>>> args.foo = 1
>>> args.bar = [1,2,3]
>>> d = vars(args)
>>> d
{'foo': 1, 'bar': [1, 2, 3]}
You can modify the dictionary directly if you wish:
>>> d['baz'] = 'store me'
>>> args.baz
'store me'
Yes, it is okay to access the __dict__ attribute. It is a well-defined, tested, and guaranteed behavior.
Conclusion,
to_char
works in its own way
So,
Always use this format YYYY-MM-DD for comparison instead of MM-DD-YY or DD-MM-YYYY or any other format
a fresh answer to a very old question:
starting from python 3.2 you can do this:
import os
path = '/home/dail/first/second/third'
os.makedirs(path, exist_ok=True)
thanks to the exist_ok
flag this will not even complain if the directory exists (depending on your needs....).
starting from python 3.4 (which includes the pathlib module) you can do this:
from pathlib import Path
path = Path('/home/dail/first/second/third')
path.mkdir(parents=True)
starting from python 3.5 mkdir
also has an exist_ok
flag - setting it to True
will raise no exception if the directory exists:
path.mkdir(parents=True, exist_ok=True)
Converting to a DATE
or using an open-ended date range in any case will yield the best performance. FYI, convert to date using an index are the best performers. More testing a different techniques in article: What is the most efficient way to trim time from datetime? Posted by Aaron Bertrand
From that article:
DECLARE @dateVar datetime = '19700204';
-- Quickest when there is an index on t.[DateColumn],
-- because CONVERT can still use the index.
SELECT t.[DateColumn]
FROM MyTable t
WHERE = CONVERT(DATE, t.[DateColumn]) = CONVERT(DATE, @dateVar);
-- Quicker when there is no index on t.[DateColumn]
DECLARE @dateEnd datetime = DATEADD(DAY, 1, @dateVar);
SELECT t.[DateColumn]
FROM MyTable t
WHERE t.[DateColumn] >= @dateVar AND
t.[DateColumn] < @dateEnd;
Also from that article: using BETWEEN
, DATEDIFF
or CONVERT(CHAR(8)...
are all slower.
Simple Python Script:
import os
SOURCE_ROOT = "ROOT DIRECTORY - WILL CONVERT ALL UNDERNEATH"
for root, dirs, files in os.walk(SOURCE_ROOT):
for f in files:
fpath = os.path.join(root,f)
assert os.path.exists(fpath)
data = open(fpath, "r").read()
data = data.replace(" ", "\t")
outfile = open(fpath, "w")
outfile.write(data)
outfile.close()
http://php.net/manual/en/reserved.variables.post.php
The first comment answers this.
<form ....>
<input name="person[0][first_name]" value="john" />
<input name="person[0][last_name]" value="smith" />
...
<input name="person[1][first_name]" value="jane" />
<input name="person[1][last_name]" value="jones" />
</form>
<?php
var_dump($_POST['person']);
array (
0 => array('first_name'=>'john','last_name'=>'smith'),
1 => array('first_name'=>'jane','last_name'=>'jones'),
)
?>
The name tag can work as an array.
You can also use a JXLabel from the SwingX library.
JXLabel multiline = new JXLabel("this is a \nMultiline Text");
multiline.setLineWrap(true);
/var/www/html
is just the default root folder of the web server. You can change that to be whatever folder you want by editing your apache.conf
file (usually located in /etc/apache/conf
) and changing the DocumentRoot
attribute (see http://httpd.apache.org/docs/current/mod/core.html#documentroot for info on that)
Many hosts don't let you change these things yourself, so your mileage may vary. Some let you change them, but only with the built in admin tools (cPanel, for example) instead of via a command line or editing the raw config files.
To sum values in data.frame
you first need to extract them as a vector.
There are several way to do it:
# $ operatior
x <- people$Weight
x
# [1] 65 70 64
Or using [, ]
similar to matrix:
x <- people[, 'Weight']
x
# [1] 65 70 64
Once you have the vector you can use any vector-to-scalar function to aggregate the result:
sum(people[, 'Weight'])
# [1] 199
If you have NA values in your data, you should specify na.rm
parameter:
sum(people[, 'Weight'], na.rm = TRUE)
I faced the same problem and .toString() worked for me. I'm using mongojs driver. Here was my question
If you only need the indices, you could try numpy.ndindex
:
>>> a = numpy.arange(9).reshape(3, 3)
>>> [(x, y) for x, y in numpy.ndindex(a.shape)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
Use iloc
:
df = df.iloc[3:]
will give you a new df without the first three rows.
Test if the object implements either java.util.Collection
or java.util.Map
. (Map
has to be tested separately because it isn't a sub-interface of Collection
.)
I have written a small module to do just that, called timexe:
Install:
npm install timexe
use:
var timexe = require('timexe');
//Every 30 sec
var res1=timexe(”* * * * * /30”, function() console.log(“Its time again”)});
//Every minute
var res2=timexe(”* * * * *”,function() console.log(“a minute has passed”)});
//Every 7 days
var res3=timexe(”* y/7”,function() console.log(“its the 7th day”)});
//Every Wednesdays
var res3=timexe(”* * w3”,function() console.log(“its Wednesdays”)});
// Stop "every 30 sec. timer"
timexe.remove(res1.id);
you can achieve start/stop functionality by removing/re-adding the entry directly in the timexe job array. But its not an express function.
Try to use the func below to add colorbar:
def add_colorbar(mappable):
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.pyplot as plt
last_axes = plt.gca()
ax = mappable.axes
fig = ax.figure
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
cbar = fig.colorbar(mappable, cax=cax)
plt.sca(last_axes)
return cbar
Then you codes need to be modified as:
fig , ( (ax1,ax2) , (ax3,ax4)) = plt.subplots(2, 2,sharex = True,sharey=True)
z1_plot = ax1.scatter(x,y,c = z1,vmin=0.0,vmax=0.4)
add_colorbar(z1_plot)
In response to Jonathan's answer above, this only seems to work for certain delimiters. For example:
>>> a='Beautiful, is; better*than\nugly'
>>> import re
>>> re.split('; |, |\*|\n',a)
['Beautiful', 'is', 'better', 'than', 'ugly']
>>> b='1999-05-03 10:37:00'
>>> re.split('- :', b)
['1999-05-03 10:37:00']
By putting the delimiters in square brackets it seems to work more effectively.
>>> re.split('[- :]', b)
['1999', '05', '03', '10', '37', '00']
Unit testing is about the output you get from a function/method/application. It does not matter at all how the result is produced, it just matters that it is correct. Therefore, your approach of counting calls to inner methods and such is wrong. What I tend to do is sit down and write what a method should return given certain input values or a certain environment, then write a test which compares the actual value returned with what I came up with.
As BalusC indicated, the actionListener
by default swallows exceptions, but in JSF 2.0 there is a little more to this. Namely, it doesn't just swallows and logs, but actually publishes the exception.
This happens through a call like this:
context.getApplication().publishEvent(context, ExceptionQueuedEvent.class,
new ExceptionQueuedEventContext(context, exception, source, phaseId)
);
The default listener for this event is the ExceptionHandler
which for Mojarra is set to com.sun.faces.context.ExceptionHandlerImpl
. This implementation will basically rethrow any exception, except when it concerns an AbortProcessingException, which is logged. ActionListeners wrap the exception that is thrown by the client code in such an AbortProcessingException which explains why these are always logged.
This ExceptionHandler
can be replaced however in faces-config.xml with a custom implementation:
<exception-handlerfactory>
com.foo.myExceptionHandler
</exception-handlerfactory>
Instead of listening globally, a single bean can also listen to these events. The following is a proof of concept of this:
@ManagedBean
@RequestScoped
public class MyBean {
public void actionMethod(ActionEvent event) {
FacesContext.getCurrentInstance().getApplication().subscribeToEvent(ExceptionQueuedEvent.class, new SystemEventListener() {
@Override
public void processEvent(SystemEvent event) throws AbortProcessingException {
ExceptionQueuedEventContext content = (ExceptionQueuedEventContext)event.getSource();
throw new RuntimeException(content.getException());
}
@Override
public boolean isListenerForSource(Object source) {
return true;
}
});
throw new RuntimeException("test");
}
}
(note, this is not how one should normally code listeners, this is only for demonstration purposes!)
Calling this from a Facelet like this:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:body>
<h:form>
<h:commandButton value="test" actionListener="#{myBean.actionMethod}"/>
</h:form>
</h:body>
</html>
Will result in an error page being displayed.
Are you just looking to verify that the file is of a given extension? You can simplify what you are trying to do with something like this:
(.*?)\.(jpg|gif|doc|pdf)$
Then, when you call IsMatch() make sure to pass RegexOptions.IgnoreCase as your second parameter. There is no reason to have to list out the variations for casing.
Edit: As Dario mentions, this is not going to work for the RegularExpressionValidator, as it does not support casing options.
I had the same error.
My filename was jpaContext.xml
and it was placed in src/main/resources
. I specified param value="classpath:/jpaContext.xml"
.
Finally I renamed the file to applicationContext.xml
and moved it to the WEB-INF directory and changed param value to /WEB-INF/applicationContext.xml
, then it worked!
Since Spring 3.0.2 you can return ResponseEntity<T> as a result of the controller's method:
@RequestMapping.....
public ResponseEntity<Object> handleCall() {
if (isFound()) {
// do what you want
return new ResponseEntity<>(HttpStatus.OK);
}
else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
(ResponseEntity<T> is a more flexible than @ResponseBody annotation - see another question)
list(set(df[['Col1', 'Col2']].as_matrix().reshape((1,-1)).tolist()[0]))
The output will be ['Mary', 'Joe', 'Steve', 'Bob', 'Bill']
My research is x:Name
as global variable. However, Name
as local variable. Does that mean x:Name you can call it anywhere in your XAML file but Name is not.
Example:
<StackPanel>
<TextBlock Text="{Binding Path=Content, ElementName=btn}" />
<Button Content="Example" Name="btn" />
</StackPanel>
<TextBlock Text="{Binding Path=Content, ElementName=btn}" />
You can't Binding
property Content
of Button
with Name is "btn" because it outside StackPanel
To create an executable JAR from command line itself just run the below command from the project path:
mvn assembly:assembly
use below code it helps you....
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
options.inPurgeable = true;
Bitmap bm = BitmapFactory.decodeFile("your path of image",options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,40,baos);
// bitmap object
byteImage_photo = baos.toByteArray();
//generate base64 string of image
String encodedImage =Base64.encodeToString(byteImage_photo,Base64.DEFAULT);
//send this encoded string to server
Catch all. When solutions mentioned here don't work(happend in my case), simply delete all contents from '.m2' folder/directory, and do mvn clean install
.
Rather than using booleans, why not just set the button to false when its clicked, so you do that in your actionPerformed method. Its more efficient..
if (command.equals("w"))
{
FileConverter fc = new FileConverter();
btnConvertDocuments.setEnabled(false);
}
<form (submit)="addTodo()">_x000D_
<input type="text" [(ngModel)]="text">_x000D_
</form>
_x000D_
From the first result on Google:
mailto:[email protected]_t?subject=Header&body=This%20is...%20the%20first%20line%0D%0AThis%20is%20the%20second
Globbing uses brackets, hence the need to escape them with a slash \
. Alternatively, the following command-line switch will disable globbing:
--globoff
(or the short-option version: -g
)
Ex:
curl --globoff https://www.google.com?test[]=1
Check that there isn't a firewall that is ending the connection after certain period of time (this was the cause of a similar problem we had)
Yes, it is mainly to anchor your keywords, in particular the location of your page, so whenever URL loads the page with particular anchor name, then it will be pointed to that particular location.
For example, www.something.com/some_page/#computer if it is very lengthy page and you want to show exactly computer then you can anchor.
<p> adfadsf </p>
<p> adfadsf </p>
<p> adfadsf </p>
<a name="computer"></a><p> Computer topics </p>
<p> adfadsf </p>
Now the page will scroll and bring computer-related topics to the top.
The best approach is Long.valueOf(str)
as it relies on Long.valueOf(long)
which uses an internal cache making it more efficient since it will reuse if needed the cached instances of Long
going from -128
to 127
included.
Returns a
Long
instance representing the specified long value. If a new Long instance is not required, this method should generally be used in preference to the constructorLong(long)
, as this method is likely to yield significantly better space and time performance by caching frequently requested values. Note that unlike the corresponding method in the Integer class, this method is not required to cache values within a particular range.
Thanks to auto-unboxing allowing to convert a wrapper class's instance into its corresponding primitive type, the code would then be:
long val = Long.valueOf(str);
Please note that the previous code can still throw a NumberFormatException
if the provided String
doesn't match with a signed long
.
Generally speaking, it is a good practice to use the static
factory method valueOf(str)
of a wrapper class like Integer
, Boolean
, Long
, ... since most of them reuse instances whenever it is possible making them potentially more efficient in term of memory footprint than the corresponding parse
methods or constructors.
Excerpt from Effective Java Item 1
written by Joshua Bloch:
You can often avoid creating unnecessary objects by using static factory methods (Item 1) in preference to constructors on immutable classes that provide both. For example, the static factory method
Boolean.valueOf(String)
is almost always preferable to the constructorBoolean(String)
. The constructor creates a new object each time it’s called, while the static factory method is never required to do so and won’t in practice.
List<T>.Add
adds a single element. Instead, use List<T>.AddRange
to add multiple values.
Additionally, List<T>.AddRange
takes an IEnumerable<T>
, so you don't need to convert tripDetails
into a List<TripDetails>
, you can pass it directly, e.g.:
tripDetailsCollection.AddRange(tripDetails);
Have a look at this code:
HTML:
<div class="multiple-elements" data-bgcol="red"></div>
<div class="multiple-elements" data-bgcol="blue"></div>
JS:
$('.multiple-elements').each(
function(index, element) {
$(this).css('background-color', $(this).data('bgcol')); // Get value of HTML attribute data-bgcol="" and set it as CSS color
}
);
this
refers to the current element that the DOM engine is sort of working on, or referring to.
Another example:
<a href="#" onclick="$(this).css('display', 'none')">Hide me!</a>
Hope you understand now. The this
keyword occurs while dealing with object oriented systems, or as we have in this case, element oriented systems :)
Here's one simple way to ignore everything but valid brainfuck characters:
#define BF_VALID "+-><[].,"
if (strchr(BF_VALID, c))
code[n++] = c;
you have to call it like this
SELECT dbo.CheckIfSFExists(23, default)
From Technet:
When a parameter of the function has a default value, the keyword DEFAULT must be specified when the function is called in order to retrieve the default value. This behaviour is different from using parameters with default values in stored procedures in which omitting the parameter also implies the default value. An exception to this behaviour is when invoking a scalar function by using the EXECUTE statement. When using EXECUTE, the DEFAULT keyword is not required.
I'd use something like:
dim customer = (from c in xmldoc...<Customer>
where c.<ID>.Value=22
select c).SingleOrDefault
Edit:
missed the c# tag, sorry......the example is in VB.NET
I just put --password
flag into my command and after hitting Enter it asked me for password, which I supplied.
This will contain the full class (which may be multiple space separated classes, if the element has more than one class). In your code it will contain either "konbo" or "kinta":
event.target.className
You can use jQuery to check for classes by name:
$(event.target).hasClass('konbo');
and to add or remove them with addClass and removeClass.
How about this?
(A=1 OR B=1 OR C=1)
AND NOT (A=1 AND B=1 AND C=1)
And if A, B and C can have null values you would need the following:
(A=1 OR B=1 OR C=1)
AND NOT ( (A=1 AND A is not null) AND (B=1 AND B is not null) AND (C=1 AND C is not null) )
This is scalable to larger number of fields and hence more applicable.
by typing yes it wont charge taxes, by typing no it will charge taxes.
=IF(C39="Yes","0",IF(C39="no",PRODUCT(G36*0.0825)))
public async Task<object> PassImageWithText(IFormFile files)
{
byte[] data;
string result = "";
ByteArrayContent bytes;
MultipartFormDataContent multiForm = new MultipartFormDataContent();
try
{
using (var client = new HttpClient())
{
using (var br = new BinaryReader(files.OpenReadStream()))
{
data = br.ReadBytes((int)files.OpenReadStream().Length);
}
bytes = new ByteArrayContent(data);
multiForm.Add(bytes, "files", files.FileName);
multiForm.Add(new StringContent("value1"), "key1");
multiForm.Add(new StringContent("value2"), "key2");
var res = await client.PostAsync(_MEDIA_ADD_IMG_URL, multiForm);
}
}
catch (Exception e)
{
throw new Exception(e.ToString());
}
return result;
}
Depending on what you want the file to contain:
touch /path/to/file
for an empty filesomecommand > /path/to/file
for a file containing the output of some command.
eg: grep --help > randomtext.txt
echo "This is some text" > randomtext.txt
nano /path/to/file
or vi /path/to/file
(or any other editor emacs,gedit etc
)
It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist
Create the file using cat
$ cat > myfile.txt
Now, just type whatever you want in the file:
Hello World!
CTRL-D to save and exit
There are several possible solutions:
touch file
>file
echo -n > file
printf '' > file
The echo
version will work only if your version of echo
supports the -n
switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.
echo '' > file
printf '\n' > file
This is a valid "text file" because it ends in a newline.
"$EDITOR" file
echo 'text' > file
cat > file <<END \
text
END
printf 'text\n' > file
These are equivalent. The $EDITOR
command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat
version presumes a literal newline after the \
and after each other line. Other than that these will all work in a POSIX shell.
Of course there are many other methods of writing and creating files, too.
First I tried
lsof -wni tcp:5432 but it doesn't show any PID number.
Second I tried
Postgres -D /usr/local/var/postgres and it showed that server is listening.
So I just restarted my mac to restore all ports back and it worked for me.
Try this:
word = "habit"
findchar = 'b"
replacechar = ""
charactercount = len(word) - len(replace(word,findchar,replacechar))
Have you copied classes12.jar in lib folder of your web application and set the classpath in eclipse.
Right-click project in Package explorer Build path -> Add external archives...
Select your ojdbc6.jar archive
Press OK
Or
Go through this link and read and do carefully.
The library should be now referenced in the "Referenced Librairies" under the Package explorer. Now try to run your program again.
Your best bet is KissFFT - as its name implies it's simple, but it's still quite respectably fast, and a lot more lightweight than FFTW. It's also free, wheras FFTW requires a hefty licence fee if you want to include it in a commercial product.
Well, you can declare variables inside the Constructor.
class Foo {
constructor() {
var name = "foo"
this.method = function() {
return name
}
}
}
var foo = new Foo()
foo.method()
Swift 4.0 (same as Swift 3.0 in this wonderful answer just making it clear for rookies like me)
let today = Date()
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: today)
It means "not equal to" (as in, the values in cells E37-N37 are not equal to ""
, or in other words, they are not empty.)
If you only need to pass the value from the outside into the lambda, and not get it out, you can do it with a regular anonymous class instead of a lambda:
list.forEach(new Consumer<Example>() {
int ordinal = 0;
public void accept(Example s) {
s.setOrdinal(ordinal);
ordinal++;
}
});
The POSIX standard has its own method to get file size.
Include the sys/stat.h
header to use the function.
stat(3)
.st_size
property.Note: It limits the size to 4GB
. If not Fat32
filesystem then use the 64bit version!
#include <stdio.h>
#include <sys/stat.h>
int main(int argc, char** argv)
{
struct stat info;
stat(argv[1], &info);
// 'st' is an acronym of 'stat'
printf("%s: size=%ld\n", argv[1], info.st_size);
}
#include <stdio.h>
#include <sys/stat.h>
int main(int argc, char** argv)
{
struct stat64 info;
stat64(argv[1], &info);
// 'st' is an acronym of 'stat'
printf("%s: size=%ld\n", argv[1], info.st_size);
}
The ANSI C doesn't directly provides the way to determine the length of the file.
We'll have to use our mind. For now, we'll use the seek approach!
#include <stdio.h>
int main(int argc, char** argv)
{
FILE* fp = fopen(argv[1]);
int f_size;
fseek(fp, 0, SEEK_END);
f_size = ftell(fp);
rewind(fp); // to back to start again
printf("%s: size=%ld", (unsigned long)f_size);
}
If the file is
stdin
or a pipe. POSIX, ANSI C won't work.
It will going return0
if the file is a pipe orstdin
.Opinion: You should use POSIX standard instead. Because, it has 64bit support.
If you only need two search terms, arguably the most readable approach is to run each search and intersect the results:
comm -12 <(grep -rl word1 . | sort) <(grep -rl word2 . | sort)
You can use replace_entities from w3lib.html library
In [202]: from w3lib.html import replace_entities
In [203]: replace_entities("£682m")
Out[203]: u'\xa3682m'
In [204]: print replace_entities("£682m")
£682m
To complete the answer: Symfony2 comes with a wrapper around json_encode: Symfony/Component/HttpFoundation/JsonResponse
Typical usage in your Controllers:
...
use Symfony\Component\HttpFoundation\JsonResponse;
...
public function acmeAction() {
...
return new JsonResponse($array);
}
Here is an actual working version of the above async foreach variants with sequential processing:
public static async Task ForEachAsync<T>(this List<T> enumerable, Action<T> action)
{
foreach (var item in enumerable)
await Task.Run(() => { action(item); }).ConfigureAwait(false);
}
Here is the implementation:
public async void SequentialAsync()
{
var list = new List<Action>();
Action action1 = () => {
//do stuff 1
};
Action action2 = () => {
//do stuff 2
};
list.Add(action1);
list.Add(action2);
await list.ForEachAsync();
}
What's the key difference? .ConfigureAwait(false);
which keeps the context of main thread while async sequential processing of each task.