If you define classproperty
as follows, then your example works exactly as you requested.
class classproperty(object):
def __init__(self, f):
self.f = f
def __get__(self, obj, owner):
return self.f(owner)
The caveat is that you can't use this for writable properties. While e.I = 20
will raise an AttributeError
, Example.I = 20
will overwrite the property object itself.
chartr
is also convenient for these types of substitutions:
chartr("_", "-", data1$c)
# [1] "A-B" "A-B" "A-B" "A-B" "A-C" "A-C" "A-C" "A-C" "A-C" "A-C"
Thus, you can just do:
data1$c <- chartr("_", "-", data1$c)
The next()
method (offcial doc here) simply move the pointer of the result rows set to the next row (if it can). Anyway you can read this from the offcial doc as well:
Moves the cursor down one row from its current position.
This method return true if there's another row or false otherwise.
If checkout master
was the last thing you did, then the reflog entry HEAD@{1}
will contain your commits (otherwise use git reflog
or git log -p
to find them). Use git merge HEAD@{1}
to fast forward them into master.
EDIT:
As noted in the comments, Git Ready has a great article on this.
git reflog
and git reflog --all
will give you the commit hashes of the mis-placed commits.
Source: http://gitready.com/intermediate/2009/02/09/reflog-your-safety-net.html
It is bad practice to throw Exception, as that requires anyone who calls your constructor to catch Exception which is a bad practice.
It is a good idea to have a constructor (or any method) throw an exception, generally speaking IllegalArgumentException, which is unchecked, and thus the compiler doesn't force you to catch it.
You should throw checked exceptions (things that extend from Exception, but not RuntimeException) if you want the caller to catch it.
It makes no sense, but:
System.out.println(dateFormat.format(dateFormat.parse("31/05/2011")))
SimpleDateFormat.parse() = // parse Date from String
SimpleDateFormat.format() = // format Date into String
This code sample can be used to change date format. Here I want to change from yyyy-MM-dd to dd-MM-yyyy. Here pos
is position of column.
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
class Test{
public static void main( String[] args )
{
String input="D:\\somefolder\\somefile.xlsx";
String output="D:\\somefolder\\someoutfile.xlsx"
FileInputStream file = new FileInputStream(new File(input));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> iterator = sheet.iterator();
Cell cell = null;
Row row=null;
row=iterator.next();
int pos=5; // 5th column is date.
while(iterator.hasNext())
{
row=iterator.next();
cell=row.getCell(pos-1);
//CellStyle cellStyle = wb.createCellStyle();
XSSFCellStyle cellStyle = (XSSFCellStyle)cell.getCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(
createHelper.createDataFormat().getFormat("dd-MM-yyyy"));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d=null;
try {
d= sdf.parse(cell.getStringCellValue());
} catch (ParseException e) {
// TODO Auto-generated catch block
d=null;
e.printStackTrace();
continue;
}
cell.setCellValue(d);
cell.setCellStyle(cellStyle);
}
file.close();
FileOutputStream outFile =new FileOutputStream(new File(output));
workbook.write(outFile);
workbook.close();
outFile.close();
}}
Question: search for 'loom' excluding 'gloom'.
Answer:
grep -w 'loom' ~/projects/**/trunk/src/**/*.@(h|cpp)
Write below code in script and also add jQuery library
var getElement = document.getElementById('myID');
if (document.activeElement === getElement) {
$(document).keydown(function(event) {
if (event.which === 40) {
console.log('keydown pressed')
}
});
}
Thank you...
angular-cli
now has a dedicated wiki page where you can find everything you need. TLDR, install bootstrap
via npm
and add the styles link to "styles" section in your .angular-cli.json
file
I am going to use this one. Very similar to third one shown by @Marin.
app
|
|___ images
|
|___ fonts
|
|___ css
|
|___ *main.ts*
|
|___ *main.component.ts*
|
|___ *index.html*
|
|___ components
| |
| |___ shared
| |
| |___ home
| |
| |___ about
| |
| |___ product
|
|___ services
|
|___ structures
I use two underscore characters as delimiter i.e.
fk__ForeignKeyTable__PrimaryKeyTable
This is because table names will occasionally contain underscore characters themselves. This follows the naming convention for constraints generally because data elements' names will frequently contain underscore characters e.g.
CREATE TABLE NaturalPersons (
...
person_death_date DATETIME,
person_death_reason VARCHAR(30)
CONSTRAINT person_death_reason__not_zero_length
CHECK (DATALENGTH(person_death_reason) > 0),
CONSTRAINT person_death_date__person_death_reason__interaction
CHECK ((person_death_date IS NULL AND person_death_reason IS NULL)
OR (person_death_date IS NOT NULL AND person_death_reason IS NOT NULL))
...
Base on @Mark answer, I add the constructor to directive and it work with me.
I share a sample to whom concern.
constructor(private el: ElementRef, private renderer: Renderer) {
}
TS file
@Directive({ selector: '[accordion]' })
export class AccordionDirective {
constructor(private el: ElementRef, private renderer: Renderer) {
}
@HostListener('click', ['$event']) onClick($event) {
console.info($event);
this.el.nativeElement.classList.toggle('is-open');
var content = this.el.nativeElement.nextElementSibling;
if (content.style.maxHeight) {
// accordion is currently open, so close it
content.style.maxHeight = null;
} else {
// accordion is currently closed, so open it
content.style.maxHeight = content.scrollHeight + "px";
}
}
}
HTML
<button accordion class="accordion">Accordian #1</button>
<div class="accordion-content">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas deleniti molestias necessitatibus quaerat quos incidunt! Quas officiis repellat dolore omnis nihil quo,
ratione cupiditate! Sed, deleniti, recusandae! Animi, sapiente, nostrum?
</p>
</div>
Demo https://stackblitz.com/edit/angular-directive-accordion?file=src/app/app.component.ts
JpaRepository
The Spring Data JpaRepository
defines the following two methods:
getOne
, which returns an entity proxy that is suitable for setting a @ManyToOne
or @OneToOne
parent association when persisting a child entity.findById
, which returns the entity POJO after running the SELECT statement that loads the entity from the associated tableHowever, in your case, you didn't call either getOne
or findById
:
Person person = personRepository.findOne(1L);
So, I assume the findOne
method is a method you defined in the PersonRepository
. However, the findOne
method is not very useful in your case. Since you need to fetch the Person
along with is roles
collection, it's better to use a findOneWithRoles
method instead.
You can define a PersonRepositoryCustom
interface, as follows:
public interface PersonRepository
extends JpaRepository<Person, Long>, PersonRepositoryCustom {
}
public interface PersonRepositoryCustom {
Person findOneWithRoles(Long id);
}
And define its implementation like this:
public class PersonRepositoryImpl implements PersonRepositoryCustom {
@PersistenceContext
private EntityManager entityManager;
@Override
public Person findOneWithRoles(Long id)() {
return entityManager.createQuery("""
select p
from Person p
left join fetch p.roles
where p.id = :id
""", Person.class)
.setParameter("id", id)
.getSingleResult();
}
}
That's it!
In my case, it was caused by a missing (0)
in javascript:void(0)
in an anchor.
You can access other containers' service by their name(ping apache
will get the ip or curl http://apache
would access the http service) And this can be a alternative of a static ip.
docker rmi $(docker images -a -q)
Stated the following images where in use. I think this command gets rid of unwanted images.
Try this if other answers did not work for you.
For me This happened for API 27 Emulator.
API 26 Emulator worked just fine. So I started API 26 Emulator first and then closed it.
Then I started API 27 Emulator and It worked with No errors at all.
Refer https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists
dt = datetime.datetime(*t[:7])
Our team avoids putting credentials in repositories, so that means they're not allowed in Dockerfile
. Our best practice within applications is to use creds from environment variables.
We solve for this using docker-compose
.
Within docker-compose.yml
, you can specify a file that contains the environment variables for the container:
env_file:
- .env
Make sure to add .env
to .gitignore
, then set the credentials within the .env
file like:
SOME_USERNAME=myUser
SOME_PWD_VAR=myPwd
Store the .env
file locally or in a secure location where the rest of the team can grab it.
See: https://docs.docker.com/compose/environment-variables/#/the-env-file
The difference is not just for Chrome but for most of the web browsers.
F5
refreshes the web page and often reloads the same page from the cached contents of the web browser. However, reloading from cache every time is not guaranteed and it also depends upon the cache expiry.
Shift + F5
forces the web browser to ignore its cached contents and retrieve a fresh copy of the web page into the browser.
Shift + F5
guarantees loading of latest contents of the web page.
However, depending upon the size of page, it is usually slower than F5
.
You may want to refer to: What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?
Make sure you have the latest version of CocoaPods installed. $ pod update POD
was introduced recently.
See this issue thread for more information:
$ pod update
When you run
pod update SomePodName
, CocoaPods will try to find an updated version of the pod SomePodName, without taking into account the version listed inPodfile.lock
. It will update the pod to the latest version possible (as long as it matches the version restrictions in your Podfile).If you run pod update without any pod name, CocoaPods will update every pod listed in your Podfile to the latest version possible.
EDITED TO ADD: The following code is outdated and won't work in PHP 7. See the note towards the bottom of the answer for more details.
Assuming a table structure of an integer ID and a blob DATA column, and assuming MySQL functions are being used to interface with the database, you could probably do something like this:
$result = mysql_query 'INSERT INTO table (
data
) VALUES (
\'' . mysql_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf')) . '\'
);';
A word of warning though, storing blobs in databases is generally not considered to be the best idea as it can cause table bloat and has a number of other problems associated with it. A better approach would be to move the file somewhere in the filesystem where it can be retrieved, and store the path to the file in the database instead of the file itself.
Also, using mysql_* function calls is discouraged as those methods are effectively deprecated and aren't really built with versions of MySQL newer than 4.x in mind. You should switch to mysqli or PDO instead.
UPDATE: mysql_* functions are deprecated in PHP 5.x and are REMOVED COMPLETELY IN PHP 7! You now have no choice but to switch to a more modern Database Abstraction (MySQLI, PDO). I've decided to leave the original answer above intact for historical reasons but don't actually use it
Here's how to do it with mysqli in procedural mode:
$result = mysqli_query ($db, 'INSERT INTO table (
data
) VALUES (
\'' . mysqli_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf'), $db) . '\'
);');
The ideal way of doing it is with MySQLI/PDO prepared statements.
The default port for SQL Server Database Engine is 1433.
And as a best practice it should always be changed after the installation. 1433 is widely known which makes it vulnerable to attacks.
You declared activity A with the standard launchMode
in the Android manifest. According to the documentation, that means the following:
The system always creates a new instance of the activity in the target task and routes the intent to it.
Therefore, the system is forced to recreate activity A (i.e. calling onCreate
) even if the task stack is handled correctly.
To fix this problem you need to change the manifest, adding the following attribute to the A activity declaration:
android:launchMode="singleTop"
Note: calling finish()
(as suggested as solution before) works only when you are completely sure that the activity B instance you are terminating lives on top of an instance of activity A. In more complex workflows (for instance, launching activity B from a notification) this might not be the case and you have to correctly launch activity A from B.
document.getElementsByClassName
returns a NodeList
, not a single element, I'd recommend either using jQuery, since you'd only have to use something like $('.new').toggle()
or if you want plain JS try :
function toggle_by_class(cls, on) {
var lst = document.getElementsByClassName(cls);
for(var i = 0; i < lst.length; ++i) {
lst[i].style.display = on ? '' : 'none';
}
}
fibonacci 1,000 ... 10,000 ... 100,000
Some answers run into issues when trying to calculate large fibonacci numbers. Others are approximating numbers using phi. This answer will show you how to calculate a precise series of large fibonacci numbers without running into limitations set by JavaScript's floating point implementation.
Below, we generate the first 1,000 fibonacci numbers in a few milliseconds. Later, we'll do 100,000!
const { fromInt, toString, add } =
Bignum
const bigfib = function* (n = 0)
{
let a = fromInt (0)
let b = fromInt (1)
let _
while (n >= 0) {
yield toString (a)
_ = a
a = b
b = add (b, _)
n = n - 1
}
}
console.time ('bigfib')
const seq = Array.from (bigfib (1000))
console.timeEnd ('bigfib')
// 25 ms
console.log (seq.length)
// 1001
console.log (seq)
// [ 0, 1, 1, 2, 3, ... 995 more elements ]
Let's see the 1,000th fibonacci number
console.log (seq [1000])
// 43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875
10,000
This solution scales quite nicely. We can calculate the first 10,000 fibonacci numbers in under 2 seconds. At this point in the sequence, the numbers are over 2,000 digits long – way beyond the capacity of JavaScript's floating point numbers. Still, our result includes precise values without making approximations.
console.time ('bigfib')
const seq = Array.from (bigfib (10000))
console.timeEnd ('bigfib')
// 1877 ms
console.log (seq.length)
// 10001
console.log (seq [10000] .length)
// 2090
console.log (seq [10000])
// 3364476487 ... 2070 more digits ... 9947366875
Of course all of that magic takes place in Bignum
, which we will share now. To get an intuition for how we will design Bignum
, recall how you added big numbers using pen and paper as a child...
1259601512351095520986368
+ 50695640938240596831104
---------------------------
?
You add each column, right to left, and when a column overflows into the double digits, remembering to carry the 1 over to the next column...
... <-001
1259601512351095520986368
+ 50695640938240596831104
---------------------------
... <-472
Above, we can see that if we had two 10-digit numbers, it would take approximately 30 simple additions (3 per column) to compute the answer. This is how we will design Bignum
to work
const Bignum =
{ fromInt: (n = 0) =>
n < 10
? [ n ]
: [ n % 10, ...Bignum.fromInt (n / 10 >> 0) ]
, fromString: (s = "0") =>
Array.from (s, Number) .reverse ()
, toString: (b) =>
Array.from (b) .reverse () .join ('')
, add: (b1, b2) =>
{
const len = Math.max (b1.length, b2.length)
let answer = []
let carry = 0
for (let i = 0; i < len; i = i + 1) {
const x = b1[i] || 0
const y = b2[i] || 0
const sum = x + y + carry
answer.push (sum % 10)
carry = sum / 10 >> 0
}
if (carry > 0) answer.push (carry)
return answer
}
}
We'll run a quick test to verify our example above
const x =
fromString ('1259601512351095520986368')
const y =
fromString ('50695640938240596831104')
console.log (toString (add (x,y)))
// 1310297153289336117817472
And now a complete program demonstration. Expand it to calculate the precise 10,000th fibonacci number in your own browser! Note, the result is the same as the answer provided by wolfram alpha
const Bignum =_x000D_
{ fromInt: (n = 0) =>_x000D_
n < 10_x000D_
? [ n ]_x000D_
: [ n % 10, ...Bignum.fromInt (n / 10 >> 0) ]_x000D_
_x000D_
, fromString: (s = "0") =>_x000D_
Array.from (s, Number) .reverse ()_x000D_
_x000D_
, toString: (b) =>_x000D_
Array.from (b) .reverse () .join ('')_x000D_
_x000D_
, add: (b1, b2) =>_x000D_
{_x000D_
const len = Math.max (b1.length, b2.length)_x000D_
let answer = []_x000D_
let carry = 0_x000D_
for (let i = 0; i < len; i = i + 1) {_x000D_
const x = b1[i] || 0_x000D_
const y = b2[i] || 0_x000D_
const sum = x + y + carry_x000D_
answer.push (sum % 10)_x000D_
carry = sum / 10 >> 0_x000D_
}_x000D_
if (carry > 0) answer.push (carry)_x000D_
return answer_x000D_
}_x000D_
}_x000D_
_x000D_
const { fromInt, toString, add } =_x000D_
Bignum_x000D_
_x000D_
const bigfib = function* (n = 0)_x000D_
{_x000D_
let a = fromInt (0)_x000D_
let b = fromInt (1)_x000D_
let __x000D_
while (n >= 0) {_x000D_
yield toString (a)_x000D_
_ = a_x000D_
a = b_x000D_
b = add (b, _)_x000D_
n = n - 1_x000D_
}_x000D_
}_x000D_
_x000D_
console.time ('bigfib')_x000D_
const seq = Array.from (bigfib (10000))_x000D_
console.timeEnd ('bigfib')_x000D_
// 1877 ms_x000D_
_x000D_
console.log (seq.length)_x000D_
// 10001_x000D_
_x000D_
console.log (seq [10000] .length)_x000D_
// 2090_x000D_
_x000D_
console.log (seq [10000])_x000D_
// 3364476487 ... 2070 more digits ... 9947366875
_x000D_
100,000
I was just curious how far this little script could go. It seems like the only limitation is just time and memory. Below, we calculate the first 100,000 fibonacci numbers without approximation. Numbers at this point in the sequence are over 20,000 digits long, wow! It takes 3.18 minutes to complete but the result still matches the answer from wolfram alpha
console.time ('bigfib')
const seq = Array.from (bigfib (100000))
console.timeEnd ('bigfib')
// 191078 ms
console.log (seq .length)
// 100001
console.log (seq [100000] .length)
// 20899
console.log (seq [100000])
// 2597406934 ... 20879 more digits ... 3428746875
You need to ensure that C:\Python35\Sripts
is in your system path. Follow the top answer instructions here to do that:
You run the command in windows command prompt, not in the python interpreter that you have open.
Press:
Win + R
Type CMD
in the run window which has opened
Type pip install openpyxl
in windows command prompt.
I was getting this error when I was updating the dictionary with the wrong syntax:
Try with these:
lineItem.values.update({attribute,value})
instead of
lineItem.values.update({attribute:value})
Really easy solve. Tested and working. You just need to generate a new url when you update your meta tags. It's as simple as adding a "&cacheBuster=1" to your url. If you change the meta tags, just increment the "&cacheBuster=2"
Orginal URL
www.example.com
URL when og meta tags are updated:
www.example.com?cacheBuster=1
URL when og meta tags are updated again:
www.example.com?cacheBuster=2
Facebook will treat each like a new url and get fresh meta data.
I tried many of the answers in this thread and none of them worked for me. Then I came across this answer to a similar post: https://stackoverflow.com/a/40853424/2120023 where he mentions HttpContext.Request.Body
so another search and I found this https://stackoverflow.com/a/1302851/2120023 which gave me HttpContext.Current
so I finally got this to work using:
HttpContext.Current.Request.Form.Get("value");
My request from Postman:
curl --location --request POST 'https://example.com/token' --header 'Content-Type: application/x-www-form-urlencoded' --data-urlencode 'value=test'
GUI Option:
Open System Properties
a. Type it in the Start Menu
b. Use the keyboard shortcut Win+Pause)
c. From Windows Explorer
address bar go to
%windir%\System32\SystemPropertiesProtection.exe
d. Write SystemPropertiesProtection
in run window and press Enter
Switch to the Advanced
tab
Environment Variables
PATH
in the System variables
sectionEdit
For example:
C:\Windows;C:\Windows\System32;C:\Python27
Command Line Option:
Check existing paths under PATH
variable (the paths are separated by semicolons). If your python folder already listed then no need to add again. Default python folder is C:\Python27
C:\Windows\system32>path
or C:\Windows\system32>echo %PATH%
Append python path using setx
command. The /M
option sets the variable at SYSTEM
scope.
The default behavior is to set it for the USER
.
C:\Windows\system32>setx /M PATH "%PATH%;C:\Python27"
I think using NOW()
function is incorrect for getting time difference. Because by NOW()
function every time your are calculating the past 24 hours.
You must use CURDATE()
instead.
function your_function($time, $your_date) {
if ($time == 'today') {
$timeSQL = ' Date($your_date)= CURDATE()';
}
if ($time == 'week') {
$timeSQL = ' YEARWEEK($your_date)= YEARWEEK(CURDATE())';
}
if ($time == 'month') {
$timeSQL = ' Year($your_date)=Year(CURDATE()) AND Month(`your_date`)= Month(CURDATE())';
}
$Sql = "SELECT * FROM jokes WHERE ".$timeSQL
return $Result = $this->db->query($Sql)->result_array();
}
Considering @Ben answer, R would throw an error if df1
does not contain x
column. But it can be solved elegantly with paste
:
aggregate(paste(Year, Month) ~ Year + Month, data = df1, FUN = NROW)
Similarly, it can be generalized if more than two variables are used in grouping:
aggregate(paste(Year, Month, Day) ~ Year + Month + Day, data = df1, FUN = NROW)
Okay, here's all of your bounty requirements met:
Here's a demo and link to my code (JSFiddle)
Here are the features that I've incorporated into this purely JS, CSS and HTML5 fiddle:
HTML:
<div id="wrapper">
<div id="a">Hover over this div to see a cool tool tip!</div>
</div>
CSS:
#a{
background-color:yellow;
padding:10px;
border:2px solid red;
}
.tooltip{
background:black;
color:white;
padding:5px;
box-shadow:0 0 10px 0 rgba(0, 0, 0, 1);
border-radius:10px;
opacity:0;
}
JavaScript:
var div = document.getElementById('wrapper');
var a = document.getElementById("a");
var fadeSpeed = 25; // a value between 1 and 1000 where 1000 will take 10
// seconds to fade in and out and 1 will take 0.01 sec.
var tipMessage = "The content of the tooltip...";
var showTip = function(){
var tip = document.createElement("span");
tip.className = "tooltip";
tip.id = "tip";
tip.innerHTML = tipMessage;
div.appendChild(tip);
tip.style.opacity="0"; // to start with...
var intId = setInterval(function(){
newOpacity = parseFloat(tip.style.opacity)+0.1;
tip.style.opacity = newOpacity.toString();
if(tip.style.opacity == "1"){
clearInterval(intId);
}
}, fadeSpeed);
};
var hideTip = function(){
var tip = document.getElementById("tip");
var intId = setInterval(function(){
newOpacity = parseFloat(tip.style.opacity)-0.1;
tip.style.opacity = newOpacity.toString();
if(tip.style.opacity == "0"){
clearInterval(intId);
tip.remove();
}
}, fadeSpeed);
tip.remove();
};
a.addEventListener("mouseover", showTip, false);
a.addEventListener("mouseout", hideTip, false);
Yes, you should try to serve valid code if possible.
Most browsers will silently correct this error, but there is a problem with relying on the error handling in the browsers. There is no standard for how to handle incorrect code, so it's up to each browser vendor to try to figure out what to do with each error, and the results may vary.
Some examples where browsers are likely to react differently is if you put elements inside a table but outside the table cells, or if you nest links inside each other.
For your specific example it's not likely to cause any problems, but error correction in the browser might for example cause the browser to change from standards compliant mode into quirks mode, which could make your layout break down completely.
So, you should correct errors like this in the code, if not for anything else so to keep the error list in the validator short, so that you can spot more serious problems.
pandas.Series.astype
You can do something like this :
weather["Temp"] = weather.Temp.astype(float)
You can also use pd.to_numeric
that will convert the column from object to float
Example :
s = pd.Series(['apple', '1.0', '2', -3])
print(pd.to_numeric(s, errors='ignore'))
print("=========================")
print(pd.to_numeric(s, errors='coerce'))
Output:
0 apple
1 1.0
2 2
3 -3
=========================
dtype: object
0 NaN
1 1.0
2 2.0
3 -3.0
dtype: float64
In your case you can do something like this:
weather["Temp"] = pd.to_numeric(weather.Temp, errors='coerce')
convert_objects
Example is as follows
>> pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True)
0 1
1 2
2 3
3 4
4 NaN
dtype: float64
You can use this as follows:
weather["Temp"] = weather.Temp.convert_objects(convert_numeric=True)
NaN
... so be careful while using it.You have two options:
Configure Workspace Settings (disable the validation for the current workspace): Go to Window > Preferences > Validation and uncheck the manual and build for: XML Schema Validator, XML Validator
Check enable project specific settings (disable the validation for this project): Right-click on the project, select Properties > Validation and uncheck the manual and build for: XML Schema Validator, XML Validator
Right-click on the project and select Validate to make the errors disappear.
If you don't mind getting a new data frame object returned as opposed to updating the original Pandas .assign() will avoid SettingWithCopyWarning
. Your example:
df = df.assign(B=df1['E'])
A simpler way to explain this,
public bool CheckInputs(int a, int b){
public bool condition = true;
if (a > b || a == b)
{
condition = false;
}
else
{
condition = true;
}
return condition;
}
You can close a figure by calling matplotlib.pyplot.close
, for example:
from numpy import *
import matplotlib.pyplot as plt
from scipy import *
t = linspace(0, 0.1,1000)
w = 60*2*pi
fig = plt.figure()
plt.plot(t,cos(w*t))
plt.plot(t,cos(w*t-2*pi/3))
plt.plot(t,cos(w*t-4*pi/3))
plt.show()
plt.close(fig)
You can also close all open figures by calling matplotlib.pyplot.close("all")
SSRS will not accept duplicated columns so ensure that your query or store procedure is returning unique column names.
Views in Oracle may be updateable under specific conditions. It can be tricky, and usually is not advisable.
From the Oracle 10g SQL Reference:
Notes on Updatable Views
An updatable view is one you can use to insert, update, or delete base table rows. You can create a view to be inherently updatable, or you can create an INSTEAD OF trigger on any view to make it updatable.
To learn whether and in what ways the columns of an inherently updatable view can be modified, query the USER_UPDATABLE_COLUMNS data dictionary view. The information displayed by this view is meaningful only for inherently updatable views. For a view to be inherently updatable, the following conditions must be met:
In addition, if an inherently updatable view contains pseudocolumns or expressions, then you cannot update base table rows with an UPDATE statement that refers to any of these pseudocolumns or expressions.
If you want a join view to be updatable, then all of the following conditions must be true:
$array = range('a', 'z');
This is not possible. The java specification forbids the use of primitives in generics. However, you can create ArrayList<Integer>
and call add(i)
if i
is an int thanks to boxing.
Open command prompt and give the platform-tools path of the sdk. Eg:- C:\Android\sdk\platform-tools> Then type 'adb push' command like below,
C:\Android\sdk\platform-tools>adb push C:\MyFiles\fileName.txt /sdcard/fileName.txt
This command push the file to the root folder of the emulator.
string urlParameters = "param1=value1¶m2=value2";
string _endPointName = "your url post api";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(_endPointName);
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
httpWebRequest.Headers["ContentType"] = "application/x-www-form-urlencoded";
System.Net.ServicePointManager.ServerCertificateValidationCallback +=
(se, cert, chain, sslerror) =>
{
return true;
};
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(urlParameters);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
I Hope that this helps you out... Because I tried all the answers but nothing worked perfectly. So, I had to come up with a solution on my own.
#horizontal-style {
padding-inline-start: 0 !important; // Just in case if you find that there is an extra padding at the start of the line
justify-content: space-around;
display: flex;
}
#horizontal-style a {
text-align: center;
color: white;
text-decoration: none;
}
>>> 15 % 4
3
>>>
The modulo gives the remainder after integer division.
I had this problem even after setting the config properly. git config
My scenario was issuing git command through supervisor (in Linux). On further debugging, supervisor was not reading the git config from home folder. Hence, I had to set the environment HOME variable in the supervisor config so that it can locate the git config correctly. It's strange that supervisor was not able to locate the git config just from the username configured in supervisor's config (/etc/supervisor/conf.d).
Well, in my case I had to test a Phone Number with the help of regex, and I was getting the same error,
Invalid regular expression: /+923[0-9]{2}-(?!1234567)(?!1111111)(?!7654321)[0-9]{7}/: Nothing to repeat'
So, what was the error in my case was that +
operator after the /
in the start of the regex. So enclosing the +
operator with square brackets [+]
, and again sending the request, worked like a charm.
Following will work:
/[+]923[0-9]{2}-(?!1234567)(?!1111111)(?!7654321)[0-9]{7}/
This answer may be helpful for those, who got the same type of error, but their chances of getting the error from this point of view, as mine! Cheers :)
You can use the index of the column you want to apply the multiplication for
df.loc[:,6] *= -1
This will multiply the column with index 6 with -1.
Call "setWarningMsg()" Method and pass the text that you want to show.
exm:- setWarningMsg("thank you for using java");
public static void setWarningMsg(String text){
Toolkit.getDefaultToolkit().beep();
JOptionPane optionPane = new JOptionPane(text,JOptionPane.WARNING_MESSAGE);
JDialog dialog = optionPane.createDialog("Warning!");
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
}
Or Just use
JOptionPane optionPane = new JOptionPane("thank you for using java",JOptionPane.WARNING_MESSAGE);
JDialog dialog = optionPane.createDialog("Warning!");
dialog.setAlwaysOnTop(true); // to show top of all other application
dialog.setVisible(true); // to visible the dialog
You can use JOptionPane. (WARNING_MESSAGE or INFORMATION_MESSAGE or ERROR_MESSAGE)
UltraID3Lib...
Be aware that UltraID3Lib is no longer officially available, and thus no longer maintained. See comments below for the link to a Github project that includes this library
//using HundredMilesSoftware.UltraID3Lib;
UltraID3 u = new UltraID3();
u.Read(@"C:\mp3\song.mp3");
//view
Console.WriteLine(u.Artist);
//edit
u.Artist = "New Artist";
u.Write();
w3wp.exe is a process associated with the application pool in IIS. If you have more than one application pool, you will have more than one instance of w3wp.exe running. This process usually allocates large amounts of resources. It is important for the stable and secure running of your computer and should not be terminated.
You can get more information on w3wp.exe here
http://www.processlibrary.com/en/directory/files/w3wp/25761/
First of all consider using query parameters in prepared statements:
PreparedStatement stm = c.prepareStatement("UPDATE user_table SET name=? WHERE id=?");
stm.setString(1, "the name");
stm.setInt(2, 345);
stm.executeUpdate();
The other thing that can be done is to keep all queries in properties file. For example in a queries.properties file can place the above query:
update_query=UPDATE user_table SET name=? WHERE id=?
Then with the help of a simple utility class:
public class Queries {
private static final String propFileName = "queries.properties";
private static Properties props;
public static Properties getQueries() throws SQLException {
InputStream is =
Queries.class.getResourceAsStream("/" + propFileName);
if (is == null){
throw new SQLException("Unable to load property file: " + propFileName);
}
//singleton
if(props == null){
props = new Properties();
try {
props.load(is);
} catch (IOException e) {
throw new SQLException("Unable to load property file: " + propFileName + "\n" + e.getMessage());
}
}
return props;
}
public static String getQuery(String query) throws SQLException{
return getQueries().getProperty(query);
}
}
you might use your queries as follows:
PreparedStatement stm = c.prepareStatement(Queries.getQuery("update_query"));
This is a rather simple solution, but works well.
With Swift 5 and iOS 12, according to your needs, you may use one of the two following ways to find the difference between two dates in days.
Calendar
's dateComponents(_:from:to:)
methodimport Foundation
let calendar = Calendar.current
let startDate = calendar.date(from: DateComponents(year: 2010, month: 11, day: 22))!
let endDate = calendar.date(from: DateComponents(year: 2015, month: 5, day: 1))!
let dateComponents = calendar.dateComponents([Calendar.Component.day], from: startDate, to: endDate)
print(dateComponents) // prints: day: 1621 isLeapMonth: false
print(String(describing: dateComponents.day)) // prints: Optional(1621)
DateComponentsFormatter
's string(from:to:)
methodimport Foundation
let calendar = Calendar.current
let startDate = calendar.date(from: DateComponents(year: 2010, month: 11, day: 22))!
let endDate = calendar.date(from: DateComponents(year: 2015, month: 5, day: 1))!
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.allowedUnits = [NSCalendar.Unit.day]
let elapsedTime = formatter.string(from: startDate, to: endDate)
print(String(describing: elapsedTime)) // prints: Optional("1,621 days")
You can use sys.master_files.
Contains a row per file of a database as stored in the master database. This is a single, system-wide view.
Personally I think it's not good, that your function "hides" invalid values as false
and - depending on your use cases - doesn't return true
for "1"
.
Another problem could be that it barfs on anything that's not a string.
I would use something like this:
function parseBool(value) {
if (typeof value === "string") {
value = value.replace(/^\s+|\s+$/g, "").toLowerCase();
if (value === "true" || value === "false")
return value === "true";
}
return; // returns undefined
}
And depending on the use cases extend it to distinguish between "0"
and "1"
.
(Maybe there is a way to compare only once against "true"
, but I couldn't think of something right now.)
So I was having this problem, none of the other remedies worked. The error message was opaque, but checking dmesg was key:
[ 10.118255] NVRM: API mismatch: the client has the version 410.79, but
NVRM: this kernel module has the version 384.130. Please
NVRM: make sure that this kernel module and all NVIDIA driver
NVRM: components have the same version.
However I had completely removed the 384 version, and removed any remaining kernel drivers nvidia-384*
. But even after reboot, I was still getting this. Seeing this meant that the kernel was still compiled to reference 384, but was only finding 410. So I recompiled my kernel:
# uname -a # find the kernel it's using
Linux blah 4.13.0-43-generic #48~16.04.1-Ubuntu SMP Thu May 17 12:56:46 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
# update-initramfs -c -k 4.13.0-43-generic #recompile it
# reboot
And then it worked.
After removing 384, I still had 384 files in: /var/lib/dkms/nvidia-XXX/XXX.YY/4.13.0-43-generic/x86_64/module /lib/modules/4.13.0-43-generic/kernel/drivers
I recommend using the locate
command (not installed by default) rather than searching the filesystem every time.
If you're using underscore.js
you can use its find
and indexOf
functions to get exactly what you want:
var index = _.indexOf(your_array, _.find(your_array, function (d) {
return d === true;
}));
Documentation:
This file works properly as it is: just copy and paste in your computer. Surfing on the web I have found this easy implementation on wikipedia page here. The page is in italian, so I re-wrote the code with some translations. Here there are almost the same informations but in english. ENJOY!
#include <iostream>
#include <complex>
#define MAX 200
using namespace std;
#define M_PI 3.1415926535897932384
int log2(int N) /*function to calculate the log2(.) of int numbers*/
{
int k = N, i = 0;
while(k) {
k >>= 1;
i++;
}
return i - 1;
}
int check(int n) //checking if the number of element is a power of 2
{
return n > 0 && (n & (n - 1)) == 0;
}
int reverse(int N, int n) //calculating revers number
{
int j, p = 0;
for(j = 1; j <= log2(N); j++) {
if(n & (1 << (log2(N) - j)))
p |= 1 << (j - 1);
}
return p;
}
void ordina(complex<double>* f1, int N) //using the reverse order in the array
{
complex<double> f2[MAX];
for(int i = 0; i < N; i++)
f2[i] = f1[reverse(N, i)];
for(int j = 0; j < N; j++)
f1[j] = f2[j];
}
void transform(complex<double>* f, int N) //
{
ordina(f, N); //first: reverse order
complex<double> *W;
W = (complex<double> *)malloc(N / 2 * sizeof(complex<double>));
W[1] = polar(1., -2. * M_PI / N);
W[0] = 1;
for(int i = 2; i < N / 2; i++)
W[i] = pow(W[1], i);
int n = 1;
int a = N / 2;
for(int j = 0; j < log2(N); j++) {
for(int i = 0; i < N; i++) {
if(!(i & n)) {
complex<double> temp = f[i];
complex<double> Temp = W[(i * a) % (n * a)] * f[i + n];
f[i] = temp + Temp;
f[i + n] = temp - Temp;
}
}
n *= 2;
a = a / 2;
}
free(W);
}
void FFT(complex<double>* f, int N, double d)
{
transform(f, N);
for(int i = 0; i < N; i++)
f[i] *= d; //multiplying by step
}
int main()
{
int n;
do {
cout << "specify array dimension (MUST be power of 2)" << endl;
cin >> n;
} while(!check(n));
double d;
cout << "specify sampling step" << endl; //just write 1 in order to have the same results of matlab fft(.)
cin >> d;
complex<double> vec[MAX];
cout << "specify the array" << endl;
for(int i = 0; i < n; i++) {
cout << "specify element number: " << i << endl;
cin >> vec[i];
}
FFT(vec, n, d);
cout << "...printing the FFT of the array specified" << endl;
for(int j = 0; j < n; j++)
cout << vec[j] << endl;
return 0;
}
I like this solution from a similar question. https://stackoverflow.com/a/25036303/2364401 Use bootstraps text-center
class on the actual table data <td>
and table header <th>
elements. So
<td class="text-center">Cell data</td>
and
<th class="text-center">Header cell data</th>
Assuming there is a table config
with unique index on config_code
column:
CONFIG_CODE PARAM1 PARAM2
--------------- -------- --------
default_config def 000
config1 abc 123
config2 def 456
This query returns line for config1
values, because it exists in the table:
SELECT *
FROM (SELECT *
FROM config
WHERE config_code = 'config1'
OR config_code = 'default_config'
ORDER BY CASE config_code WHEN 'default_config' THEN 999 ELSE 1 END)
WHERE rownum = 1;
CONFIG_CODE PARAM1 PARAM2
--------------- -------- --------
config1 abc 123
This one returns default record as config3
doesn't exist in the table:
SELECT *
FROM (SELECT *
FROM config
WHERE config_code = 'config3'
OR config_code = 'default_config'
ORDER BY CASE config_code WHEN 'default_config' THEN 999 ELSE 1 END)
WHERE rownum = 1;
CONFIG_CODE PARAM1 PARAM2
--------------- -------- --------
default_config def 000
In comparison with other solutions this one queries table config
only once.
I like these commands as they use svn status
to find the new or missing files, which respects files that are ignored.
svn add $( svn status | sed -e '/^?/!d' -e 's/^?//' )
svn rm $( svn status | sed -e '/^!/!d' -e 's/^!//' )
TypeDescriptor.GetConverter(PropertyObject).ConvertFrom(Value)
TypeDescriptor
is class having method GetConvertor
which accept a Type
object and then you can call ConvertFrom
method to convert the value
for that specified object.
This is in the feature backlog for Compose but it doesn't look like work has been started yet. Github issue.
what about javascript without jQuery ?
for any input that you can get with or without jQuery, just :
input.readOnly
note : mind camelCase
Without punctuation (as @Burusothman has mentioned):
current_date_time="`date +%Y%m%d%H%M%S`";
echo $current_date_time;
O/P:
20170115072120
With punctuation:
current_date_time="`date "+%Y-%m-%d %H:%M:%S"`";
echo $current_date_time;
O/P:
2017-01-15 07:25:33
If your experiencing the same problem while querying a DB2 database, you'll need to use the below query.
SELECT *
FROM OPENQUERY(LINK_DB,'SELECT
CITY,
cast(STATE as varchar(40))
FROM DATABASE')
For Windows
pip install mysql-connector
For Ubuntu /Linux
sudo apt-get install python3-pymysql
You can also wrap the view in a FrameLayout, then set the frame's background color and padding to what you want; however, the textview, by default has a 'transparent' background, so you'd need to change the textview's background color too.
Generally, Postman used for debugging and used in the development phase. But in case you want to block it even from postman try this.
const referrer_domain = "[enter-the-domain-name-of-the-referrer]"
//check for the referrer domain
app.all('/*', function(req, res, next) {
if(req.headers.referer.indexOf(referrer_domain) == -1){
res.send('Invalid Request')
}
next();
});
I used a different tactic, fields that are allocated 8K in some places. Here only about 50/100 are used.
declare @NVPN_list as table
nvpn varchar(50)
,nvpn_revision varchar(5)
,nvpn_iteration INT
,mpn_lifecycle varchar(30)
,mfr varchar(100)
,mpn varchar(50)
,mpn_revision varchar(5)
,mpn_iteration INT
-- ...
) INSERT INTO @NVPN_LIST
SELECT left(nvpn ,50) as nvpn
,left(nvpn_revision ,10) as nvpn_revision
,nvpn_iteration
,left(mpn_lifecycle ,30)
,left(mfr ,100)
,left(mpn ,50)
,left(mpn_revision ,5)
,mpn_iteration
,left(mfr_order_num ,50)
FROM [DASHBOARD].[dbo].[mpnAttributes] (NOLOCK) mpna
I wanted speed, since I have 1M total records, and load 28K of them.
I would omit the * { text-align:center }
declaration, as it sets center alignment for all elements.
Usually with a fixed width container margin: 0 auto
should be enough
No packages needed:
String paddedString = i < 100 ? i < 10 ? "00" + i : "0" + i : "" + i;
This will pad the string to three characters, and it is easy to add a part more for four or five. I know this is not the perfect solution in any way (especially if you want a large padded string), but I like it.
However, interface is 100% abstract class and abstract class can implements interface(100% abstract class) without implement its methods. What is the problem when it is defining as "interface" ?
This is simply a matter of convention. The writers of the java language decided that "extends" is the best way to describe this relationship, so that's what we all use.
In general, even though an interface is "a 100% abstract class," we don't think about them that way. We usually think about interfaces as a promise to implement certain key methods rather than a class to derive from. And so we tend to use different language for interfaces than for classes.
As others state, there are good reasons for choosing "extends" over "implements."
There are two BeanUtils.copyProperties(parameter1, parameter2) in Java.
One is
org.apache.commons.beanutils.BeanUtils.copyProperties(Object dest, Object orig)
Another is
org.springframework.beans.BeanUtils.copyProperties(Object source, Object target)
Pay attention to the opposite position of parameters.
In my case it worked at first and after a while stopped working and IIS Express reported that the port was in use.
netstat -ab
showed that Chrome was using the port. After I quit Chrome, it started working again.
I am not sure however, why Chrome would occupy that port.
Node.js does not run in a browser, therefore you will not have a document
object available. Actually, you will not even have a DOM tree at all. If you are a bit confused at this point, I encourage you to read more about it before going further.
There are a few methods you can choose from to do what you want.
Because you wrote about opening the file in the browser, why don't you use a framework that will serve the file directly as an HTTP service, instead of having a two-step process? This way, your code will be more dynamic and easily maintainable (not mentioning your HTML always up-to-date).
There are plenty frameworks out there for that :
The most basic way you could do what you want is this :
var http = require('http');
http.createServer(function (req, res) {
var html = buildHtml(req);
res.writeHead(200, {
'Content-Type': 'text/html',
'Content-Length': html.length,
'Expires': new Date().toUTCString()
});
res.end(html);
}).listen(8080);
function buildHtml(req) {
var header = '';
var body = '';
// concatenate header string
// concatenate body string
return '<!DOCTYPE html>'
+ '<html><head>' + header + '</head><body>' + body + '</body></html>';
};
And access this HTML with http://localhost:8080
from your browser.
(Edit: you could also serve them with a small HTTP server.)
If what you are trying to do is simply generating some HTML files, then go simple. To perform IO access on the file system, Node has an API for that, documented here.
var fs = require('fs');
var fileName = 'path/to/file';
var stream = fs.createWriteStream(fileName);
stream.once('open', function(fd) {
var html = buildHtml();
stream.end(html);
});
Note: The buildHtml
function is exactly the same as in Method 1.
stdout
This is the most basic Node.js implementation and requires the invoking application to handle the output itself. To output something in Node (ie. to stdout), the best way is to use console.log(message)
where message
is any string, or object, etc.
var html = buildHtml();
console.log(html);
Note: The buildHtml
function is exactly the same as in Method 1 (again)
If your script is called html-generator.js
(for example), in Linux/Unix based system, simply do
$ node html-generator.js > path/to/file
Because Node is a modular system, you can even put the buildHtml
function inside it's own module and simply write adapters to handle the HTML however you like. Something like
var htmlBuilder = require('path/to/html-builder-module');
var html = htmlBuilder(options);
...
You have to think "server-side" and not "client-side" when writing JavaScript for Node.js; you are not in a browser and/or limited to a sandbox, other than the V8 engine.
Extra reading, learn about npm. Hope this helps.
I did this in 1.9.1 (to delete the last or latest migration created):
rm <appname>/migrations/<migration #>*
example: rm myapp/migrations/0011*
logged into database and ran this SQL (postgres in this example)
delete from django_migrations where name like '0011%';
I was then able to create new migrations that started with the migration number that I had just deleted (in this case, 11).
Found this:
public String MD5(String md5) {
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] array = md.digest(md5.getBytes());
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; ++i) {
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
}
return sb.toString();
} catch (java.security.NoSuchAlgorithmException e) {
}
return null;
}
on the site below, I take no credit for it, but its a solution that works! For me lots of other code didnt work properly, I ended up missing 0s in the hash. This one seems to be the same as PHP has. source: http://m2tec.be/blog/2010/02/03/java-md5-hex-0093
There's no simple answer to this question. Apple's mobile version of WebKit, used in iPhones, iPod Touches, and iPads, will scale the page to fit the screen, at which point the user can zoom in and out freely.
That said, you can design your page to minimize the amount of zooming necessary. Your best bet is to make the width and height the same as the lower resolution of the iPad, since you don't know which way it's oriented; in other words, you would make your page 768x768, so that it will fit well on the iPad's screen whether it's oriented to be 1024x768 or 768x1024.
More importantly, you'd want to design your page with big controls with lots of space that are easy to hit with your thumbs - you could easily design a 768x768 page that was very cluttered and therefore required lots of zooming. To accomplish this, you'll likely want to divide your controls among a number of web pages.
On the other hand, it's not the most worthwhile pursuit. If while designing you find opportunities to make your page more "finger-friendly", then go for it...but the reality is that iPad users are very comfortable with moving around and zooming in and out of the page to get to things because it's necessary on most web sites. If anything, you probably want to design it so that it's conducive to this type of navigation.
Make boxes with relevant grouped data that can be easily double-tapped to focus on, and keep related controls close to each other. iPad users will most likely appreciate a page that facilitates the familiar zoom-and-pan navigation they're accustomed to more than they will a page that has fewer controls so that they don't have to.
I am contributing here, as the OP asked:
How to change collation of database, table, column?
The selected answer just states it on table level.
Changing it database wide:
ALTER DATABASE <database_name> CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Changing it per table:
ALTER TABLE <table_name> CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Good practice is to change it at table level as it'll change it for columns as well. Changing for specific column is for any specific case.
Changing collation for a specific column:
ALTER TABLE <table_name> MODIFY <column_name> VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
The zoo
package has the function of as.yearmon
can help to convert.
require(zoo)
df$ym<-as.yearmon(df$date, "%Y %m")
Ruby's enumeration loop syntax is different:
collection.each do |item|
...
end
This reads as "a call to the 'each' method of the array object instance 'collection' that takes block with 'blockargument' as argument". The block syntax in Ruby is 'do ... end' or '{ ... }' for single line statements.
The block argument '|item|' is optional but if provided, the first argument automatically represents the looped enumerated item.
I would like to run an automation test in different environments.
So I add this to command maven command:
spring-boot:run -Drun.jvmArguments="-Dspring.profiles.active=productionEnv1"
Here is the link where I found the solution: [1]https://github.com/spring-projects/spring-boot/issues/1095
You want to use single quotes:
if(c=='\0')
Double quotes (") are for strings, which are sequences of characters. Single quotes (') are for individual characters.
However, the end-of-line is represented by the newline character, which is '\n'.
Note that in both cases, the backslash is not part of the character, but just a way you represent special characters. Using backslashes you can represent various unprintable characters and also characters which would otherwise confuse the compiler.
It's also possible to customise your bootstrap build by using:
http://twitter.github.com/bootstrap/customize.html
All the plugins are included by default.
If you're running into javascript namespace collisions, you can use Bootstrap's noConflict()
function make it cede functionality to jQuery UI.
I feel your pain, I'm trying to do the same thing. In my case I just want to clear the user.
I've created a base controller class that all my controllers inherit from. In it I override OnAuthentication
and set the filterContext.HttpContext.User to null
That's the best I've managed to far...
public abstract class ApplicationController : Controller
{
...
protected override void OnAuthentication(AuthenticationContext filterContext)
{
base.OnAuthentication(filterContext);
if ( ... )
{
// You may find that modifying the
// filterContext.HttpContext.User
// here works as desired.
// In my case I just set it to null
filterContext.HttpContext.User = null;
}
}
...
}
You can also do it in code if you need more control, for example multiple colors and positioning. Here is my Kotlin snippet to create a drawable radial gradient:
object ShaderUtils {
private class RadialShaderFactory(private val colors: IntArray, val positionX: Float,
val positionY: Float, val size: Float): ShapeDrawable.ShaderFactory() {
override fun resize(width: Int, height: Int): Shader {
return RadialGradient(
width * positionX,
height * positionY,
minOf(width, height) * size,
colors,
null,
Shader.TileMode.CLAMP)
}
}
fun radialGradientBackground(vararg colors: Int, positionX: Float = 0.5f, positionY: Float = 0.5f,
size: Float = 1.0f): PaintDrawable {
val radialGradientBackground = PaintDrawable()
radialGradientBackground.shape = RectShape()
radialGradientBackground.shaderFactory = RadialShaderFactory(colors, positionX, positionY, size)
return radialGradientBackground
}
}
Basic usage (but feel free to adjust with additional params):
view.background = ShaderUtils.radialGradientBackground(Color.TRANSPARENT, BLACK)
If using Posix regex (grep -E
, MySQL, etc.), this may be easier to read & remember:
[[:xdigit:]]{8}(-[[:xdigit:]]{4}){3}-[[:xdigit:]]{12}
Edit: Perl & PCRE flavours also support Posix character classes so this'll work with them. For those, change the (…)
to a non-capturing subgroup (?:…)
.
Select the Body using chrome dev tools (Inspect ) and change in css overflow:visible,
If that doesn't work then check in below css file if html, body is set as overflow:hidden , change it as visible
For time:
label1.Text = DateTime.Now.ToString("HH:mm:ss"); //result 22:11:45
or
label1.Text = DateTime.Now.ToString("hh:mm:ss tt"); //result 11:11:45 PM
For date:
label1.Text = DateTime.Now.ToShortDateString(); //30.5.2012
I learnt a easy way from code example of http://tutorial.symblog.co.uk/
1) notice the ZendeskBlueFormBundle and file location
# myproject/app/config/config.yml
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: @ZendeskBlueFormBundle/Resources/config/config.yml }
framework:
2) notice Zendesk_BlueForm.emails.contact_email and file location
# myproject/src/Zendesk/BlueFormBundle/Resources/config/config.yml
parameters:
# Zendesk contact email address
Zendesk_BlueForm.emails.contact_email: [email protected]
3) notice how i get it in $client and file location of controller
# myproject/src/Zendesk/BlueFormBundle/Controller/PageController.php
public function blueFormAction($name, $arg1, $arg2, $arg3, Request $request)
{
$client = new ZendeskAPI($this->container->getParameter("Zendesk_BlueForm.emails.contact_email"));
...
}
The .NET Library EPPlus implements a conversation from the string definition to the built in number. See class ExcelNumberFormat:
internal static int GetFromBuildIdFromFormat(string format)
{
switch (format)
{
case "General":
return 0;
case "0":
return 1;
case "0.00":
return 2;
case "#,##0":
return 3;
case "#,##0.00":
return 4;
case "0%":
return 9;
case "0.00%":
return 10;
case "0.00E+00":
return 11;
case "# ?/?":
return 12;
case "# ??/??":
return 13;
case "mm-dd-yy":
return 14;
case "d-mmm-yy":
return 15;
case "d-mmm":
return 16;
case "mmm-yy":
return 17;
case "h:mm AM/PM":
return 18;
case "h:mm:ss AM/PM":
return 19;
case "h:mm":
return 20;
case "h:mm:ss":
return 21;
case "m/d/yy h:mm":
return 22;
case "#,##0 ;(#,##0)":
return 37;
case "#,##0 ;[Red](#,##0)":
return 38;
case "#,##0.00;(#,##0.00)":
return 39;
case "#,##0.00;[Red](#,#)":
return 40;
case "mm:ss":
return 45;
case "[h]:mm:ss":
return 46;
case "mmss.0":
return 47;
case "##0.0":
return 48;
case "@":
return 49;
default:
return int.MinValue;
}
}
When you use one of these formats, Excel will automatically identify them as a standard format.
All mentioned solutions are legit but if we're talking about elegance then I'll pitch in with the following example:
//function that checks if an object is null
var isNull = function(obj) {
return obj == null;
}
if(isNull(results)){
return 0;
} else {
return results[1] || 0;
}
Using the isNull function helps the code be more readable.
Hypothetically, if search landed you on this question then you probably want this:
doReturn(someReturn).when(someObject).doSomething(argThat(argument -> argument.getName().equals("Bob")));
Why? Because like me you value time and you are not going to implement .equals
just for the sake of the single test scenario.
And 99 % of tests fall apart with null returned from Mock and in a reasonable design you would avoid return null
at all costs, use Optional
or move to Kotlin. This implies that verify
does not need to be used that often and ArgumentCaptors are just too tedious to write.
This worked for me: Open task manager (of your OS) and kill adb.exe process. Now start adb again, now adb should start normally.
The simples way is to use 'to' property:
<Link to="chart" target="_blank" to="http://link2external.page.com" >Test</Link>
Scaffold(
backgroundColor: Constants.defaulBackground,
body: new Container(
child: Center(yourtext)
)
)
var divID = "question-" + (parseInt(i)+1);
Use this +
operator behave as concat
that's why it showing 11.
From the documentation:
list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, soa.insert(0, x)
inserts at the front of the list, anda.insert(len(a),x)
is equivalent toa.append(x)
http://docs.python.org/2/tutorial/datastructures.html#more-on-lists
You are opening the csv file in binary mode, it should be 'w'
import csv
# open csv file in write mode with utf-8 encoding
with open('output.csv','w',encoding='utf-8',newline='')as w:
fieldnames = ["SNo", "States", "Dist", "Population"]
writer = csv.DictWriter(w, fieldnames=fieldnames)
# write list of dicts
writer.writerows(list_of_dicts) #writerow(dict) if write one row at time
public class AesCryptoService
{
private static byte[] Key = Encoding.ASCII.GetBytes(@"qwr{@^h`h&_`50/ja9!'dcmh3!uw<&=?");
private static byte[] IV = Encoding.ASCII.GetBytes(@"9/\~V).A,lY&=t2b");
public static string EncryptStringToBytes_Aes(string plainText)
{
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
byte[] encrypted;
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
aesAlg.Mode = CipherMode.CBC;
aesAlg.Padding = PaddingMode.PKCS7;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
return Convert.ToBase64String(encrypted);
}
public static string DecryptStringFromBytes_Aes(string Text)
{
if (Text == null || Text.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
string plaintext = null;
byte[] cipherText = Convert.FromBase64String(Text.Replace(' ', '+'));
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
aesAlg.Mode = CipherMode.CBC;
aesAlg.Padding = PaddingMode.PKCS7;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
}
Hi if you are having dropdownlist like this
<select id="testID">
<option value="1">Value1</option>
<option value="2">Value2</option>
<option value="3">Value3</option>
<option value="4">Value4</option>
<option value="5">Value5</option>
<option value="6">Value6</option>
</select>
<input type="button" value="Get dropdown selected Value" onclick="getHTML();">
after giving id to dropdownlist you just need to add jquery code like this
function getHTML()
{
var display=$('#testID option:selected').html();
alert(display);
}
I have successfully used the Enterprise DT FTP library, which is free and open source. I can't compare it to other libraries (like the Apache Commons Net library) since I haven't used them. It does provide a simple upgrade path to SFTP (over SSH) and FTPS (over SSL), though that is a pay-for commercial product.
I would suggest the use of exists
instead of in
because in some scenarios that implies null values the behavior is different, so
CREATE TRIGGER sampleTrigger
ON database1.dbo.table1
FOR DELETE
AS
DELETE FROM database2.dbo.table2 childTable
WHERE bar = 4 AND exists (SELECT id FROM deleted where deleted.id = childTable.id)
GO
delete node_modules/browserslist
directory in the project
now
npm run build
no longer generates that message
I just want to notice that startActivity
from outside an activity is valid in some android versions (between N and O-MR1) and the interesting point is that it is a bug in android source code!
This is the comment above startActivity
implementation. See here.
Calling start activity from outside an activity without FLAG_ACTIVITY_NEW_TASK is generally not allowed, except if the caller specifies the task id the activity should be launched in. A bug was existed between N and O-MR1 which allowed this to work.
for swift4:
if obj is MyClass{
// then object type is MyClass Type
}
Using
Dim myarray As Variant
works but
Dim myarray As String
doesn't so I sitck to Variant
Use contains instead:
In [10]: df.b.str.contains('^f')
Out[10]:
0 False
1 True
2 True
3 False
Name: b, dtype: bool
If you are only interested in +0.0
and -0.0
, you can use fpclassify
from <cmath>
. For instance:
if( FP_ZERO == fpclassify(x) ) do_something;
Boolean
wraps the boolean primitive type. In JDK 5 and upwards, Oracle (or Sun before Oracle bought them) introduced autoboxing/unboxing, which essentially allows you to do this
boolean result = Boolean.TRUE;
or
Boolean result = true;
Which essentially the compiler does,
Boolean result = Boolean.valueOf(true);
So, for your answer, it's YES.
1 for month is February. The 30th of February is changed to 1st of March. You should set 0 for month. The best is to use the constant defined in Calendar:
c1.set(2000, Calendar.JANUARY, 30);
Supposing you're using plain JS (see other answers for jQuery), to change an element's opacity, write:
var element = document.getElementById('id');
element.style.opacity = "0.9";
element.style.filter = 'alpha(opacity=90)'; // IE fallback
I got similar error after deleting a subproject, removed
"*compile project(path: ':MySubProject', configuration: 'android-endpoints')*"
in build.gradle
(dependencies) under Gradle Scripts
In JavaScript you cannot have the direct access to the filesystem.
However, you can make browser to pop up a dialog window allowing the user to pick the save location. In order to do this, use the replace
method with your Base64String and replace "image/png"
with "image/octet-stream"
:
"data:image/png;base64,iVBORw0KG...".replace("image/png", "image/octet-stream");
Also, W3C-compliant browsers provide 2 methods to work with base64-encoded and binary data:
Probably, you will find them useful in a way...
Here is a refactored version of what I understand you need:
window.addEventListener('DOMContentLoaded', () => {_x000D_
const img = document.getElementById('embedImage');_x000D_
img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' +_x000D_
'AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO' +_x000D_
'9TXL0Y4OHwAAAABJRU5ErkJggg==';_x000D_
_x000D_
img.addEventListener('load', () => button.removeAttribute('disabled'));_x000D_
_x000D_
const button = document.getElementById('saveImage');_x000D_
button.addEventListener('click', () => {_x000D_
window.location.href = img.src.replace('image/png', 'image/octet-stream');_x000D_
});_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
<img id="embedImage" alt="Red dot" />_x000D_
<button id="saveImage" disabled="disabled">save image</button>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Here's how I do file upload in react using axios
import React from 'react'
import axios, { post } from 'axios';
class SimpleReactFileUpload extends React.Component {
constructor(props) {
super(props);
this.state ={
file:null
}
this.onFormSubmit = this.onFormSubmit.bind(this)
this.onChange = this.onChange.bind(this)
this.fileUpload = this.fileUpload.bind(this)
}
onFormSubmit(e){
e.preventDefault() // Stop form submit
this.fileUpload(this.state.file).then((response)=>{
console.log(response.data);
})
}
onChange(e) {
this.setState({file:e.target.files[0]})
}
fileUpload(file){
const url = 'http://example.com/file-upload';
const formData = new FormData();
formData.append('file',file)
const config = {
headers: {
'content-type': 'multipart/form-data'
}
}
return post(url, formData,config)
}
render() {
return (
<form onSubmit={this.onFormSubmit}>
<h1>File Upload</h1>
<input type="file" onChange={this.onChange} />
<button type="submit">Upload</button>
</form>
)
}
}
export default SimpleReactFileUpload
Only Window.onResize
exists in the specification, but you can always utilize IFrame
to generate new Window
object inside your DIV.
Please check this answer. There is a new little jquery plugin, that is portable and easy to use. You can always check the source code to see how it's done.
<!-- (1) include plugin script in a page -->
<script src="/src/jquery-element-onresize.js"></script>
// (2) use the detectResizing plugin to monitor changes to the element's size:
$monitoredElement.detectResizing({ onResize: monitoredElement_onResize });
// (3) write a function to react on changes:
function monitoredElement_onResize() {
// logic here...
}
I had the same issue. It seems the easiest solution is to just remove the remote, readd it, and fetch.
You could also try wrapping the two div's in two div's with unique ids. Then select the div by $("#div1","#wraper1")
and $("#div1","#wraper2")
Here you go:
<div id="wraper1">
<div id="div1">
</div>
<div id="wraper2">
<div id="div1">
</div>
$('#attached_docs [value="123"]').find ... .remove();
it should do your need however, you cannot duplicate id! remember it
I can't find a way to do this with code, but in stock Firefox 64, events are listed next to each HTML entity in the Developer Tools Inspector as noted on MDN's Examine Event Listeners page and as demonstrated in this image:
Probably you instance old fragment it is keeping a reference. See this interesting article Memory leaks in Android — identify, treat and avoid
If you use addToBackStack, this keeps a reference to instance fragment avoiding to Garbage Collector erase the instance. The instance remains in fragments list in fragment manager. You can see the list by
ArrayList<Fragment> fragmentList = fragmentManager.getFragments();
The next code is not the best solution (because don´t remove the old fragment instance in order to avoid memory leaks) but removes the old fragment from fragmentManger fragment list
int index = fragmentManager.getFragments().indexOf(oldFragment);
fragmentManager.getFragments().set(index, null);
You cannot remove the entry in the arrayList because apparenly FragmentManager works with index ArrayList to get fragment.
I usually use this code for working with fragmentManager
public void replaceFragment(Fragment fragment, Bundle bundle) {
if (bundle != null)
fragment.setArguments(bundle);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment oldFragment = fragmentManager.findFragmentByTag(fragment.getClass().getName());
//if oldFragment already exits in fragmentManager use it
if (oldFragment != null) {
fragment = oldFragment;
}
fragmentTransaction.replace(R.id.frame_content_main, fragment, fragment.getClass().getName());
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragmentTransaction.commit();
}
My observation on initial accepted solution.
Under RR (default mysql) - If a tx is open and a SELECT has been fired, another tx can NOT delete any row belonging to previous READ result set until previous tx is committed (in fact delete statement in the new tx will just hang), however the next tx can delete all rows from the table without any trouble. Btw, a next READ in previous tx will still see the old data until it is committed.
An alternative solution uses the stash:
Before:
~/dev/gitpro $git stash list
~/dev/gitpro $git log --oneline -3
* 7049dd5 (HEAD -> master) c111
* 3f1fa3d c222
* 0a0f6c4 c333
note you cannot run 'git stash pop' without specifying the stash@{1} entry. The stash is a LIFO stack -- not FIFO -- so that would incorrectly pop the stash@{0} entry with c222's changes (instead of stash@{1} with c111's changes).
note if there are conflicting chunks between commits 111 and 222, then you'll be forced to resolve them when attempting to pop. (This would be the case if you went with an alternative rebase solution as well.)
After:
~/dev/gitpro $git stash list
stash@{0}: On master: c222
~/dev/gitpro $git log -2 --oneline
* edbd9e8 (HEAD -> master) c111
* 0a0f6c4 c333
I finally found out how to do this! Basically you need to run adb shell
first and then while you're in the shell run su
, which will switch the shell to run as root!
$: adb shell
$: su
The one problem I still have is that sqlite3 is not installed so the command is not recognized.
Class<?> cls = Class.forName(className);
But your className
should be fully-qualified - i.e. com.mycompany.MyClass
I'd probably use an ImageIcon and set it on a JLabel which I'd add to the JPanel.
Here's Sun's docs on the subject matter.
There's a short discussion of what appears to be this issue here. The page it links to appears to be gone, but one of the responses might be what you need:
Indeed, copying US_export_policy.jar and local_policy.jar from core/lib/jce to $JAVA_HOME/jre/lib/security helped. Thanks.
There actually is an example how to create a circle IconButton similar to the FloatingActionButton.
Ink(
decoration: const ShapeDecoration(
color: Colors.lightBlue,
shape: CircleBorder(),
),
child: IconButton(
icon: Icon(Icons.home),
onPressed: () {},
),
)
To create a local project with this code sample, run:
flutter create --sample=material.IconButton.2 mysample
$ disown node server.js &
It will remove command from active task list and send the command to background
The primary consumers of these properties are user agents such as screen readers for blind people. So in the case with a Bootstrap modal, the modal's div
has role="dialog"
. When the screen reader notices that a div
becomes visible which has this role, it'll speak the label for that div
.
There are lots of ways to label things (and a few new ones with ARIA), but in some cases it is appropriate to use an existing element as a label (semantic) without using the <label>
HTML tag. With HTML modals the label is usually a <h>
header. So in the Bootstrap modal case, you add aria-labelledby=[IDofModalHeader]
, and the screen reader will speak that header when the modal appears.
Generally speaking a screen reader is going to notice whenever DOM elements become visible or invisible, so the aria-hidden
property is frequently redundant and can probably be skipped in most cases.
This is not directly to your code sample, but in general about the error. I'm writing it here, because Google directs this error to this question, so it may be useful for the other devs.
Another use case when you can receive such error is when you're adding a selector to method in another class, eg:
private class MockTextFieldTarget {
private(set) var didCallDoneAction = false
@objc func doneActionHandler() {
didCallDoneAction = true
}
}
And then in another class:
final class UITextFieldTests: XCTestCase {
func testDummyCode() {
let mockTarget = MockTextFieldTarget()
UIBarButtonItem(barButtonSystemItem: .cancel, target: mockTarget, action: MockTextFieldTarget.doneActionHandler)
// ... do something ...
}
}
If in the last line you'd simply call #selector(cancelActionHandler)
instead of #selector(MockTextFieldTarget.cancelActionHandler)
, you'd get
use of unresolved identifier
error.
In order to return filename without extension and without parameters use the following:
String filenameWithParams = FilenameUtils.getBaseName(urlStr); // may hold params if http://example.com/a?param=yes
return filenameWithParams.split("\\?")[0]; // removing parameters from url if they exist
In order to return filename with extension without params use this:
/** Parses a URL and extracts the filename from it or returns an empty string (if filename is non existent in the url) <br/>
* This method will work in win/unix formats, will work with mixed case of slashes (forward and backward) <br/>
* This method will remove parameters after the extension
*
* @param urlStr original url string from which we will extract the filename
* @return filename from the url if it exists, or an empty string in all other cases */
private String getFileNameFromUrl(String urlStr) {
String baseName = FilenameUtils.getBaseName(urlStr);
String extension = FilenameUtils.getExtension(urlStr);
try {
extension = extension.split("\\?")[0]; // removing parameters from url if they exist
return baseName.isEmpty() ? "" : baseName + "." + extension;
} catch (NullPointerException npe) {
return "";
}
}
import java.util.Calendar;
import java.util.Locale;
import static java.util.Calendar.*;
import java.util.Date;
public static int getDiffYears(Date first, Date last) {
Calendar a = getCalendar(first);
Calendar b = getCalendar(last);
int diff = b.get(YEAR) - a.get(YEAR);
if (a.get(MONTH) > b.get(MONTH) ||
(a.get(MONTH) == b.get(MONTH) && a.get(DATE) > b.get(DATE))) {
diff--;
}
return diff;
}
public static Calendar getCalendar(Date date) {
Calendar cal = Calendar.getInstance(Locale.US);
cal.setTime(date);
return cal;
}
You might want to start with scapy.
Apache Commons Lang provides a host of helper utilities for the java.lang API, most notably String manipulation methods. In your case, the start and end substrings are the same, so just call the following function.
StringUtils.substringBetween(String str, String tag)
Gets the String that is nested in between two instances of the same String.
If the start and the end substrings are different then use the following overloaded method.
StringUtils.substringBetween(String str, String open, String close)
Gets the String that is nested in between two Strings.
If you want all instances of the matching substrings, then use,
StringUtils.substringsBetween(String str, String open, String close)
Searches a String for substrings delimited by a start and end tag, returning all matching substrings in an array.
For the example in question to get all instances of the matching substring
String[] results = StringUtils.substringsBetween(mydata, "'", "'");
This works for me
$('.someclass').click(function() {
$varName = $(this).data('fulltext');
console.log($varName);
});
This problem has been studied in some depth by physicists. There is a good implementation in ROOT. Look at the TSpectrum classes (especially TSpectrum2 for your case) and the documentation for them.
References:
...and for those who don't have access to a subscription to NIM:
Changing a constant type will lead to an Undefined Behavior.
However, if you have an originally non-const object which is pointed to by a pointer-to-const or referenced by a reference-to-const then you can use const_cast to get rid of that const-ness.
Casting away constness is considered evil and should not be avoided. You should consider changing the type of the pointers you use in vector to non-const if you want to modify the data through it.
stdout
is the standard output stream in UNIX. See http://www.gnu.org/software/libc/manual/html_node/Standard-Streams.html#Standard-Streams.
When running in a terminal, you will see data written to stdout
in the terminal and you can redirect it as you choose.
Assuming they always exist and are not part of your data, this will work:
declare @string varchar(8000) = '23;chair,red [$3]'
select substring(@string, charindex(';', @string) + 1, charindex(' [', @string) - charindex(';', @string) - 1)
Then you need a ArrayList
of ArrayLists
:
ArrayList<ArrayList<String>> nodes = new ArrayList<ArrayList<String>>();
ArrayList<String> nodeList = new ArrayList<String>();
nodes.add(nodeList);
Note that NodeList
has been changed to nodeList
. In Java Naming Conventions variables start with a lower case. Classes start with an upper case.
for i in count:
means for i in 7:
, which won't work. The bit after the in
should be of an iterable type, not a number. Try this:
for i in range(count):
I suspect this just hasn’t been implemented properly yet. The Swift Programming Guide definitely seems to imply that the compiler can infer exhaustive matches 'like a switch statement'. It doesn’t make any mention of needing a general catch
in order to be exhaustive.
You'll also notice that the error is on the try
line, not the end of the block, i.e. at some point the compiler will be able to pinpoint which try
statement in the block has unhandled exception types.
The documentation is a bit ambiguous though. I’ve skimmed through the ‘What’s new in Swift’ video and couldn’t find any clues; I’ll keep trying.
Update:
We’re now up to Beta 3 with no hint of ErrorType inference. I now believe if this was ever planned (and I still think it was at some point), the dynamic dispatch on protocol extensions probably killed it off.
Beta 4 Update:
Xcode 7b4 added doc comment support for Throws:
, which “should be used to document what errors can be thrown and why”. I guess this at least provides some mechanism to communicate errors to API consumers. Who needs a type system when you have documentation!
Another update:
After spending some time hoping for automatic ErrorType
inference, and working out what the limitations would be of that model, I’ve changed my mind - this is what I hope Apple implements instead. Essentially:
// allow us to do this:
func myFunction() throws -> Int
// or this:
func myFunction() throws CustomError -> Int
// but not this:
func myFunction() throws CustomErrorOne, CustomErrorTwo -> Int
Yet Another Update
Apple’s error handling rationale is now available here. There have also been some interesting discussions on the swift-evolution mailing list. Essentially, John McCall is opposed to typed errors because he believes most libraries will end up including a generic error case anyway, and that typed errors are unlikely to add much to the code apart from boilerplate (he used the term 'aspirational bluff'). Chris Lattner said he’s open to typed errors in Swift 3 if it can work with the resilience model.
If what interests you is bitwise operations look here for a brief tutorial : http://weblogs.asp.net/alessandro/archive/2007/10/02/bitwise-operators-in-c-or-xor-and-amp-amp-not.aspx .bitwise operation perform the same operations like the ones exemplified above they just work with binary representation (the operation applies to each individual bit of the value)
If you want logical operation answers are already given.
You just need to divide each element by the sum of the values in its column.
Doing this should suffice:
data.perc <- apply(data, 2, function(x){x/sum(x)})
Note that the second parameter tells apply
to apply the provided function to columns (using 1 you would apply it to rows). The anonymous function, then, gets passed each data column, one at a time.
If the variable is interchangable, you must have logic somewhere that's determining which variable gets used. All you need to do is put the variable name in $variable
within that logic while you're doing everything else.
I think we're all having a hard time understanding what you're needing this for. Sample code or an explanation of what you're actually trying to do might help, but I suspect you're way, way overthinking this.
Try this.
20 4 * * *
Check the below Screenshot
Referred URL - https://www.lenar.io/jenkins-schedule-build-periodically/
file_get_contents()
is a simple screwdriver. Great for simple GET requests where the header, HTTP request method, timeout, cookiejar, redirects, and other important things do not matter.
fopen()
with a stream context or cURL with setopt are powerdrills with every bit and option you can think of.
For 2020 Mac OS X Catalina users:
Forget about other useless answers, here only two steps needed:
Create a file with the naming convention: priority-appname. Then copy-paste the path you want to add to PATH
.
E.g. 80-vscode
with content /Applications/Visual Studio Code.app/Contents/Resources/app/bin/
in my case.
Move that file to /etc/paths.d/
. Don't forget to open a new tab(new session) in the Terminal and type echo $PATH
to check that your path is added!
Notice: this method only appends your path to PATH
.
Well, your code is not reproducible so we will never know for sure, but this is what help('break')
says:
break breaks out of a for, while or repeat loop; control is transferred to the first statement outside the inner-most loop.
So yes, break
only breaks the current loop. You can also see it in action with e.g.:
for (i in 1:10)
{
for (j in 1:10)
{
for (k in 1:10)
{
cat(i," ",j," ",k,"\n")
if (k ==5) break
}
}
}
As "docker ps --size" produces heavy IO load on host, it is not feasable running such command every minute in a production environment. Therefore we have to do a workaround in order to get desired container size or to be more precise, the size of the RW-Layer with a low impact to systems perfomance.
This approach gathers the "device name" of every container and then checks size of it using "df" command. Those "device names" are thin provisioned volumes that a mounted to / on each container. One problem still persists as this observed size also implies all the readonly-layers of underlying image. In order to address this we can simple check size of used container image and substract it from size of a device/thin_volume.
One should note that every image layer is realized as a kind of a lvm snapshot when using device mapper. Unfortunately I wasn't able to get my rhel system to print out those snapshots/layers. Otherwise we could simply collect sizes of "latest" snapshots. Would be great if someone could make things clear. However...
After some tests, it seems that creation of a container always adds an overhead of approx. 40MiB (tested with containers based on Image "httpd:2.4.46-alpine"):
Following shell prints results (in bytes) that match results from "docker ps --size" (but keep in mind mentioned overhead of 40MB)
for c in $(docker ps -q); do \
container_name=$(docker inspect -f "{{.Name}}" ${c} | sed 's/^\///g' ); \
device_n=$(docker inspect -f "{{.GraphDriver.Data.DeviceName}}" ${c} | sed 's/.*-//g'); \
device_size_kib=$(df -T | grep ${device_n} | awk '{print $4}'); \
device_size_byte=$((1024 * ${device_size_kib})); \
image_sha=$(docker inspect -f "{{.Image}}" ${c} | sed 's/.*://g' ); \
image_size_byte=$(docker image inspect -f "{{.Size}}" ${image_sha}); \
container_size_byte=$((${device_size_byte} - ${image_size_byte})); \
\
echo my_node_dm_device_size_bytes\{cname=\"${container_name}\"\} ${device_size_byte}; \
echo my_node_dm_container_size_bytes\{cname=\"${container_name}\"\} ${container_size_byte}; \
echo my_node_dm_image_size_bytes\{cname=\"${container_name}\"\} ${image_size_byte}; \
done
Further reading about device mapper: https://test-dockerrr.readthedocs.io/en/latest/userguide/storagedriver/device-mapper-driver/
Posting it from my project.
<select name="parent" id="parent"><option value="0">None</option>
<?php
$select="select=selected";
$allparent=mysql_query("select * from tbl_page_content where parent='0'");
while($parent=mysql_fetch_array($allparent))
{?>
<option value="<?= $parent['id']; ?>" <?php if( $pageDetail['parent']==$parent['id'] ) { echo($select); }?>><?= $parent['name']; ?></option>
<?php
}
?></select>
This has nothing to do with the MULTILINE flag; what you're seeing is the difference between the find()
and matches()
methods. find()
succeeds if a match can be found anywhere in the target string, while matches()
expects the regex to match the entire string.
Pattern p = Pattern.compile("xyz");
Matcher m = p.matcher("123xyzabc");
System.out.println(m.find()); // true
System.out.println(m.matches()); // false
Matcher m = p.matcher("xyz");
System.out.println(m.matches()); // true
Furthermore, MULTILINE
doesn't mean what you think it does. Many people seem to jump to the conclusion that you have to use that flag if your target string contains newlines--that is, if it contains multiple logical lines. I've seen several answers here on SO to that effect, but in fact, all that flag does is change the behavior of the anchors, ^
and $
.
Normally ^
matches the very beginning of the target string, and $
matches the very end (or before a newline at the end, but we'll leave that aside for now). But if the string contains newlines, you can choose for ^
and $
to match at the start and end of any logical line, not just the start and end of the whole string, by setting the MULTILINE flag.
So forget about what MULTILINE
means and just remember what it does: changes the behavior of the ^
and $
anchors. DOTALL
mode was originally called "single-line" (and still is in some flavors, including Perl and .NET), and it has always caused similar confusion. We're fortunate that the Java devs went with the more descriptive name in that case, but there was no reasonable alternative for "multiline" mode.
In Perl, where all this madness started, they've admitted their mistake and gotten rid of both "multiline" and "single-line" modes in Perl 6 regexes. In another twenty years, maybe the rest of the world will have followed suit.
Go to your client machine and type in:
nslookup server.company.com
substituting the real host name of your server for server.company.com
, of course.
That should tell you which DNS server your client is using (if any) and what it thinks the problem is with the name.
To force an application to use an IP address, generally you just configure it to use the IP address instead of a host name. If the host name is hard-coded, or the application insists on using a host name in preference to an IP address (as one of your other comments seems to indicate), then you're probably out of luck there.
However, you can change the way that most machine resolve the host names, such as with /etc/resolv.conf
and /etc/hosts
on UNIXy systems and a local hosts file on Windows-y systems.
Since Google takes you to this post when searching for C# Web API Referrer
here's the deal: Web API
uses a different type of Request
from normal MVC Request
called HttpRequestMessage
which does not include UrlReferrer
. Since a normal Web API
request does not include this information, if you really need it, you must have your clients go out of their way to include it. Although you could make this be part of your API Object
, a better way is to use Headers
.
First, you can extend HttpRequestMessage
to provide a UrlReferrer()
method:
public static string UrlReferrer(this HttpRequestMessage request)
{
return request.Headers.Referrer == null ? "unknown" : request.Headers.Referrer.AbsoluteUri;
}
Then your clients need to set the Referrer Header
to their API Request
:
// Microsoft.AspNet.WebApi.Client
client.DefaultRequestHeaders.Referrer = new Uri(url);
And now the Web API Request
includes the referrer data which you can access like this from your Web API
:
Request.UrlReferrer();
We tried so many things, and in the end the issue was that the client had turned "Less Secure App Access" off in their Google Account settings.
To turn this on:
I hope this saves someone some time!
All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if
to bind them all together in the way I believe you intend.
With EL 2 (Expression Language 2) you can use this type of construct for your question:
#{formatBean.format(myBean.birthdate)}
Or you can add an alternate getter in your bean resulting in
#{myBean.birthdateString}
where getBirthdateString returns the proper text representation. Remember to annotate the get method as @Transient if it is an Entity.
Try this:
function generate_name ($length = LENGTH_IMG_PATH) {
$image_name = "";
$possible = "0123456789abcdefghijklmnopqrstuvwxyz";
$i = 0;
while ($i < $length) {
$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
if (!strstr($image_name, $char)) {
$image_name .= $char;
$i++;
}
}
return $image_name;
}
Here is one solution to clear all your application's activities when you use the logout button.
Every time you start an Activity, start it like this:
Intent myIntent = new Intent(getBaseContext(), YourNewActivity.class);
startActivityForResult(myIntent, 0);
When you want to close the entire app, do this:
setResult(RESULT_CLOSE_ALL);
finish();
RESULT_CLOSE_ALL is a final global variable with a unique integer to signal you want to close all activities.
Then define every activity's onActivityResult(...)
callback so when an activity returns with the RESULT_CLOSE_ALL value, it also calls finish()
:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(resultCode)
{
case RESULT_CLOSE_ALL:
setResult(RESULT_CLOSE_ALL);
finish();
}
super.onActivityResult(requestCode, resultCode, data);
}
This will cause a cascade effect that closes all your activities.
This is a hack however and uses startActivityForResult
in a way that it was not designed to be used.
Perhaps a better way to do this would be using broadcast receivers as shown here:
See these threads for other methods as well:
Seems like you can't iterate through JSONArray
with a for each
. You can loop through your JSONArray
like this:
for (int i=0; i < arr.length(); i++) {
arr.getJSONObject(i);
}
Edit the gradle wrapper settings in gradle/wrapper/gradle-wrapper.properties
and change gradle-1.6-bin.zip to gradle-2.4-bin.zip.
./gradle/wrapper/gradle-wrapper.properties :
#Wed Apr 10 15:27:10 PDT 2013
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=http\://services.gradle.org/distributions/gradle-1.8-bin.zip
It should compile without any error now.
Note: update version numbers with the most recent ones
The HTML attribute required="required"
is a statement telling the browser that this field is required in order for the form to be valid. (required="required"
is the XHTML form, just using required
is equivalent)
The Angular attribute ng-required="yourCondition"
means 'isRequired(yourCondition)' and sets the HTML attribute dynamically for you depending on your condition.
Also note that the HTML version is confusing, it is not possible to write something conditional like required="true"
or required="false"
, only the presence of the attribute matters (present means true) ! This is where Angular helps you out with ng-required
.
It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment
to your bean.
@Autowired
private Environment environment;
....
this.environment.getActiveProfiles();
In my opinion, a dynamic PL/SQL block is somewhat obscure. While is very flexible, is also hard to tune, hard to debug and hard to figure out what's up. My vote goes to your first option,
EXECUTE IMMEDIATE v_query_str INTO v_num_of_employees USING p_job;
Both uses bind variables, but first, for me, is more redeable and tuneable than @jonearles option.
I realize this is an old thread, but maybe someone will benefit from this. This command will find files in the current directory :
for F in $(find . -maxdepth 1 -type f -name "*_srv_logs_*.tar.gz" -printf '%T@ %p\n' | sort -r -z -n | tail -n+5 | awk '{ print $2; }'); do rm $F; done
This is a little more robust than some of the previous answers as it allows to limit your search domain to files matching expressions. First, find files matching whatever conditions you want. Print those files with the timestamps next to them.
find . -maxdepth 1 -type f -name "*_srv_logs_*.tar.gz" -printf '%T@ %p\n'
Next, sort them by the timestamps:
sort -r -z -n
Then, knock off the 4 most recent files from the list:
tail -n+5
Grab the 2nd column (the filename, not the timestamp):
awk '{ print $2; }'
And then wrap that whole thing up into a for statement:
for F in $(); do rm $F; done
This may be a more verbose command, but I had much better luck being able to target conditional files and execute more complex commands against them.
To supplement the other answers, document.myForm.foo is the so-called DOM level 0, which is the way implemented by Netscape and thus is not really an open standard even though it is supported by most browsers.
You can use method from Django Doc from this page https://docs.djangoproject.com/en/1.8/ref/models/fields/#default
Create default and use it
def contact_default():
return {"email": "[email protected]"}
contact_info = JSONField("ContactInfo", default=contact_default)
You'd need to be careful as onBlur
has some caveats in IE11 (How to use relatedTarget (or equivalent) in IE?, https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/relatedTarget).
There is, however, no way to use onFocusOut
in React as far as I can tell. See the issue on their github https://github.com/facebook/react/issues/6410 if you need more information.
I actually found something that worked for me. It converts the text to binary and then to UTF8.
Source Text that has encoding issues: If ‘Yes’, what was your last
SELECT CONVERT(CAST(CONVERT(
(SELECT CONVERT(CAST(CONVERT(english_text USING LATIN1) AS BINARY) USING UTF8) AS res FROM m_translation WHERE id = 865)
USING LATIN1) AS BINARY) USING UTF8) AS 'result';
Corrected Result text: If ‘Yes’, what was your last
My source was wrongly encoded twice so I had two do it twice. For one time you can use:
SELECT CONVERT(CAST(CONVERT(column_name USING latin1) AS BINARY) USING UTF8) AS res FROM m_translation WHERE id = 865;
Please excuse me for any formatting mistakes
What fixed the "Could not find schema information for the element ..." for me was
app.config
.Properties
.Schemas
, I clicked that row and selected the browse ...
box that appears in the row.use
box for all the rows that had my project somewhere in them, and also for the current version of .Net I was using. For instance: DotNetConfig30.xsd
.After that everything went to working fine.
How those schema rows with my project got unchecked I'm not sure, but when I made sure they were checked, I was back in business.
ComboBox with TextBox (For Pre-defined Values as well as User-defined Values.)
object["property"] = value;
or
object.property = value;
Object and Array in JavaScript are different in terms of usage. Its best if you understand them:
Yeah, it's typically because it starts out as 'where 1 = 0', to force the statement to fail.
It's a more naive way of wrapping it up in a transaction and not committing it at the end, to test your query. (This is the preferred method).
To simplify these answers, and increase performance when downloading a large file, the below may work a bit more efficiently.
import requests
from contextlib import closing
import csv
url = "http://download-and-process-csv-efficiently/python.csv"
with closing(requests.get(url, stream=True)) as r:
reader = csv.reader(r.iter_lines(), delimiter=',', quotechar='"')
for row in reader:
print row
By setting stream=True
in the GET request, when we pass r.iter_lines()
to csv.reader(), we are passing a generator to csv.reader(). By doing so, we enable csv.reader() to lazily iterate over each line in the response with for row in reader
.
This avoids loading the entire file into memory before we start processing it, drastically reducing memory overhead for large files.
Try this:
<video width="320" height="240" autoplay muted>
<source src="video.mp4" type="video/mp4">
</video>
$('input').focus(function () {
var self = $(this);
setTimeout(function () {
self.select();
}, 1);
});
Edit: Per @DavidG's request, I can't provide details because I'm not sure why this works, but I believe it has something to do with the focus event propagating up or down or whatever it does and the input element getting the notification it's received focus. Setting the timeout gives the element a moment to realize it's done so.
In class file you can either use:
module.exports = class ClassNameHere {
print() {
console.log('In print function');
}
}
or you can use this syntax
class ClassNameHere{
print(){
console.log('In print function');
}
}
module.exports = ClassNameHere;
On the other hand to use this class in any other file you need to do these steps.
First require that file using this syntax:
const anyVariableNameHere = require('filePathHere');
Then create an object
const classObject = new anyVariableNameHere();
After this you can use classObject
to access the actual class variables
Use CryptoJS
Here's the code: https://github.com/odedhb/AES-encrypt
And here's an online working example: https://odedhb.github.io/AES-encrypt/
use auto and min or max width like this:
td {
max-width:50px;
width:auto;
min-width:10px;
}
I use the first (running the code against a test database). The only substantive issue I see you raising with this approach is the possibilty of schemas getting out of sync, which I deal with by keeping a version number in my database and making all schema changes via a script which applies the changes for each version increment.
I also make all changes (including to the database schema) against my test environment first, so it ends up being the other way around: After all tests pass, apply the schema updates to the production host. I also keep a separate pair of testing vs. application databases on my development system so that I can verify there that the db upgrade works properly before touching the real production box(es).
First, attempt to pull from the same refspec that you are trying to push to.
If this does not work, you can force a git push
by using git push -f <repo> <refspec>
, but use caution: this method can cause references to be deleted on the remote repository.
In my case in the bin folder was a non reference dll called Unity.MVC3 , i tried to search any reference to this in visual studio without success, so my solution was so easy as delete that dll from the bin folder.
When the browser puts something in its cache, it also stores the Last-Modified
or ETag
header from the server.
The browser then sends a request with the If-Modified-Since
or If-None-Match
header, telling the server to send a 304 if the content still has that date or ETag.
The server needs some way of calculating a date-modified or ETag for each version of each resource; this typically comes from the filesystem or a separate database column.
You could change the compiler settings to accept Java 6 syntax but generate Java 5 output (as I remember). And set the "Generated class files compatibility" a bit lower if needed by your runtime. Update: I checked Eclipse, but it complains if I set source compatibility to 1.6 and class compatibility to 1.5. If 1.6 is not allowed I usually manually comment out the offending @Override annotations in the source (which doesn't help your case).
Update2: If you do only manual build, you could write a small program which copies the original project into a new one, strips @Override annotations from the java sources and you just hit Clean project in Eclipse.
This is what worked for me:
Enter the command:
osql -S localhost\SQLEXPRESS -E
(or change localhost to whatever your PC is called).
At the prompt type the following commands:
CREATE LOGIN my_Login_here WITH PASSWORD = 'my_Password_here'
go
sp_addsrvrolemember 'my_Login_here', 'sysadmin'
go
quit
Stop the "SQL Server (SQLEXPRESS)" service.
Remove the "-m" from the Start parameters field (if still there).
Start the service.
In Management Studio, use the login and password you just created. This should give it admin permission.
Get Month & Year From Date
DECLARE @lcMonth nvarchar(10)
DECLARE @lcYear nvarchar(10)
SET @lcYear=(SELECT DATEPART(YEAR,@Date))
SET @lcMonth=(SELECT DATEPART(MONTH,@Date))
Visit https://developers.google.com/mobile/add and try to fill "Android package name". In some cases it can write error: "Invalid Android package name".
In https://developer.android.com/studio/build/application-id.html it is written:
And although the application ID looks like a traditional Java package name, the naming rules for the application ID are a bit more restrictive:
- It must have at least two segments (one or more dots).
- Each segment must start with a letter.
- All characters must be alphanumeric or an underscore [a-zA-Z0-9_].
So, "0com.example.app" and "com.1example.app" are errors.
The exit
function is declared in the stdlib header, so you need to have
#include <stdlib.h>
at the top of your program to be able to use exit
.
Note also that exit
takes an integer argument, so you can't call it like exit()
, you have to call as exit(0)
or exit(42)
. 0 usually means your program completed successfully, and nonzero values are used as error codes.
There are also predefined macros EXIT_SUCCESS
and EXIT_FAILURE
, e.g. exit(EXIT_SUCCESS);
**check this out**
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).keypress(function(e)
{
var keynum;
if(window.event)
{ // IE
keynum = e.keyCode;
}
else if(e.which)
{
// Netscape/Firefox/Opera
keynum = e.which;
}
alert(String.fromCharCode(keynum));
var unicode=e.keyCode? e.keyCode : e.charCode;
alert(unicode);
});
});
</script>
</head>
<body>
<input type="text"></input>
</body>
</html>
HTML :
<div class="span4">
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body panel-height">fdoinfds sdofjohisdfj</div>
</div>
</div>
CSS :
.panel-height {
height: 100px; / change according to your requirement/
}