Swift 5 and ensures the image scales to the size of the button but stays within the buttons bounds.
yourButton.clipsToBounds = true
yourButton.contentMode = .scaleAspectFill
// Use setBackgroundImage or setImage
yourButton.setBackgroundImage(UIImage(named: "yourImage"), for: .normal)
Yes, you're right. With the css()
method you can retrieve the desired css value stored in the DOM. You can read more about this at: http://api.jquery.com/css/
But if you want to get its position you can check offset() and position() methods to get it's position.
git config --global core.editor "code --wait"
OR
git config --global core.editor "code -w"
Check
git config --global e
Your configuration will open in Visual Studio Code
You may be interested in this: An optimization anecdote by Guido. Although it is worth remembering also that this is an old article and it predates the existence of things like ''.join
(although I guess string.joinfields
is more-or-less the same)
On the strength of that, the array
module may be fastest if you can shoehorn your problem into it. But ''.join
is probably fast enough and has the benefit of being idiomatic and thus easier for other python programmers to understand.
Finally, the golden rule of optimization: don't optimize unless you know you need to, and measure rather than guessing.
You can measure different methods using the timeit
module. That can tell you which is fastest, instead of random strangers on the internet making guesses.
You can also use the following command:
echo toto; history -d $(history | sed -n '$s/\s*\([0-9]*\)\s*.*$/\1/p')
I think it's a very portable command.
If I move
CreateUser.py
to the main user_management directory, I can easily use:import Modules.LDAPManager
to importLDAPManager.py
--- this works.
Please, don't. In this way the LDAPManager
module used by CreateUser
will not be the same as the one imported via other imports. This can create problems when you have some global state in the module or during pickling/unpickling. Avoid imports that work only because the module happens to be in the same directory.
When you have a package structure you should either:
Use relative imports, i.e if the CreateUser.py
is in Scripts/
:
from ..Modules import LDAPManager
Note that this was (note the past tense) discouraged by PEP 8 only because old versions of python didn't support them very well, but this problem was solved years ago. The current version of PEP 8 does suggest them as an acceptable alternative to absolute imports. I actually like them inside packages.
Use absolute imports using the whole package name(CreateUser.py
in Scripts/
):
from user_management.Modules import LDAPManager
In order for the second one to work the package user_management
should be installed inside the PYTHONPATH
. During development you can configure the IDE so that this happens, without having to manually add calls to sys.path.append
anywhere.
Also I find it odd that Scripts/
is a subpackage. Because in a real installation the user_management
module would be installed under the site-packages
found in the lib/
directory (whichever directory is used to install libraries in your OS), while the scripts should be installed under a bin/
directory (whichever contains executables for your OS).
In fact I believe Script/
shouldn't even be under user_management
. It should be at the same level of user_management
.
In this way you do not have to use -m
, but you simply have to make sure the package can be found (this again is a matter of configuring the IDE, installing the package correctly or using PYTHONPATH=. python Scripts/CreateUser.py
to launch the scripts with the correct path).
In summary, the hierarchy I would use is:
user_management (package)
|
|------- __init__.py
|
|------- Modules/
| |
| |----- __init__.py
| |----- LDAPManager.py
| |----- PasswordManager.py
|
Scripts/ (*not* a package)
|
|----- CreateUser.py
|----- FindUser.py
Then the code of CreateUser.py
and FindUser.py
should use absolute imports to import the modules:
from user_management.Modules import LDAPManager
During installation you make sure that user_management
ends up somewhere in the PYTHONPATH
, and the scripts inside the directory for executables so that they are able to find the modules. During development you either rely on IDE configuration, or you launch CreateUser.py
adding the Scripts/
parent directory to the PYTHONPATH
(I mean the directory that contains both user_management
and Scripts
):
PYTHONPATH=/the/parent/directory python Scripts/CreateUser.py
Or you can modify the PYTHONPATH
globally so that you don't have to specify this each time. On unix OSes (linux, Mac OS X etc.) you can modify one of the shell scripts to define the PYTHONPATH
external variable, on Windows you have to change the environmental variables settings.
Addendum I believe, if you are using python2, it's better to make sure to avoid implicit relative imports by putting:
from __future__ import absolute_import
at the top of your modules. In this way import X
always means to import the toplevel module X
and will never try to import the X.py
file that's in the same directory (if that directory isn't in the PYTHONPATH
). In this way the only way to do a relative import is to use the explicit syntax (the from . import X
), which is better (explicit is better than implicit).
This will make sure you never happen to use the "bogus" implicit relative imports, since these would raise an ImportError
clearly signalling that something is wrong. Otherwise you could use a module that's not what you think it is.
Try clearing your .subversion
folder in your home directory and try to commit again. It should prompt you for your password and then ask you if you would like to save the password.
>>> test[:,0]
array([1, 3, 5])
Similarly,
>>> test[1,:]
array([3, 4])
lets you access rows. This is covered in Section 1.4 (Indexing) of the NumPy reference. This is quick, at least in my experience. It's certainly much quicker than accessing each element in a loop.
.erb-image-wrapper img{
max-width:100% !important;
height:auto;
display:block;
}
Worked for me.
Thanks for MrMisterMan for his assistance.
The getActionCommand() method returns an String associated with that Component set through the setActionCommand() , whereas the getSource() method returns an Object of the Object class specifying the source of the event.
No, but you could have something like:
bool b;
b = b.YourExtensionMethod();
size_t
is the unsigned integer type of the result of the sizeof operator (ISO C99 Section 7.17.)
The sizeof
operator yields the size (in bytes) of its operand, which may be an
expression or the parenthesized name of a type. The size is determined from the type of
the operand. The result is an integer. The value of the result is implementation-de?ned, and
its type (an unsigned integer type) is size_t
(ISO C99 Section 6.5.3.4.)
I know this is an old question but I found a way to get the fields by index.
You can do it by using the Object.keys
method.
When you call the Object.keys
method it returns the keys in the order they were assigned (See the example below). I tested the method below in the following browsers:
I also wrote a small extension to the object class so you can call the nth key of the object using getByIndex
.
// Function to get the nth key from the object_x000D_
Object.prototype.getByIndex = function(index) {_x000D_
return this[Object.keys(this)[index]];_x000D_
};_x000D_
_x000D_
var obj1 = {_x000D_
"set1": [1, 2, 3],_x000D_
"set2": [4, 5, 6, 7, 8],_x000D_
"set3": [9, 10, 11, 12]_x000D_
};_x000D_
_x000D_
var obj2 = {_x000D_
"set2": [4, 5, 6, 7, 8],_x000D_
"set1": [1, 2, 3],_x000D_
"set3": [9, 10, 11, 12]_x000D_
};_x000D_
_x000D_
log('-- Obj1 --');_x000D_
log(obj1);_x000D_
log(Object.keys(obj1));_x000D_
log(obj1.getByIndex(0));_x000D_
_x000D_
_x000D_
log('-- Obj2 --');_x000D_
log(obj2);_x000D_
log(Object.keys(obj2));_x000D_
log(obj2.getByIndex(0));_x000D_
_x000D_
_x000D_
// Log function to make the snippet possible_x000D_
function log(x) {_x000D_
var d = document.createElement("div");_x000D_
if (typeof x === "object") {_x000D_
x = JSON.stringify(x, null, 4);_x000D_
}_x000D_
d.textContent= x;_x000D_
document.body.appendChild(d);_x000D_
}
_x000D_
The pylab examples page is a very useful source. The example relevant for your question:
http://matplotlib.sourceforge.net/mpl_examples/pylab_examples/scatter_demo2.py http://matplotlib.sourceforge.net/users/screenshots.html#scatter-demo
For me in Ubuntu(18.08), I have added below line in .bashrc and it works.
source /home/username/.rvm/scripts/rvm
Please add this line.
Non-reflective solution for Java 8, without using a series of if's, would be to stream all fields and check for nullness:
return Stream.of(id, name).allMatch(Objects::isNull);
This remains quite easy to maintain while avoiding the reflection hammer. This will return true for null attributes.
Here a .NET C# similar implementation of a timespan class that supports days, hours, minutes and seconds. This implementation also supports negative timespans.
const MILLIS_PER_SECOND = 1000;
const MILLIS_PER_MINUTE = MILLIS_PER_SECOND * 60; // 60,000
const MILLIS_PER_HOUR = MILLIS_PER_MINUTE * 60; // 3,600,000
const MILLIS_PER_DAY = MILLIS_PER_HOUR * 24; // 86,400,000
export class TimeSpan {
private _millis: number;
private static interval(value: number, scale: number): TimeSpan {
if (Number.isNaN(value)) {
throw new Error("value can't be NaN");
}
const tmp = value * scale;
const millis = TimeSpan.round(tmp + (value >= 0 ? 0.5 : -0.5));
if ((millis > TimeSpan.maxValue.totalMilliseconds) || (millis < TimeSpan.minValue.totalMilliseconds)) {
throw new TimeSpanOverflowError("TimeSpanTooLong");
}
return new TimeSpan(millis);
}
private static round(n: number): number {
if (n < 0) {
return Math.ceil(n);
} else if (n > 0) {
return Math.floor(n);
}
return 0;
}
private static timeToMilliseconds(hour: number, minute: number, second: number): number {
const totalSeconds = (hour * 3600) + (minute * 60) + second;
if (totalSeconds > TimeSpan.maxValue.totalSeconds || totalSeconds < TimeSpan.minValue.totalSeconds) {
throw new TimeSpanOverflowError("TimeSpanTooLong");
}
return totalSeconds * MILLIS_PER_SECOND;
}
public static get zero(): TimeSpan {
return new TimeSpan(0);
}
public static get maxValue(): TimeSpan {
return new TimeSpan(Number.MAX_SAFE_INTEGER);
}
public static get minValue(): TimeSpan {
return new TimeSpan(Number.MIN_SAFE_INTEGER);
}
public static fromDays(value: number): TimeSpan {
return TimeSpan.interval(value, MILLIS_PER_DAY);
}
public static fromHours(value: number): TimeSpan {
return TimeSpan.interval(value, MILLIS_PER_HOUR);
}
public static fromMilliseconds(value: number): TimeSpan {
return TimeSpan.interval(value, 1);
}
public static fromMinutes(value: number): TimeSpan {
return TimeSpan.interval(value, MILLIS_PER_MINUTE);
}
public static fromSeconds(value: number): TimeSpan {
return TimeSpan.interval(value, MILLIS_PER_SECOND);
}
public static fromTime(hours: number, minutes: number, seconds: number): TimeSpan;
public static fromTime(days: number, hours: number, minutes: number, seconds: number, milliseconds: number): TimeSpan;
public static fromTime(daysOrHours: number, hoursOrMinutes: number, minutesOrSeconds: number, seconds?: number, milliseconds?: number): TimeSpan {
if (milliseconds != undefined) {
return this.fromTimeStartingFromDays(daysOrHours, hoursOrMinutes, minutesOrSeconds, seconds, milliseconds);
} else {
return this.fromTimeStartingFromHours(daysOrHours, hoursOrMinutes, minutesOrSeconds);
}
}
private static fromTimeStartingFromHours(hours: number, minutes: number, seconds: number): TimeSpan {
const millis = TimeSpan.timeToMilliseconds(hours, minutes, seconds);
return new TimeSpan(millis);
}
private static fromTimeStartingFromDays(days: number, hours: number, minutes: number, seconds: number, milliseconds: number): TimeSpan {
const totalMilliSeconds = (days * MILLIS_PER_DAY) +
(hours * MILLIS_PER_HOUR) +
(minutes * MILLIS_PER_MINUTE) +
(seconds * MILLIS_PER_SECOND) +
milliseconds;
if (totalMilliSeconds > TimeSpan.maxValue.totalMilliseconds || totalMilliSeconds < TimeSpan.minValue.totalMilliseconds) {
throw new TimeSpanOverflowError("TimeSpanTooLong");
}
return new TimeSpan(totalMilliSeconds);
}
constructor(millis: number) {
this._millis = millis;
}
public get days(): number {
return TimeSpan.round(this._millis / MILLIS_PER_DAY);
}
public get hours(): number {
return TimeSpan.round((this._millis / MILLIS_PER_HOUR) % 24);
}
public get minutes(): number {
return TimeSpan.round((this._millis / MILLIS_PER_MINUTE) % 60);
}
public get seconds(): number {
return TimeSpan.round((this._millis / MILLIS_PER_SECOND) % 60);
}
public get milliseconds(): number {
return TimeSpan.round(this._millis % 1000);
}
public get totalDays(): number {
return this._millis / MILLIS_PER_DAY;
}
public get totalHours(): number {
return this._millis / MILLIS_PER_HOUR;
}
public get totalMinutes(): number {
return this._millis / MILLIS_PER_MINUTE;
}
public get totalSeconds(): number {
return this._millis / MILLIS_PER_SECOND;
}
public get totalMilliseconds(): number {
return this._millis;
}
public add(ts: TimeSpan): TimeSpan {
const result = this._millis + ts.totalMilliseconds;
return new TimeSpan(result);
}
public subtract(ts: TimeSpan): TimeSpan {
const result = this._millis - ts.totalMilliseconds;
return new TimeSpan(result);
}
}
const ts = TimeSpan.zero;
From milliseconds
const milliseconds = 10000; // 1 second
// by using the constructor
const ts1 = new TimeSpan(milliseconds);
// or as an alternative you can use the static factory method
const ts2 = TimeSpan.fromMilliseconds(milliseconds);
From seconds
const seconds = 86400; // 1 day
const ts = TimeSpan.fromSeconds(seconds);
From minutes
const minutes = 1440; // 1 day
const ts = TimeSpan.fromMinutes(minutes);
From hours
const hours = 24; // 1 day
const ts = TimeSpan.fromHours(hours);
From days
const days = 1; // 1 day
const ts = TimeSpan.fromDays(days);
From time with given hours, minutes and seconds
const hours = 1;
const minutes = 1;
const seconds = 1;
const ts = TimeSpan.fromTime(hours, minutes, seconds);
From time2 with given days, hours, minutes, seconds and milliseconds
const days = 1;
const hours = 1;
const minutes = 1;
const seconds = 1;
const milliseconds = 1;
const ts = TimeSpan.fromTime(days, hours, minutes, seconds, milliseconds);
From maximal safe integer
const ts = TimeSpan.maxValue;
From minimal safe integer
const ts = TimeSpan.minValue;
From minimal safe integer
const ts = TimeSpan.minValue;
Add
const ts1 = TimeSpan.fromDays(1);
const ts2 = TimeSpan.fromHours(1);
const ts = ts1.add(ts2);
console.log(ts.days); // 1
console.log(ts.hours); // 1
console.log(ts.minutes); // 0
console.log(ts.seconds); // 0
console.log(ts.milliseconds); // 0
Subtract
const ts1 = TimeSpan.fromDays(1);
const ts2 = TimeSpan.fromHours(1);
const ts = ts1.subtract(ts2);
console.log(ts.days); // 0
console.log(ts.hours); // 23
console.log(ts.minutes); // 0
console.log(ts.seconds); // 0
console.log(ts.milliseconds); // 0
Getting the intervals
const days = 1;
const hours = 1;
const minutes = 1;
const seconds = 1;
const milliseconds = 1;
const ts = TimeSpan.fromTime2(days, hours, minutes, seconds, milliseconds);
console.log(ts.days); // 1
console.log(ts.hours); // 1
console.log(ts.minutes); // 1
console.log(ts.seconds); // 1
console.log(ts.milliseconds); // 1
console.log(ts.totalDays) // 1.0423726967592593;
console.log(ts.totalHours) // 25.016944722222224;
console.log(ts.totalMinutes) // 1501.0166833333333;
console.log(ts.totalSeconds) // 90061.001;
console.log(ts.totalMilliseconds); // 90061001;
See also here: https://github.com/erdas/timespan
If you don't need a signed integer, this is an alternative that uses a slightly different approach, is easy to read and doesn't require an import:
def distance(a, b):
if a > 0 and b > 0:
return max(a, b) - min(a, b)
elif a < 0 and b < 0:
return abs(a - b)
elif a == b:
return 0
return abs(a - 0) + abs(b - 0)
To provide another approach similar to the answer by @IvanCollantes.
It works by additionally filtering the required checkboxes by name. I also simplified the code a bit and checks for a default checked
checkbox.
jQuery(function($) {_x000D_
var requiredCheckboxes = $(':checkbox[required]');_x000D_
requiredCheckboxes.on('change', function(e) {_x000D_
var checkboxGroup = requiredCheckboxes.filter('[name="' + $(this).attr('name') + '"]');_x000D_
var isChecked = checkboxGroup.is(':checked');_x000D_
checkboxGroup.prop('required', !isChecked);_x000D_
});_x000D_
requiredCheckboxes.trigger('change');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<form target="_blank">_x000D_
<p>_x000D_
At least one checkbox from each group is required..._x000D_
</p>_x000D_
<fieldset>_x000D_
<legend>Checkboxes Group test</legend>_x000D_
<label>_x000D_
<input type="checkbox" name="test[]" value="1" checked="checked" required="required">test-1_x000D_
</label>_x000D_
<label>_x000D_
<input type="checkbox" name="test[]" value="2" required="required">test-2_x000D_
</label>_x000D_
<label>_x000D_
<input type="checkbox" name="test[]" value="3" required="required">test-3_x000D_
</label>_x000D_
</fieldset>_x000D_
<br>_x000D_
<fieldset>_x000D_
<legend>Checkboxes Group test2</legend>_x000D_
<label>_x000D_
<input type="checkbox" name="test2[]" value="1" required="required">test2-1_x000D_
</label>_x000D_
<label>_x000D_
<input type="checkbox" name="test2[]" value="2" required="required">test2-2_x000D_
</label>_x000D_
<label>_x000D_
<input type="checkbox" name="test2[]" value="3" required="required">test2-3_x000D_
</label>_x000D_
</fieldset>_x000D_
<hr>_x000D_
<button type="submit" value="submit">Submit</button>_x000D_
</form>
_x000D_
Try this:
window.open(url, '_blank');
This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)
@Html.TextBoxFor(x => x.MobileNo, new { @class = "digit" , @maxlength = "10"})
@section Scripts
{
@Scripts.Render("~/bundles/jqueryui")
@Styles.Render("~/Content/cssjqryUi")
<script type="text/javascript">
$(".digit").keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57))
{
$("#errormsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
</script>
}
Here is how I do this.
Dim TAV() As Variant
Dim ArrayToPreserve() as Variant
TAV = ArrayToPreserve
ReDim ArrayToPreserve(nDim1, nDim2)
For i = 0 To UBound(TAV, 1)
For j = 0 To UBound(TAV, 2)
ArrayToPreserve(i, j) = TAV(i, j)
Next j
Next i
I think what you're trying to do should be done with multiple Activities. If you're learning Android, understanding Activities is something you're going to have to tackle. Trying to write a whole app with just one Activity will end up being a lot more difficult. Read this article to get yourself started, then you should end up with something more like this:
View.OnClickListener handler = new View.OnClickListener(){
public void onClick(View v) {
switch (v.getId()) {
case R.id.DownloadView:
// doStuff
startActivity(new Intent(ThisActivity.this, DownloadActivity.class));
break;
case R.id.AppView:
// doStuff
startActivity(new Intent(ThisActivity.this, AppActivity.class));
break;
}
}
};
findViewById(R.id.DownloadView).setOnClickListener(handler);
findViewById(R.id.AppView).setOnClickListener(handler);
From Microsoft MSDN recommendations:
Application icons and Control Panel items: The full set includes 16x16, 32x32, 48x48, and 256x256 (code scales between 32 and 256). The .ico file format is required. For Classic Mode, the full set is 16x16, 24x24, 32x32, 48x48 and 64x64.
So we have already standard recommended sizes of:
If we would like to support high DPI settings, the complete list will include the following sizes as well:
Specifying a flex attribute to the container worked for me:
.container {
flex: 0 0 auto;
}
This ensures the height is set and doesn't grow either.
Fully async version with ES6, only native packages, fs.promises and async/await, does file operations in parallel:
const fs = require('fs');
const path = require('path');
async function listDirectories(rootPath) {
const fileNames = await fs.promises.readdir(rootPath);
const filePaths = fileNames.map(fileName => path.join(rootPath, fileName));
const filePathsAndIsDirectoryFlagsPromises = filePaths.map(async filePath => ({path: filePath, isDirectory: (await fs.promises.stat(filePath)).isDirectory()}))
const filePathsAndIsDirectoryFlags = await Promise.all(filePathsAndIsDirectoryFlagsPromises);
return filePathsAndIsDirectoryFlags.filter(filePathAndIsDirectoryFlag => filePathAndIsDirectoryFlag.isDirectory)
.map(filePathAndIsDirectoryFlag => filePathAndIsDirectoryFlag.path);
}
Tested, it works nicely.
I had the same error on my Angular6 project. none of those solutions seemed to work out for me. turned out that the problem was due to an element which was specified as dropdown
but it didn't have dropdown options in it. take a look at code below:
<span class="nav-link" id="navbarDropdownMenuLink" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
<i class="material-icons "
style="font-size: 2rem">notifications</i>
<span class="notification"></span>
<p>
<span class="d-lg-none d-md-block">Some Actions</span>
</p>
</span>
<div class="dropdown-menu dropdown-menu-left"
*ngIf="global.localStorageItem('isInSadHich')"
aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="#">You have 5 new tasks</a>
<a class="dropdown-item" href="#">You're now friend with Andrew</a>
<a class="dropdown-item" href="#">Another Notification</a>
<a class="dropdown-item" href="#">Another One</a>
</div>
removing the code data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"
solved the problem.
I myself think that by each click on the first span element, the scope expected to set style for dropdown children which did not existed in the parent span, so it threw error.
The following are possible issues:
The most likely one is that the Security Group is not configured properly to provide SSH access on port 22 to your i.p. Change in security setting does not require a restart of server for it to be effective but need to wait a few minutes for it to be applicable.
The local firewall configuration does not allow SSH access to the server. ( you can try a different internet connection, your phone/dongle to try it)
The server is not started properly ( then the access checks will fail even on the amazon console), in which case you would need to stop and start the server.
Try the following:
grep -v -e '^$' foo.txt
The -e
option allows regex patterns for matching.
The single quotes around ^$
makes it work for Cshell. Other shells will be happy with either single or double quotes.
UPDATE: This works for me for a file with blank lines or "all white space" (such as windows lines with "\r\n" style line endings), whereas the above only removes files with blank lines and unix style line endings:
grep -v -e '^[[:space:]]*$' foo.txt
The current version of Mongoose (v4.x) has time stamping as a built-in option to a schema:
var mySchema = new mongoose.Schema( {name: String}, {timestamps: true} );
This option adds createdAt
and updatedAt
properties that are timestamped with a Date
, and which does all the work for you. Any time you update the document, it updates the updatedAt
property. Schema Timestamps Docs.
Simply do this, with genymotion device running you can open Virtual Box , and see that there is a VM for you device , then go to network Settings of the VM, NAT and do port forwarding of local 5555 to remote 5555 screen attachedVirtual Box Nat Network Port forwarding
.gitignore
to match the file you want to ignoregit rm --cached /path/to/file
See also:
Use next
:
(1..10).each do |a|
next if a.even?
puts a
end
prints:
1
3
5
7
9
For additional coolness check out also redo
and retry
.
Works also for friends like times
, upto
, downto
, each_with_index
, select
, map
and other iterators (and more generally blocks).
For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.
Use following code:
NSDate *now = [NSDate date];
int daysToAdd = 1;
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*daysToAdd];
As
addTimeInterval
is now deprecated.
schtasks /change /disable /tn "Name Of Task" /s REMOTEMACHINENAME /u mydomain\administrator /p adminpassword
Took some searching and reading to find a method that suited my situation, on form submit, run ajax to a remote php script, on success/failure inform user, on complete clear the form.
I had some default values, all other methods involved .val('') thereby not resetting but clearing the form.
I got this too work by adding a reset button to the form, which had an id of myform
:
$("#myform > input[type=reset]").trigger('click');
This for me had the correct outcome on resetting the form, oh and dont forget the
event.preventDefault();
to stop the form submitting in browser, like I did :).
Regards
Jacko
I have tried this kind of technique. Multiply the subtract from data by (-1) and then sum() the both amount then you will get subtracted amount.
-- Loan Outstanding
select 'Loan Outstanding' as Particular, sum(Unit), sum(UptoLastYear), sum(ThisYear), sum(UptoThisYear)
from
(
select
sum(laod.dr) as Unit,
sum(if(lao.created_at <= '2014-01-01',laod.dr,0)) as UptoLastYear,
sum(if(lao.created_at between '2014-01-01' and '2015-07-14',laod.dr,0)) as ThisYear,
sum(if(lao.created_at <= '2015-07-14',laod.dr,0)) as UptoThisYear
from loan_account_opening as lao
inner join loan_account_opening_detail as laod on lao.id=laod.loan_account_opening_id
where lao.organization = 3
union
select
sum(lr.installment)*-1 as Unit,
sum(if(lr.created_at <= '2014-01-01',lr.installment,0))*-1 as UptoLastYear,
sum(if(lr.created_at between '2014-01-01' and '2015-07-14',lr.installment,0))*-1 as ThisYear,
sum(if(lr.created_at <= '2015-07-14',lr.installment,0))*-1 as UptoThisYear
from loan_recovery as lr
inner join loan_account_opening as lo on lr.loan_account_opening_id=lo.id
where lo.organization = 3
) as t3
I had the same issue. The problem was because 'ng-controller' was defined twice (in routing and also in the HTML).
fs.exists() is deprecated dont use it https://nodejs.org/api/fs.html#fs_fs_exists_path_callback
You could implement the core nodejs way used at this: https://github.com/nodejs/node-v0.x-archive/blob/master/lib/module.js#L86
function statPath(path) {
try {
return fs.statSync(path);
} catch (ex) {}
return false;
}
this will return the stats object then once you've got the stats object you could try
var exist = statPath('/path/to/your/file.js');
if(exist && exist.isFile()) {
// do something
}
Try this:
onclick="myfunction(
'/myController/myAction',
function(){myfuncionOnOK('/myController2/myAction2','myParameter2');},
function(){myfuncionOnCancel('/myController3/myAction3','myParameter3');}
);"
Then you just need to call these two functions passed to myfunction
:
function myfunction(url, f1, f2) {
// …
f1();
f2();
}
First I am afraid your question contains a little mistake. There is not method writeline in class Console. Instead class Console provides method writer() that returns PrintWriter. This print writer has println().
Now what is the difference between
System.console().writer().println("hello from console");
and
System.out.println("hello system out");
If you run your application from command line I think there is no difference. But if console is unavailable System.console() returns null while System.out still exists. This may happen if you invoke your application and perform redirect of STDOUT to file.
Here is an example I have just implemented.
import java.io.Console;
public class TestConsole {
public static void main(String[] args) {
Console console = System.console();
System.out.println("console=" + console);
console.writer().println("hello from console");
}
}
When I ran the application from command prompt I got the following:
$ java TestConsole
console=java.io.Console@93dcd
hello from console
but when I redirected the STDOUT to file...
$ java TestConsole >/tmp/test
Exception in thread "main" java.lang.NullPointerException
at TestConsole.main(TestConsole.java:8)
Line 8 is console.writer().println()
.
Here is the content of /tmp/test
console=null
I hope my explanations help.
With filetype indent on
inside my .vimrc
, Vim indents HTML files quite nicely.
Simple example with a shiftwidth
of 2:
<html>
<body>
<p>
text
</p>
</body>
</html>
All the answers posted do not apply today. For example, getDrawable() is deprecated. Here is an updated answer, cheers!
ContextCompat.getDrawable(mContext, drawable)
From documented method
public static final android.graphics.drawable.Drawable getDrawable(@NotNull android.content.Context context,
@android.support.annotation.DrawableRes int id
Instead of using Ajax Post method, you can use dynamic form along with element. It will works even page is loaded in SSL and submitted source is non SSL.
You need to set value value of element of form.
Actually new dynamic form will open as non SSL mode in separate tab of Browser when target attribute has set '_blank'
var f = document.createElement('form');
f.action='http://XX.XXX.XX.XX/vicidial/non_agent_api.php';
f.method='POST';
//f.target='_blank';
//f.enctype="multipart/form-data"
var k=document.createElement('input');
k.type='hidden';k.name='CustomerID';
k.value='7299';
f.appendChild(k);
//var z=document.getElementById("FileNameId")
//z.setAttribute("name", "IDProof");
//z.setAttribute("id", "IDProof");
//f.appendChild(z);
document.body.appendChild(f);
f.submit()
You don't need to encode data that is already encoded. When you try to do that, Python will first try to decode it to unicode
before it can encode it back to UTF-8. That is what is failing here:
>>> data = u'\u00c3' # Unicode data
>>> data = data.encode('utf8') # encoded to UTF-8
>>> data
'\xc3\x83'
>>> data.encode('utf8') # Try to *re*-encode it
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
Just write your data directly to the file, there is no need to encode already-encoded data.
If you instead build up unicode
values instead, you would indeed have to encode those to be writable to a file. You'd want to use codecs.open()
instead, which returns a file object that will encode unicode values to UTF-8 for you.
You also really don't want to write out the UTF-8 BOM, unless you have to support Microsoft tools that cannot read UTF-8 otherwise (such as MS Notepad).
For your MySQL insert problem, you need to do two things:
Add charset='utf8'
to your MySQLdb.connect()
call.
Use unicode
objects, not str
objects when querying or inserting, but use sql parameters so the MySQL connector can do the right thing for you:
artiste = artiste.decode('utf8') # it is already UTF8, decode to unicode
c.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s', (artiste,))
# ...
c.execute('INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)', (artiste, artiste + u'/'))
It may actually work better if you used codecs.open()
to decode the contents automatically instead:
import codecs
sql = mdb.connect('localhost','admin','ugo&(-@F','music_vibration', charset='utf8')
with codecs.open('config/index/'+index, 'r', 'utf8') as findex:
for line in findex:
if u'#artiste' not in line:
continue
artiste=line.split(u'[:::]')[1].strip()
cursor = sql.cursor()
cursor.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s', (artiste,))
if not cursor.fetchone()[0]:
cursor = sql.cursor()
cursor.execute('INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)', (artiste, artiste + u'/'))
artists_inserted += 1
You may want to brush up on Unicode and UTF-8 and encodings. I can recommend the following articles:
The answer to many CSS formatting problems seems to be "add another <div>!"
So, in that spirit, have you tried adding a wrapper div to which the border/padding are applied and then putting the 100% width textarea inside of that? Something like (untested):
textarea_x000D_
{_x000D_
width:100%;_x000D_
}_x000D_
.textwrapper_x000D_
{_x000D_
border:1px solid #999999;_x000D_
margin:5px 0;_x000D_
padding:3px;_x000D_
}
_x000D_
<div style="display: block;" id="rulesformitem" class="formitem">_x000D_
<label for="rules" id="ruleslabel">Rules:</label>_x000D_
<div class="textwrapper"><textarea cols="2" rows="10" id="rules"/></div>_x000D_
</div>
_x000D_
The ALTER TABLE
MySQL command should do the trick. The following command will change the default character set of your table and the character set of all its columns to UTF8.
ALTER TABLE etape_prospection CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
This command will convert all text-like columns in the table to the new character set. Character sets use different amounts of data per character, so MySQL will convert the type of some columns to ensure there's enough room to fit the same number of characters as the old column type.
I recommend you read the ALTER TABLE MySQL documentation before modifying any live data.
In this case, you may want to check if element exists in current DOM
if you want to check if element exist in DOM tree (is attached to DOM), you can use:
var data = $('#data_1');
if(jQuery.contains(document.documentElement, data[0])){
// #data_1 element attached to DOM
} else {
// is not attached to DOM
}
You could use LINQ:
var checkedButton = container.Controls.OfType<RadioButton>()
.FirstOrDefault(r => r.Checked);
Note that this requires that all of the radio buttons be directly in the same container (eg, Panel or Form), and that there is only one group in the container. If that is not the case, you could make List<RadioButton>
s in your constructor for each group, then write list.FirstOrDefault(r => r.Checked)
.
Check jQuery.ScrollTo, I think that's the behavior that you want, check the demo.
Simpliest way for my opinion
var web = new WebClient();
var url = $"{hostname}/LoadDataSync?systemID={systemId}";
var responseString = web.DownloadString(url);
OR
var bytes = web.DownloadData(url);
You can do a subquery where you first get the IDs of the top 10 ordered by priority and then update the ones that are on that sub query:
UPDATE messages
SET status=10
WHERE ID in (SELECT TOP (10) Id
FROM Table
WHERE status=0
ORDER BY priority DESC);
J.Random Coder's answer and initialize version field.
private string version = "10.4';
The answer comes from the javadoc of ZoneId
(emphasis mine) ...
A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:
- Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
- Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply
Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.
... and from the javadoc of ZoneId#of
(emphasis mine):
This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.
The argument id is specified as "UTC"
, therefore it will return a ZoneId
with an offset, which also presented in the string form:
System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));
Outputs:
2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]
As you use the equals
method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false
.
When the normalized()
method is used as proposed in the documentation, the comparison using equals
will return true
, as normalized()
will return the corresponding ZoneOffset
:
Normalizes the time-zone ID, returning a ZoneOffset where possible.
now.withZoneSameInstant(ZoneOffset.UTC)
.equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true
As the documentation states, if you use "Z"
or "+0"
as input id, of
will return the ZoneOffset
directly and there is no need to call normalized()
:
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true
To check if they store the same date time, you can use the isEqual
method instead:
now.withZoneSameInstant(ZoneOffset.UTC)
.isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true
Sample
System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
.isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));
Output:
equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true
If you have a single Buffer
you can use its toString
method that will convert all or part of the binary contents to a string using a specific encoding. It defaults to utf8
if you don't provide a parameter, but I've explicitly set the encoding in this example.
var req = http.request(reqOptions, function(res) {
...
res.on('data', function(chunk) {
var textChunk = chunk.toString('utf8');
// process utf8 text chunk
});
});
If you have streamed buffers like in the question above where the first byte of a multi-byte UTF8
-character may be contained in the first Buffer
(chunk) and the second byte in the second Buffer
then you should use a StringDecoder
. :
var StringDecoder = require('string_decoder').StringDecoder;
var req = http.request(reqOptions, function(res) {
...
var decoder = new StringDecoder('utf8');
res.on('data', function(chunk) {
var textChunk = decoder.write(chunk);
// process utf8 text chunk
});
});
This way bytes of incomplete characters are buffered by the StringDecoder
until all required bytes were written to the decoder.
The snippet you're showing doesn't seem to be directly responsible for the error.
This is how you can CAUSE the error:
namespace MyNameSpace
{
int i; <-- THIS NEEDS TO BE INSIDE THE CLASS
class MyClass
{
...
}
}
If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }
.
Add in the generated migration after creating the column the following (example)
add_index :photographers, :email, :unique => true
.image_block {
width: 175px;
height: 175px;
position: relative;
}
.image_block a {
width: 100%;
text-align: center;
position: absolute;
bottom: 0px;
}
.image_block img {
/* nothing specific */
}
explanation: an element positioned absolutely will be relative to the closest parent which has a non-static positioning. i'm assuming you're happy with how your .image_block
displays, so we can leave the relative positioning there.
as such, the <a>
element will be positioned relative to the .image_block
, which will give us the bottom alignment. then, we text-align: center
the <a>
element, and give it a 100% width so that it is the size of .image_block
.
the <img>
within <a>
will then center appropriately.
If you are working on your own, and you want the closest thing to OOP as you would find in Java or C# or C++, see the javascript library, CrxOop. CrxOop provides syntax somewhat familiar to Java developers.
Just be careful, Java's OOP is not the same as that found in Javascript. To get the same behavior as in Java, use CrxOop's classes, not CrxOop's structures, and make sure all your methods are virtual. An example of the syntax is,
crx_registerClass("ExampleClass",
{
"VERBOSE": 1,
"public var publicVar": 5,
"private var privateVar": 7,
"public virtual function publicVirtualFunction": function(x)
{
this.publicVar1 = x;
console.log("publicVirtualFunction");
},
"private virtual function privatePureVirtualFunction": 0,
"protected virtual final function protectedVirtualFinalFunction": function()
{
console.log("protectedVirtualFinalFunction");
}
});
crx_registerClass("ExampleSubClass",
{
VERBOSE: 1,
EXTENDS: "ExampleClass",
"public var publicVar": 2,
"private virtual function privatePureVirtualFunction": function(x)
{
this.PARENT.CONSTRUCT(pA);
console.log("ExampleSubClass::privatePureVirtualFunction");
}
});
var gExampleSubClass = crx_new("ExampleSubClass", 4);
console.log(gExampleSubClass.publicVar);
console.log(gExampleSubClass.CAST("ExampleClass").publicVar);
The code is pure javascript, no transpiling. The example is taken from a number of examples from the official documentation.
Do not use Mockito.anyXXXX(). Directly pass the value to the method parameter of same type. Example:
A expected = new A(10);
String firstId = "10w";
String secondId = "20s";
String product = "Test";
String type = "type2";
Mockito.when(service.getTestData(firstId, secondId, product,type)).thenReturn(expected);
public class A{
int a ;
public A(int a) {
this.a = a;
}
}
To print stacktrace of Error
in console in more readable way:
console.log(ex, ex.stack.split("\n"));
Example result:
[Error] [ 'Error',
' at repl:1:7',
' at REPLServer.self.eval (repl.js:110:21)',
' at Interface.<anonymous> (repl.js:239:12)',
' at Interface.EventEmitter.emit (events.js:95:17)',
' at Interface._onLine (readline.js:202:10)',
' at Interface._line (readline.js:531:8)',
' at Interface._ttyWrite (readline.js:760:14)',
' at ReadStream.onkeypress (readline.js:99:10)',
' at ReadStream.EventEmitter.emit (events.js:98:17)',
' at emitKey (readline.js:1095:12)' ]
Typically this is the directory where your app (java) was started (working dir). "Typically" because it can be changed, eg when you run an app with Runtime.exec(String[] cmdarray, String[] envp, File dir)
/html/body/table/tbody/tr[9]/td[1]
In Chrome (possible Safari too) you can inspect an element, then right click on the tag you want to get the xpath for, then you can copy the xpath to select that element.
Add a reference to Microsoft.VisualBasic
and a using Microsoft.VisualBasic.Devices;
.
The ComputerInfo
class has all the information that you need.
In the documentation http://www.apachefriends.org/en/xampp-windows.html (Configuration files section, near the bottom of the page): \xampp\php\php.ini
All you need to do is make an array of fields and then set it to the class you want like shown below.
Field fld[] = (class name).class.getDeclaredFields();
for(Field x : fld)
{System.out.println(x);}
For example if you did
Field fld[] = Integer.class.getDeclaredFields();
for(Field x : fld)
{System.out.println(x);}
you would get
public static final int java.lang.Integer.MIN_VALUE
public static final int java.lang.Integer.MAX_VALUE
public static final java.lang.Class java.lang.Integer.TYPE
static final char[] java.lang.Integer.digits
static final char[] java.lang.Integer.DigitTens
static final char[] java.lang.Integer.DigitOnes
static final int[] java.lang.Integer.sizeTable
private static java.lang.String java.lang.Integer.integerCacheHighPropValue
private final int java.lang.Integer.value
public static final int java.lang.Integer.SIZE
private static final long java.lang.Integer.serialVersionUID
onMeasure()
is your opportunity to tell Android how big you want your custom view to be dependent the layout constraints provided by the parent; it is also your custom view's opportunity to learn what those layout constraints are (in case you want to behave differently in a match_parent
situation than a wrap_content
situation). These constraints are packaged up into the MeasureSpec
values that are passed into the method. Here is a rough correlation of the mode values:
layout_width
or layout_height
value was set to a specific value. You should probably make your view this size. This can also get triggered when match_parent
is used, to set the size exactly to the parent view (this is layout dependent in the framework).layout_width
or layout_height
value was set to match_parent
or wrap_content
where a maximum size is needed (this is layout dependent in the framework), and the size of the parent dimension is the value. You should not be any larger than this size.layout_width
or layout_height
value was set to wrap_content
with no restrictions. You can be whatever size you would like. Some layouts also use this callback to figure out your desired size before determine what specs to actually pass you again in a second measure request.The contract that exists with onMeasure()
is that setMeasuredDimension()
MUST be called at the end with the size you would like the view to be. This method is called by all the framework implementations, including the default implementation found in View
, which is why it is safe to call super
instead if that fits your use case.
Granted, because the framework does apply a default implementation, it may not be necessary for you to override this method, but you may see clipping in cases where the view space is smaller than your content if you do not, and if you lay out your custom view with wrap_content
in both directions, your view may not show up at all because the framework doesn't know how large it is!
Generally, if you are overriding View
and not another existing widget, it is probably a good idea to provide an implementation, even if it is as simple as something like this:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int desiredWidth = 100;
int desiredHeight = 100;
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width;
int height;
//Measure Width
if (widthMode == MeasureSpec.EXACTLY) {
//Must be this size
width = widthSize;
} else if (widthMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
width = Math.min(desiredWidth, widthSize);
} else {
//Be whatever you want
width = desiredWidth;
}
//Measure Height
if (heightMode == MeasureSpec.EXACTLY) {
//Must be this size
height = heightSize;
} else if (heightMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
height = Math.min(desiredHeight, heightSize);
} else {
//Be whatever you want
height = desiredHeight;
}
//MUST CALL THIS
setMeasuredDimension(width, height);
}
Hope that Helps.
Using Following Code You Solve thisQuestion.... If you run a file using localhost server than this problem solve by following Jsp Page Code.This Code put Between Head Tag in jsp file
<style type="text/css">
<%@include file="css/style.css" %>
</style>
<script type="text/javascript">
<%@include file="js/script.js" %>
</script>
Wow, after few attempts I finally figured out how to deal with my text edits in vbs. The code works perfectly, it gives me the result I was expecting. Maybe it's not the best way to do this, but it does its job. Here's the code:
Option Explicit
Dim StdIn: Set StdIn = WScript.StdIn
Dim StdOut: Set StdOut = WScript
Main()
Sub Main()
Dim objFSO, filepath, objInputFile, tmpStr, ForWriting, ForReading, count, text, objOutputFile, index, TSGlobalPath, foundFirstMatch
Set objFSO = CreateObject("Scripting.FileSystemObject")
TSGlobalPath = "C:\VBS\TestSuiteGlobal\Test suite Dispatch Decimal - Global.txt"
ForReading = 1
ForWriting = 2
Set objInputFile = objFSO.OpenTextFile(TSGlobalPath, ForReading, False)
count = 7
text=""
foundFirstMatch = false
Do until objInputFile.AtEndOfStream
tmpStr = objInputFile.ReadLine
If foundStrMatch(tmpStr)=true Then
If foundFirstMatch = false Then
index = getIndex(tmpStr)
foundFirstMatch = true
text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
End If
If index = getIndex(tmpStr) Then
text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
ElseIf index < getIndex(tmpStr) Then
index = getIndex(tmpStr)
text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
End If
Else
text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
End If
Loop
Set objOutputFile = objFSO.CreateTextFile("C:\VBS\NuovaProva.txt", ForWriting, true)
objOutputFile.Write(text)
End Sub
Function textSubstitution(tmpStr,index,foundMatch)
Dim strToAdd
strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_CF5.0_Features_TC" & CStr(index) & "</a></td></tr>"
If foundMatch = "false" Then
textSubstitution = tmpStr
ElseIf foundMatch = "true" Then
textSubstitution = strToAdd & vbCrLf & tmpStr
End If
End Function
Function getIndex(tmpStr)
Dim substrToFind, charAtPos, char1, char2
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
charAtPos = len(substrToFind) + 1
char1 = Mid(tmpStr, charAtPos, 1)
char2 = Mid(tmpStr, charAtPos+1, 1)
If IsNumeric(char2) Then
getIndex = CInt(char1 & char2)
Else
getIndex = CInt(char1)
End If
End Function
Function foundStrMatch(tmpStr)
Dim substrToFind
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
If InStr(tmpStr, substrToFind) > 0 Then
foundStrMatch = true
Else
foundStrMatch = false
End If
End Function
This is the original txt file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>
And this is the result I'm expecting
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC5.html">Beginning_of_CF5.0_Features_TC5</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC6.html">Beginning_of_CF5.0_Features_TC6</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC7.html">Beginning_of_CF5.0_Features_TC7</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>
Before you call setContentView()
, call setTheme(android.R.style...)
and just replace the ... with the theme that you want(Theme, Theme_NoTitleBar, etc.).
Or if your theme is a custom theme, then replace the entire thing, so you get setTheme(yourThemesResouceId)
Coordinating access to a single file at the OS level is fraught with all kinds of issues that you probably don't want to solve.
Your best bet is have a separate process that coordinates read/write access to that file.
I'm assuming that you wish to write software to do this. To do it naively you would just find lines and set the vectors. To do it intelligently, you attempt to fit shapes onto the drawing (model fitting). Additionally, you should attempt to ascertain bitmaped regions (regions you can't model through shames or applying textures. I would not recommend going this route as that it will take quite a bit of time and require a bit of graphics and computer vision knowledge. However, the output will much and scale much better than your original output.
There's already a question about this, you could perhaps read it
There's no Clone() method as it exists in Java for example, but you could include a copy constructor in your clases, that's another good approach.
class A
{
private int attr
public int Attr
{
get { return attr; }
set { attr = value }
}
public A()
{
}
public A(A p)
{
this.attr = p.Attr;
}
}
This would be an example, copying the member 'Attr' when building the new object.
Here's a bit of code that should pick a valid IP by checking through various sources.
First, it checks if 'REMOTE_ADDR' is a public IP or not (and not one of your trusted reverse proxies), then goes through one of the HTTP headers until it finds a public IP and returns it. (PHP 5.2+)
It should be reliable as long as the reverse proxy is trusted or the server is directly connected with the client.
//Get client's IP or null if nothing looks valid
function ip_get($allow_private = false)
{
//Place your trusted proxy server IPs here.
$proxy_ip = ['127.0.0.1'];
//The header to look for (Make sure to pick the one that your trusted reverse proxy is sending or else you can get spoofed)
$header = 'HTTP_X_FORWARDED_FOR'; //HTTP_CLIENT_IP, HTTP_X_FORWARDED, HTTP_FORWARDED_FOR, HTTP_FORWARDED
//If 'REMOTE_ADDR' seems to be a valid client IP, use it.
if(ip_check($_SERVER['REMOTE_ADDR'], $allow_private, $proxy_ip)) return $_SERVER['REMOTE_ADDR'];
if(isset($_SERVER[$header]))
{
//Split comma separated values [1] in the header and traverse the proxy chain backwards.
//[1] https://en.wikipedia.org/wiki/X-Forwarded-For#Format
$chain = array_reverse(preg_split('/\s*,\s*/', $_SERVER[$header]));
foreach($chain as $ip) if(ip_check($ip, $allow_private, $proxy_ip)) return $ip;
}
return null;
}
//Check for valid IP. If 'allow_private' flag is set to truthy, it allows private IP ranges as valid client IP as well. (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16)
//Pass your trusted reverse proxy IPs as $proxy_ip to exclude them from being valid.
function ip_check($ip, $allow_private = false, $proxy_ip = [])
{
if(!is_string($ip) || is_array($proxy_ip) && in_array($ip, $proxy_ip)) return false;
$filter_flag = FILTER_FLAG_NO_RES_RANGE;
if(!$allow_private)
{
//Disallow loopback IP range which doesn't get filtered via 'FILTER_FLAG_NO_PRIV_RANGE' [1]
//[1] https://www.php.net/manual/en/filter.filters.validate.php
if(preg_match('/^127\.$/', $ip)) return false;
$filter_flag |= FILTER_FLAG_NO_PRIV_RANGE;
}
return filter_var($ip, FILTER_VALIDATE_IP, $filter_flag) !== false;
}
it doenst work for me but it prints the correct element to the console
this is the code:
function click(x, y)
{
var ev = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true,
'screenX': x,
'screenY': y
});
var el = document.elementFromPoint(x, y);
console.log(el); //print element to console
el.dispatchEvent(ev);
}
click(400, 400);
To find all the links, we will in this example use the urllib2 module together with the re.module *One of the most powerful function in the re module is "re.findall()". While re.search() is used to find the first match for a pattern, re.findall() finds all the matches and returns them as a list of strings, with each string representing one match*
import urllib2
import re
#connect to a URL
website = urllib2.urlopen(url)
#read html code
html = website.read()
#use re.findall to get all the links
links = re.findall('"((http|ftp)s?://.*?)"', html)
print links
I hope your stored procedure is not doing a cursor loop!
If not, take the query from your stored procedure and integrate that query within the query you are posting here:
SELECT t.TenantName, t.CarPlateNumber, t.CarColor, t.Sex, t.SSNO, t.Phone, t.Memo,
u.UnitNumber,
p.PropertyName
,dt.TenantBalance
FROM tblTenant t
LEFT JOIN tblRentalUnit u ON t.UnitID = u.ID
LEFT JOIN tblProperty p ON u.PropertyID = p.ID
LEFT JOIN (SELECT ID, SUM(ISNULL(trans.Amount,0)) AS TenantBalance
FROM tblTransaction
GROUP BY tenant.ID
) dt ON t.ID=dt.ID
ORDER BY p.PropertyName, t.CarPlateNumber
If you are doing something more than a query in your stored procedure, create a temp table and execute the stored procedure into this temp table and then join to that in your query.
create procedure test_proc
as
select 1 as x, 2 as y
union select 3,4
union select 5,6
union select 7,8
union select 9,10
return 0
go
create table #testing
(
value1 int
,value2 int
)
INSERT INTO #testing
exec test_proc
select
*
FROM #testing
The desired effect can also be achieved by moving the submit button outside of the form as described here:
Prevent page reload and redirect on form submit ajax/jquery
Like this:
<form id="getPatientsForm">
Enter URL for patient server
<br/><br/>
<input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
<input name="patientRootUrl" size="100"></input>
<br/><br/>
</form>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
First open empty new Tab by using the keys Ctrl + t and then use .get()
to fetch the URL you want. Your code should look something like this -
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,"t");
driver.findElement(By.tagName("body")).sendKeys(selectLinkOpeninNewTab);
driver.get("www.facebook.com");
If you want to open a link on the current view in a new tab then the code you've written above can be used. Instead of By.linkText()
make sure you use the appropriate By
selector class to select the web element.
Explanation of command that i am going to write:-
.
means any character, digit can come in place of .
*
means zero or more occurrences of thing written just previous to it.
|
means 'or'.
So,
james.*jack
would search james
, then any number of character until jack
comes.
Since you want either jack.*james
or james.*jack
Hence Command:
jack.*james|james.*jack
Now there is few ways to install fontAwesome on Angular CLI:
ng add @fortawesome/angular-fontawesome
OR using yarn
yarn add @fortawesome/fontawesome-svg-core
yarn add @fortawesome/free-solid-svg-icons
yarn add @fortawesome/angular-fontawesome
OR Using NPM
npm install @fortawesome/fontawesome-svg-core
npm install @fortawesome/free-solid-svg-icons
npm install @fortawesome/angular-fontawesome
Reference here: https://github.com/FortAwesome/angular-fontawesome
I got this problem because I uninstalled VS 2012, I don't want to reinstall it back, so I downloaded the AspNetMVC4Setup.exe from Microsoft.com and fixed my problem.
https://www.microsoft.com/en-us/download/details.aspx?id=30683
Something like:
$db = mysqli_connect("localhost", "user", "password", "database");
$name = $db->mysqli_real_escape_string($name);
$query = 'ALTER TABLE assesment ADD ' . $name . ' TINYINT NOT NULL DEFAULT \'0\'';
if($db->query($query)) {
echo "It worked";
}
Haven't tested it but should work.
To treat both , and . as decimal point you must not only replace one with the other, but also make sure the Culture used parsing interprets it as a decimal point.
text = text.Replace(',', '.');
return double.TryParse(text, NumberStyles.Any, CultureInfo.InvariantCulture, out value);
So, I've really tried to understand this, but it seems that Django still doesn't make this very straightforward. I'm not all that dumb, but I just can't see any (somewhat) simple solution.
I find it generally pretty ugly to have to override the Admin views for this sort of thing, and every example I find never fully applies to the Admin views.
This is such a common circumstance with the models I make that I find it appalling that there's no obvious solution to this...
I've got these classes:
# models.py
class Company(models.Model):
# ...
class Contract(models.Model):
company = models.ForeignKey(Company)
locations = models.ManyToManyField('Location')
class Location(models.Model):
company = models.ForeignKey(Company)
This creates a problem when setting up the Admin for Company, because it has inlines for both Contract and Location, and Contract's m2m options for Location are not properly filtered according to the Company that you're currently editing.
In short, I would need some admin option to do something like this:
# admin.py
class LocationInline(admin.TabularInline):
model = Location
class ContractInline(admin.TabularInline):
model = Contract
class CompanyAdmin(admin.ModelAdmin):
inlines = (ContractInline, LocationInline)
inline_filter = dict(Location__company='self')
Ultimately I wouldn't care if the filtering process was placed on the base CompanyAdmin, or if it was placed on the ContractInline. (Placing it on the inline makes more sense, but it makes it hard to reference the base Contract as 'self'.)
Is there anyone out there who knows of something as straightforward as this badly needed shortcut? Back when I made PHP admins for this sort of thing, this was considered basic functionality! In fact, it was always automatic, and had to be disabled if you really didn't want it!
As stated in 1.7.12 Release Notes, you may use
$ git rebase -i --root
If you want to remove all added files from git for commit
git reset
If you want to remove an individual file
git rm <file>
If you are a Wordpress developer I have some great news for you.
Just search for, install and activate the Wordpress plugin called: reBusted.
No configuration is necessary.
It will automatically force cache refresh if the content has been updated and it solves this issue completely and reliably. Tested and used on hundreds of clients Wordpress sites – works perfectly everywhere.
Cannot recommend it enough.
If you use Wordpress, this is by far your best option and most elegant resolution for this issue.
Enjoy!
Another approach would be to use Array.prototype.forEach()
as
const raw = {_x000D_
item1: {_x000D_
key: 'sdfd',_x000D_
value: 'sdfd'_x000D_
},_x000D_
item2: {_x000D_
key: 'sdfd',_x000D_
value: 'sdfd'_x000D_
},_x000D_
item3: {_x000D_
key: 'sdfd',_x000D_
value: 'sdfd'_x000D_
}_x000D_
};_x000D_
_x000D_
const allowed = ['item1', 'item3', 'lll'];_x000D_
_x000D_
var finalObj = {};_x000D_
allowed.forEach(allowedVal => {_x000D_
if (raw[allowedVal])_x000D_
finalObj[allowedVal] = raw[allowedVal]_x000D_
})_x000D_
console.log(finalObj)
_x000D_
It includes values of only those keys which are available in the raw data and thus preventing adding any junk data.
vb.net version
Me.Background = CType(New BrushConverter().ConvertFrom("#ffaacc"), SolidColorBrush)
An example, available for POSIX compliant systems :
/*
* This program displays the names of all files in the current directory.
*/
#include <dirent.h>
#include <stdio.h>
int main(void) {
DIR *d;
struct dirent *dir;
d = opendir(".");
if (d) {
while ((dir = readdir(d)) != NULL) {
printf("%s\n", dir->d_name);
}
closedir(d);
}
return(0);
}
Beware that such an operation is platform dependant in C.
Source : http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1046380353&id=1044780608
Try to do an UPDATE. If it doesn't modify any row that means it didn't exist, so do an insert. Obviously, you do this inside a transaction.
You can of course wrap this in a function if you don't want to put the extra code on the client side. You also need a loop for the very rare race condition in that thinking.
There's an example of this in the documentation: http://www.postgresql.org/docs/9.3/static/plpgsql-control-structures.html, example 40-2 right at the bottom.
That's usually the easiest way. You can do some magic with rules, but it's likely going to be a lot messier. I'd recommend the wrap-in-function approach over that any day.
This works for single row, or few row, values. If you're dealing with large amounts of rows for example from a subquery, you're best of splitting it into two queries, one for INSERT and one for UPDATE (as an appropriate join/subselect of course - no need to write your main filter twice)
I'm not sure of the details as you haven't posted the whole code, but:
hashCode()
as wellequals
method should have Object
, not People
as its argument type. At the moment you are overloading, not overriding, the equals method, which probably isn't what you want, especially given that you check its type later.instanceof
to check it is a People object e.g. if (!(other instanceof People)) { result = false;}
equals
is used for all objects, but not primitives. I think you mean age is an int
(primitive), in which case just use ==
. Note that an Integer (with a capital 'I') is an Object which should be compared with equals.See What issues should be considered when overriding equals and hashCode in Java? for more details.
I just find this solution but in my case it doesn't work:
@OneToMany(cascade = CascadeType.ALL, targetEntity = MyClass.class, mappedBy = "xxx", fetch = FetchType.LAZY, orphanRemoval = true)
orphanRemoval = true has no effect.
Array elements value should be less than the array length for this one:
public void findCounts(int[] arr, int n) {
int i = 0;
while (i < n) {
if (arr[i] <= 0) {
i++;
continue;
}
int elementIndex = arr[i] - 1;
if (arr[elementIndex] > 0) {
arr[i] = arr[elementIndex];
arr[elementIndex] = -1;
}
else {
arr[elementIndex]--;
arr[i] = 0;
i++;
}
}
Console.WriteLine("Below are counts of all elements");
for (int j = 0; j < n; j++) {
Console.WriteLine(j + 1 + "->" + Math.Abs(arr[j]));
}
}
Time complexity of this will be O(N)
and space complexity will be O(1)
.
import ast,sys
input_str = sys.stdin.read()
input_list = ast.literal_eval(input_str)
list_1 = input_list[0]
list_2 = input_list[1]
import numpy as np
array_1 = np.array(list_1)
array_2 = np.array(list_2)
array_3 = array_1*array_2
print(list(array_3))
package javaexception;
public class JavaException {
void show() throws Exception
{
throw new Exception("my.own.Exception");
}
void show2() throws Exception // Why throws is necessary here ?
{
show();
}
void show3() throws Exception // Why throws is necessary here ?
{
show2();
}
public static void main(String[] args) {
JavaException a = new JavaException();
try{
a.show3();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
Only small changes in your program. What It seems to be misunderstood by many regarding the main issue, is whenever you throw exception you need to handle it, not necessary in the same place ( ex. show1,2,3 method in your program) but you must at first caller method inside the 'main'. in one word, there is 'throw', there must be 'catch/try', even if not same method where exception happens.
dex2jar helps to decompile your apk but not 100%. You will have some problems with .smali files. Dex2jar cannot convert it to java. I know one application that can decompile your apk source files and no problems with .smali files. Here is a link http://www.hensence.com/en/smali2java/
A Lay men's way is
on Main() rename the executing assembly file .exe to some thing else check date and time of created. and the updated file date time and copy to the application folder.
//Rename he executing file
System.IO.FileInfo file = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location);
System.IO.File.Move(file.FullName, file.DirectoryName + "\\" + file.Name.Replace(file.Extension,"") + "-1" + file.Extension);
then do the logic check and copy the new file to executing folder
Someone will give you a better answe than this possibly, but one thing I tend to do is if all my numeric data are int64
or float64
objects, then you can create a dict of the column data types and then use the values to create your list of columns.
So for example, in a dataframe where I have columns of type float64
, int64
and object
firstly you can look at the data types as so:
DF.dtypes
and if they conform to the standard whereby the non-numeric columns of data are all object
types (as they are in my dataframes), then you can do the following to get a list of the numeric columns:
[key for key in dict(DF.dtypes) if dict(DF.dtypes)[key] in ['float64', 'int64']]
Its just a simple list comprehension. Nothing fancy. Again, though whether this works for you will depend upon how you set up you dataframe...
Yes.
var data = {_x000D_
'PropertyA': 1,_x000D_
'PropertyB': 2,_x000D_
'PropertyC': 3_x000D_
};_x000D_
_x000D_
data["PropertyD"] = 4;_x000D_
_x000D_
// dialog box with 4 in it_x000D_
alert(data.PropertyD);_x000D_
alert(data["PropertyD"]);
_x000D_
The problem is you are setting the window.location.hash to an element's ID attribute. It is the expected behavior for the browser to jump to that element, regardless of whether you "preventDefault()" or not.
One way to get around this is to prefix the hash with an arbitrary value like so:
window.location.hash = 'panel-' + id.replace('#', '');
Then, all you need to do is to check for the prefixed hash on page load. As an added bonus, you can even smooth scroll to it since you are now in control of the hash value...
$(function(){
var h = window.location.hash.replace('panel-', '');
if (h) {
$('#slider').scrollTo(h, 800);
}
});
If you need this to work at all times (and not just on the initial page load), you can use a function to monitor changes to the hash value and jump to the correct element on-the-fly:
var foundHash;
setInterval(function() {
var h = window.location.hash.replace('panel-', '');
if (h && h !== foundHash) {
$('#slider').scrollTo(h, 800);
foundHash = h;
}
}, 100);
A note in response to Belter's comment on fedtuck's accepted answer above, since I lack the reputation to add comments.
This is not true for any of which I am aware, in line with the Mozilla docs
disabled equals to true or false
When the disabled attribute is present the element is disabled regardless of value. See this example
<input placeholder="i can be changed"/>
<input disabled placeholder="i can NOT be changed"/>
<input disabled="true" placeholder="i can NOT be changed"/>
<input disabled="false" placeholder="i can NOT be changed"/>
Every element of your vector is a float[4]
, so when you resize every element needs to default initialized from a float[4]
. I take it you tried to initialize with an int
value like 0
?
Try:
static float zeros[4] = {0.0, 0.0, 0.0, 0.0};
myvector.resize(newsize, zeros);
This code is deprecated:
Drawable drawable = getResources().getDrawable( R.drawable.icon );
Use this instead:
Drawable drawable = ContextCompat.getDrawable(getApplicationContext(),R.drawable.icon);
var str = "This is a single quote: ' and so is this: '";
console.log(str);
var replaced = str.replace(/'/g, "\\'");
console.log(replaced);
Gives you:
This is a single quote: ' and so is this: '
This is a single quote: \' and so is this: \'
Suppose you have an array in PHP as $iniData with 5 fields. If using ajax -
echo json_encode($iniData);
In Javascript, use the following :
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: "ajaxCalls.php",
data: "dataType=ini",
success: function(msg)
{
var x = eval('(' + msg + ')');
$('#allowed').html(x.allowed); // these are the fields which you can now easily access..
$('#completed').html(x.completed);
$('#running').html(x.running);
$('#expired').html(x.expired);
$('#balance').html(x.balance);
}
});
});
</script>
Getting stacktrace:
StackTraceElement[] ste = Thread.currentThread().getStackTrace();
Printing stacktrace (JAVA 8+):
Arrays.asList(ste).forEach(System.out::println);
Printing stacktrage (JAVA 7):
StringBuilder sb = new StringBuilder();
for (StackTraceElement st : ste) {
sb.append(st.toString() + System.lineSeparator());
}
System.out.println(sb);
Example : we want to represent an 2D array of SIZE_X and SIZE_Y size. That means that we will have MAXY consecutive rows of MAXX size. Hence the set function is
void set_array( int x, int y, int val ) { array[ x * SIZE_Y + y ] = val; }
The get would be:
int get_array( int x, int y ) { return array[ x * SIZE_Y + y ]; }
Using jQuery the easiest will be:
var text = '<p>name</p><p><span style="font-size:xx-small;">ajde</span></p><p><em>da</em></p>';
var output = $("<div />").html(text).text();
console.log(output);
Another possible solution is to use FocusBehavior provided by free DevExpress MVVM Framework:
<TextBox Text="This control is focused on startup">
<dxmvvm:Interaction.Behaviors>
<dxmvvm:FocusBehavior/>
</dxmvvm:Interaction.Behaviors>
</TextBox>
It allows you to focus a control when it's loaded, when a certain event is raised or a property is changed.
If you're okay with ES2017, await
is good:
const DEF_DELAY = 1000;
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms || DEF_DELAY));
}
await sleep(100);
Note that the await
part needs to be in an async function:
//IIAFE (immediately invoked async function expression)
(async()=>{
//Do some stuff
await sleep(100);
//Do some more stuff
})()
Also, you can do this:
FirstClass.this.overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
And you don't need to add any animation xml
It's method syntax (which I find easier to read) but this might do it
Updated post comment
Use .FirstOrDefault()
instead of .First()
With regard to the dates average, you may have to drop that ordering for the moment as I am unable to get to an IDE at the moment
var groupByReference = context.Measurements
.GroupBy(m => m.Reference)
.Select(g => new {Creation = g.FirstOrDefault().CreationTime,
// Avg = g.Average(m => m.CreationTime.Ticks),
Items = g })
.OrderBy(x => x.Creation)
// .ThenBy(x => x.Avg)
.Take(numOfEntries)
.ToList();
use Illuminate\Database\Eloquent\Builder;
$query = Customers::with('orders');
$query = $query->whereHas('orders', function (Builder $query) use ($request) {
$query = $query->where('orders.customer_id', 'NULL')
});
$query = $query->get();
Did you try setting the style:
input {
text-align:right;
}
Just tested, this works fine (in FF3 at least):
<html>
<head>
<title>Blah</title>
<style type="text/css">
input { text-align:right; }
</style>
</head>
<body>
<input type="text" value="2">
</body>
</html>
You'll probably want to throw a class on these inputs, and use that class as the selector. I would shy away from "rightAligned" or something like that. In a class name, you want to describe what the element's function is, not how it should be rendered. "numeric" might be good, or perhaps the business function of the text boxes.
Low Coupling and High Cohesion is a recommended phenomenon.
Coupling means to what extent various modules are interdependent and how the other modules are affected on changing some/considerable functionality of a module. Low coupling is emphasized as the dependency has to be maintained low so that very least/negligible changes are made to other modules.
Another option is to use
int? accom = (accomStr == "noval" ? Convert.DBNull : Convert.ToInt32(accomStr);
I like this one most.
GetCursorPos() will return to you the x/y if you pass in a pointer to a POINT structure.
Hiding the cursor can be done with ShowCursor().
Speaking for current (2021-2) Java versions there is still the old ISO-8859-1 function utils.Properties#load.
Allow me to quote from the official doc.
PropertyResourceBundle
PropertyResourceBundle can be constructed either from an InputStream or a Reader, which represents a property file. Constructing a PropertyResourceBundle instance from an InputStream requires that the input stream be encoded in UTF-8. By default, if a MalformedInputException or an UnmappableCharacterException occurs on reading the input stream, then the PropertyResourceBundle instance resets to the state before the exception, re-reads the input stream in ISO-8859-1, and continues reading. If the system property java.util.PropertyResourceBundle.encoding is set to either "ISO-8859-1" or "UTF-8", the input stream is solely read in that encoding, and throws the exception if it encounters an invalid sequence. If "ISO-8859-1" is specified, characters that cannot be represented in ISO-8859-1 encoding must be represented by Unicode Escapes as defined in section 3.3 of The Java™ Language Specification whereas the other constructor which takes a Reader does not have that limitation. Other encoding values are ignored for this system property. The system property is read and evaluated when initializing this class. Changing or removing the property has no effect after the initialization.
https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/PropertyResourceBundle.html
Properties#load
Reads a property list (key and element pairs) from the input byte stream. The input stream is in a simple line-oriented format as specified in load(Reader) and is assumed to use the ISO 8859-1 character encoding; that is each byte is one Latin1 character. Characters not in Latin1, and certain special characters, are represented in keys and elements using Unicode escapes as defined in section 3.3 of The Java™ Language Specification.
Bootstrap 4 (^beta) has changed the classes for responsive hiding/showing elements. See this link for correct classes to use: http://getbootstrap.com/docs/4.0/utilities/display/#hiding-elements
Old question, but the autolayout-solution with runtime border adjustments still missing.
borders(for: [.left, .bottom], width: 2, color: .red)
The following UIView extension will add the border only on the given edges. If you change the edges at runtime, the borders will adjust accordingly.
extension UIView {
func borders(for edges:[UIRectEdge], width:CGFloat = 1, color: UIColor = .black) {
if edges.contains(.all) {
layer.borderWidth = width
layer.borderColor = color.cgColor
} else {
let allSpecificBorders:[UIRectEdge] = [.top, .bottom, .left, .right]
for edge in allSpecificBorders {
if let v = viewWithTag(Int(edge.rawValue)) {
v.removeFromSuperview()
}
if edges.contains(edge) {
let v = UIView()
v.tag = Int(edge.rawValue)
v.backgroundColor = color
v.translatesAutoresizingMaskIntoConstraints = false
addSubview(v)
var horizontalVisualFormat = "H:"
var verticalVisualFormat = "V:"
switch edge {
case UIRectEdge.bottom:
horizontalVisualFormat += "|-(0)-[v]-(0)-|"
verticalVisualFormat += "[v(\(width))]-(0)-|"
case UIRectEdge.top:
horizontalVisualFormat += "|-(0)-[v]-(0)-|"
verticalVisualFormat += "|-(0)-[v(\(width))]"
case UIRectEdge.left:
horizontalVisualFormat += "|-(0)-[v(\(width))]"
verticalVisualFormat += "|-(0)-[v]-(0)-|"
case UIRectEdge.right:
horizontalVisualFormat += "[v(\(width))]-(0)-|"
verticalVisualFormat += "|-(0)-[v]-(0)-|"
default:
break
}
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: horizontalVisualFormat, options: .directionLeadingToTrailing, metrics: nil, views: ["v": v]))
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: verticalVisualFormat, options: .directionLeadingToTrailing, metrics: nil, views: ["v": v]))
}
}
}
}
}
I used the StringReader class in java.io. One of it's functions read(char[] cbuf)
reads a string's contents into an array.
String str = "hello";
char[] array = new char[str.length()];
StringReader read = new StringReader(str);
try {
read.read(array); //Reads string into the array. Throws IOException
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 0; i < str.length(); i++) {
System.out.println("array["+i+"] = "+array[i]);
}
Running this gives you the output:
array[0] = h
array[1] = e
array[2] = l
array[3] = l
array[4] = o
http://www.quirksmode.org/js/cookies.html
update would just be resetting it using createCookie
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 *1000));
var expires = "; expires=" + date.toGMTString();
} else {
var expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1,c.length);
}
if (c.indexOf(nameEQ) == 0) {
return c.substring(nameEQ.length,c.length);
}
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
The document.location
is an object that contains properties for the current location.
The href
property is one of these properties, containing the complete URL, i.e. all the other properties put together.
Some browsers allow you to assign an URL to the location
object and acts as if you assigned it to the href
property. Some other browsers are more picky, and requires you to use the href
property. Thus, to make the code work in all browsers, you have to use the href
property.
Both the window
and document
objects has a location
object. You can set the URL using either window.location.href
or document.location.href
. However, logically the document.location
object should be read-only (as you can't change the URL of a document; changing the URL loads a new document), so to be on the safe side you should rather use window.location.href
when you want to set the URL.
ExpressJS is bare-bones web application framework on top of NodeJS.
It can be used to build WebApps, RESTFUL APIs etc quickly.
Supports multiple template engines like Jade, EJS.
ExpressJS keeps only a minimalist functionality as core features and as such there are no ORMs or DBs supported as default. But with a little effort expressjs apps can be integrated with different databases.
For a getting started guide on creating ExpressJS apps, look into the following link:
var TableRowItem = React.createClass({
render: function() {
var td = function() {
return this.props.columns.map(function(c, i) {
return <td key={i}>{this.props.data[c]}</td>;
}, this);
}.bind(this);
return (
<tr>{ td(this.props.item) }</tr>
)
}
});
This will sove the problem.
onCreate()
method gets called when activity gets created, and its called only once in whole Activity life cycle.
where as onStart()
is called when activity is stopped... I mean it has gone to background and its onStop()
method is called by the os. onStart()
may be called multiple times in Activity life cycle.More details here
String Formatting:
a = 6.789809823
print('%.2f' %a)
OR
print ("{0:.2f}".format(a))
Round Function can be used:
print(round(a, 2))
Good thing about round() is that, we can store this result to another variable, and then use it for other purposes.
b = round(a, 2)
print(b)
Here's a more complete and flexible example that doesn't omit necessary includes to generate compilation errors:
#include <iostream>
#include <unordered_map>
class Hashtable {
std::unordered_map<const void *, const void *> htmap;
public:
void put(const void *key, const void *value) {
htmap[key] = value;
}
const void *get(const void *key) {
return htmap[key];
}
};
int main() {
Hashtable ht;
ht.put("Bob", "Dylan");
int one = 1;
ht.put("one", &one);
std::cout << (char *)ht.get("Bob") << "; " << *(int *)ht.get("one");
}
Still not particularly useful for keys, unless they are predefined as pointers, because a matching value won't do! (However, since I normally use strings for keys, substituting "string" for "const void *" in the declaration of the key should resolve this problem.)
As others have mentioned, Environment.NewLine
returns a platform-specific string for beginning a new line, which should be:
"\r\n"
(\u000D\u000A) for Windows"\n"
(\u000A) for Unix"\r"
(\u000D) for Mac (if such implementation existed)Note that when writing to the console, Environment.NewLine is not strictly necessary. The console stream will translate "\n"
to the appropriate new-line sequence, if necessary.
Something close to:
@Html.DropDownListFor(m => m.UserRole,
new SelectList(Model.Roles, "UserRoleId", "UserRole", Model.Roles.First().UserRoleId),
new { /* any html attributes here */ })
You need a SelectList to populate the DropDownListFor. For any HTML attributes you need, you can add:
new { @class = "DropDown", @id = "dropdownUserRole" }
I solved this problem to add a public setter for all properties, which should be deserialized.
I suggest using the amazing tool direnv. With it you can inject environment variables once you cd into the project. These steps worked for me:
.envrc file
source_up
dotenv
.env file
_JAVA_OPTIONS="-DYourEnvHere=123"
I hope this helps someone. I use this bit of logic to verify if network shares are responsive before checking the individual paths. It should handle DNS names and IP addresses
A valid path in the text file would be \192.168.1.2\'folder' or \NAS\'folder'
@echo off
title Network Folder Check
pushd "%~dp0"
:00
cls
for /f "delims=\\" %%A in (Files-to-Check.txt) do set Server=%%A
setlocal EnableDelayedExpansion
ping -n 1 %Server% | findstr TTL= >nul
if %errorlevel%==1 (
ping -n 1 %Server% | findstr "Reply from" | findstr "time" >nul
if !errorlevel!==1 (echo Network Asset %Server% Not Found & pause & goto EOF)
)
:EOF
Your question is vague (are you always looking for the first part?), but you can get the exact output you asked for with string.Split
:
string[] substrings = a.Split(',');
b = substrings[0];
Console.WriteLine(b);
Output:
abc
I faced the same problem too. Look up to the left side, and select (full). (Make), (gcc) and many others will appear. You will be able to chose the search bar to find them easily.
Create a small utility function like:
def date(datestr="", format="%Y-%m-%d"):
from datetime import datetime
if not datestr:
return datetime.today().date()
return datetime.strptime(datestr, format).date()
This is versatile enough:
Easiest way is to delete default APN from emulator(in my case its T- mobile) and create new APN with your proxy settings.
Note: i have tried all command line options and also tried setting the proxy for emulators default APN but nothing worked.
I have uploaded a sample project. You can take a look.
Check the format of the video you are rendering. Rendering of mp4 format started from API level 11 and the format must be mp4(H.264)
I encountered the same problem, I had to convert my video to many formats before I hit the format: Use total video converter to convert the video to mp4. It works like a charm.
to @BalusC answer I would add how to convert the response in a String:
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
Log.i("Read from server", result);
}
set <ORACLE_HOME> path variable
example
path ORACLE_HOME
value is C:\oraclexe\app\oracle\product\10.2.0\server
Note: This will completely remove nodejs from your system; then you can make a fresh install from the below commands.
Removing Nodejs and Npm
sudo apt-get remove nodejs npm node
sudo apt-get purge nodejs
Now remove .node
and .npm
folders from your system
sudo rm -rf /usr/local/bin/npm
sudo rm -rf /usr/local/share/man/man1/node*
sudo rm -rf /usr/local/lib/dtrace/node.d
sudo rm -rf ~/.npm
sudo rm -rf ~/.node-gyp
sudo rm -rf /opt/local/bin/node
sudo rm -rf opt/local/include/node
sudo rm -rf /opt/local/lib/node_modules
sudo rm -rf /usr/local/lib/node*
sudo rm -rf /usr/local/include/node*
sudo rm -rf /usr/local/bin/node*
Go to home directory and remove any node or node_modules
directory, if exists.
You can verify your uninstallation by these commands; they should not output anything.
which node
which nodejs
which npm
Installing NVM (Node Version Manager) by downloading and running a script
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh | bash
The command above will clone the NVM repository from Github to the ~/.nvm
directory:
Close and reopen your terminal to start using nvm or run the following to use it now:
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion
As the output above says, you should either close and reopen the terminal or run the commands to add the path to nvm script to the current shell session. You can do whatever is easier for you.
Once the script is in your PATH, verify that nvm was properly installed by typing:
nvm --version
which should give this output:
0.34.0
Installing Node.js and npm
nvm install node
nvm install --lts
Once the installation is completed, verify it by printing the Node.js version:
node --version
should give this output:
v12.8.1
Npm should also be installed with node, verify it using
npm -v
should give:
6.13.4
Extra - [Optional] You can also use two different versions of node using nvm easily
nvm install 8.10.0 # just put the node version number Now switch between node versions
$ nvm ls
-> v12.14.1
v13.7.0
default -> lts/* (-> v12.14.1)
node -> stable (-> v13.7.0) (default)
stable -> 13.7 (-> v13.7.0) (default)
iojs -> N/A (default)
unstable -> N/A (default)
lts/* -> lts/erbium (-> v12.14.1)
lts/argon -> v4.9.1 (-> N/A)
lts/boron -> v6.17.1 (-> N/A)
lts/carbon -> v8.17.0 (-> N/A)
lts/dubnium -> v10.18.1 (-> N/A)
In my case v12.14.1 and v13.7.0 both are installed, to switch I have to just use
nvm use 12.14.1
Configuring npm for global installations In your home directory, create a directory for global installations:
mkdir ~/.npm-global
Configure npm to use the new directory path:
npm config set prefix '~/.npm-global'
In your preferred text editor, open or create a ~/.profile
file if does not exist and add this line:
PATH="$HOME/.npm-global/bin:$PATH"
On the command line, update your system variables:
source ~/.profile
That's all
You just need to escape the quote in your first example:
$ sed 's/\"//g' file.txt
Erin's method updated to Swift 3, This shows days from today (disregarding time of day)
func daysBetweenDates( endDate: Date) -> Int
let calendar: Calendar = Calendar.current
let date1 = calendar.startOfDay(for: Date())
let date2 = calendar.startOfDay(for: secondDate)
return calendar.dateComponents([.day], from: date1, to: date2).day!
}
Currently (Swift 2.1) you can check it using 3 ways:
Using '?' answered by @Sulthan
And using as?
operator:
if let delegateMe = self.delegate as? YourCustomViewController
{
delegateMe.onSuccess()
}
Basically it depends on what you are trying to achieve:
In addition to all here, the href is shown on browser's status bar, and onclick not. I think it's not user friendly to show javascript code there.
Here's a way to convert binary numbers to ASCII characters that is often simple enough to do in your head.
1 - Convert every 4 binary digits into one hex digit.
Here's a binary to hex conversion chart:
0001 = 1
0010 = 2
0011 = 3
0100 = 4
0101 = 5
0110 = 6
0111 = 7
1000 = 8
1001 = 9
1010 = a (the hex number a, not the letter a)
1011 = b
1100 = c
1101 = d
1110 = e
1111 = f
(The hexadecimal numbers a through f are the decimal numbers 10 through 15. That's what hexadecimal, or "base 16" is - instead of each digit being capable of representing 10 different numbers [0 - 9], like decimal or "base 10" does, each digit is instead capable of representing 16 different numbers [0 - f].)
Once you know that chart, converting any string of binary digits into a string of hex digits is simple.
For example,
01000100 = 0100 0100 = 44 hex
1010001001110011 = 1010 0010 0111 0011 = a273 hex
Simple enough, right? It is a simple matter to convert a binary number of any length into its hexadecimal equivalent.
(This works because hexadecimal is base 16 and binary is base 2 and 16 is the 4th power of 2, so it takes 4 binary digits to make 1 hex digit. 10, on the other hand, is not a power of 2, so we can't convert binary to decimal nearly as easily.)
2 - Split the string of hex digits into pairs.
When converting a number into ASCII, every 2 hex digits is a character. So break the hex string into sets of 2 digits.
You would split a hex number like 7340298b392 this into 6 pairs, like this:
7340298b392 = 07 34 02 98 b3 92
(Notice I prepended a 0, since I had an odd number of hex digits.)
That's 6 pairs of hex digits, so its going to be 6 letters. (Except I know right away that 98, b3 and 92 aren't letters. I'll explain why in a minute.)
3 - Convert each pair of hex digits into a decimal number.
Do this by multiplying the (decimal equivalent of the) left digit by 16, and adding the 2nd.
For example, b3 hex = 11*16 + 3, which is 110 + 66 + 3, which is 179. (b hex is 11 decimal.)
4 - Convert the decimal numbers into ASCII characters.
Now, to get the ASCII letters for the decimal numbers, simply keep in mind that in ASCII, 65 is an uppercase 'A', and 97 is a lowercase 'a'.
So what letter is 68?
68 is the 4th letter of the alphabet in uppercase, right?
65 = A, 66 = B, 67 = C, 68 = D.
So 68 is 'D'.
You take the decimal number, subtract 64 for uppercase letters if the number is less than 97, or 96 for lowercase letters if the number is 97 or larger, and that's the number of the letter of the alphabet associated with that set of 2 hex digits.
Alternatively, if you're not afraid of a little bit of easy hex arithmetic, you can skip step 3, and just go straight from hex to ASCII, by remembering, for example, that
hex 41 = 'A'
hex 61 = 'a'
So subtract 40 hex for uppercase letters or 60 hex for lowercase letters, and convert what's left to decimal to get the alphabet letter number.
For example
01101100 = 6c, 6c - 60 = c = 12 decimal = 'l'
01010010 = 52, 52 - 40 = 12 hex = 18 decimal = 'R'
(When doing this, it's helpful to remember that 'm' (or 'M') is the 13 letter of the alphabet. So you can count up or down from 13 to find a letter that's nearer to the middle than to either end.)
I saw this on a shirt once, and was able to read it in my head:
01000100
01000001
01000100
I did it like this:
01000100 = 0100 0100 = 44 hex, - 40 hex = ucase letter 4 = D
01000001 = 0100 0001 = 41 hex, - 40 hex = ucase letter 1 = A
01000100 = 0100 0100 = 44 hex, - 40 hex = ucase letter 4 = D
The shirt said "DAD", which I thought was kinda cool, since it was being purchased by a pregnant woman. Her husband must be a geek like me.
How did I know right away that 92, b3, and 98 were not letters?
Because the ASCII code for a lowercase 'z' is 96 + 26 = 122, which in hex is 7a. 7a is the largest hex number for a letter. Anything larger than 7a is not a letter.
So that's how you can do it as a human.
How do computer programs do it?
For each set of 8 binary digits, convert it to a number, and look it up in an ASCII table.
(That's one pretty obvious and straight forward way. A typical programmer could probably think of 10 or 15 other ways in the space of a few minutes. The details depend on the computer language environment.)
Just to add another solution to the list, what I've found is that Visual Studio (2012 in my case) occasionally locks files under different processes.
So, on a crash, devenv.exe might still be running and holding onto the file(s). Alternatively (as I just discovered), vstestrunner or vstestdiscovery might be holding onto the file as well.
Kill all those processes and it might fix up the issue.
I do not want to repeat others' answers, so, in short I explain some common misunderstanding
You should avoid using it all across your project
DDD stresses the need to focus the most effort on the core subdomain. The core subdomain is the area of your product that will be the difference between it being a success and it being a failure. It’s the product’s unique selling point, the reason it is being built rather than bought.
Basically, it is because it takes too much time and effort. So, it is suggested to break down the whole domain into subdomain and just apply it in those with high business value. (ex not in generic subdomain like email, ...)
It is not object oriented programming. It is mostly problem solving approach and (sometimes) you do not need to use OO patterns (such as Gang of Four) in your domain models. Simply because it can not be understood by Business Experts (they do not know much about Factory, Decorator, ...). There are even some patterns in DDD (such as The Transaction Script, Table Module) which are not 100% in line with OO concepts.
It formats the string as two uppercase hexadecimal characters.
In more depth, the argument "X2"
is a "format string" that tells the ToString()
method how it should format the string. In this case, "X2" indicates the string should be formatted in Hexadecimal.
byte.ToString()
without any arguments returns the number in its natural decimal representation, with no padding.
Microsoft documents the standard numeric format strings which generally work with all primitive numeric types' ToString()
methods. This same pattern is used for other types as well: for example, standard date/time format strings can be used with DateTime.ToString()
.
As javascript is dynamically typed, rather than using the .length property as above you can simply treat the input value as a boolean:
var input = $.trim($("#spa").val());
if (input) {
// Do Stuff
}
You can also extract the logic out into functions, then by assigning a class and using the each()
method the code is more dynamic if, for example, in the future you wanted to add another input you wouldn't need to change any code.
So rather than hard coding the function call into the input markup, you can give the inputs a class, in this example it's test
, and use:
$(".test").each(function () {
$(this).keyup(function () {
$("#submit").prop("disabled", CheckInputs());
});
});
which would then call the following and return a boolean value to assign to the disabled
property:
function CheckInputs() {
var valid = false;
$(".test").each(function () {
if (valid) { return valid; }
valid = !$.trim($(this).val());
});
return valid;
}
You can see a working example of everything I've mentioned in this JSFiddle.
You can do this is in Scala, which runs on the JVM and is compatible with Java programs. http://www.scala-lang.org/
i.e.
class Foo(var prime: Boolean = false, val rib: String) {}
When you use a Range
object, you cannot simply use the following syntax:
Dim myRange as Range
myRange = Range("A1")
You must use the set
keyword to assign Range objects:
Function getData(currentWorksheet As Worksheet, dataStartRow As Integer, dataEndRow As Integer, DataStartCol As Integer, dataEndCol As Integer)
Dim dataTable As Range
Set dataTable = currentWorksheet.Range(currentWorksheet.Cells(dataStartRow, DataStartCol), currentWorksheet.Cells(dataEndRow, dataEndCol))
Set getData = dataTable
End Function
Sub main()
Dim test As Range
Set test = getData(ActiveSheet, 1, 3, 2, 5)
test.select
End Sub
Note that every time a range is declared I use the Set
keyword.
You can also allow your getData
function to return a Range
object instead of a Variant
although this is unrelated to the problem you are having.
Map can also be used, but sometimes hard to read when you have lots of things going on.
map{ print "element $_\n" } @array;
From Android Studio v3 and up, Infer Constraint was removed from the dropdown.
Use the magic wand icon in the toolbar menu above the design preview; there is the "Infer Constraints" button. Click on this button, this will automatically add some lines in the text field and the red line will be removed.
Try setting display:none
to hide and set display:block
to show.
Another method is has_key()
(if still using Python 2.X):
>>> a={"1":"one","2":"two"}
>>> a.has_key("1")
True
Try dir /b
, for bare format.
dir /?
will show you documentation of what you can do with the dir
command. Here is the output from my Windows 7 machine:
C:\>dir /?
Displays a list of files and subdirectories in a directory.
DIR [drive:][path][filename] [/A[[:]attributes]] [/B] [/C] [/D] [/L] [/N]
[/O[[:]sortorder]] [/P] [/Q] [/R] [/S] [/T[[:]timefield]] [/W] [/X] [/4]
[drive:][path][filename]
Specifies drive, directory, and/or files to list.
/A Displays files with specified attributes.
attributes D Directories R Read-only files
H Hidden files A Files ready for archiving
S System files I Not content indexed files
L Reparse Points - Prefix meaning not
/B Uses bare format (no heading information or summary).
/C Display the thousand separator in file sizes. This is the
default. Use /-C to disable display of separator.
/D Same as wide but files are list sorted by column.
/L Uses lowercase.
/N New long list format where filenames are on the far right.
/O List by files in sorted order.
sortorder N By name (alphabetic) S By size (smallest first)
E By extension (alphabetic) D By date/time (oldest first)
G Group directories first - Prefix to reverse order
/P Pauses after each screenful of information.
/Q Display the owner of the file.
/R Display alternate data streams of the file.
/S Displays files in specified directory and all subdirectories.
/T Controls which time field displayed or used for sorting
timefield C Creation
A Last Access
W Last Written
/W Uses wide list format.
/X This displays the short names generated for non-8dot3 file
names. The format is that of /N with the short name inserted
before the long name. If no short name is present, blanks are
displayed in its place.
/4 Displays four-digit years
Switches may be preset in the DIRCMD environment variable. Override
preset switches by prefixing any switch with - (hyphen)--for example, /-W.
You can actually create a simple Array with Alert Dialog like this.
val sexArray = arrayOf("Male", "Female")
val selectedPosition = 0
AlertDialog.Builder(requireContext())
.setSingleChoiceItems(sexArray, 0) { dialog, position ->
val selectedSex = sexArray[position]
}.show()
In IDLE press F5
You can open your .py file with IDLE and press F5 to run it.
You can open that same file with other editor ( like Komodo as you said ) save it and press F5 again; F5 works with IDLE ( even when the editing is done with another tool ).
If you want to run it directly from Komodo according to this article: Executing Python Code Within Komodo Edit you have to:
in the 'Command' field enter this text:
%(python) %F 3.a optionall click on the 'Key Binding' tab and assign a key command to this command
First, you use include_directories()
to tell CMake to add the directory as -I
to the compilation command line. Second, you list the headers in your add_executable()
or add_library()
call.
As an example, if your project's sources are in src
, and you need headers from include
, you could do it like this:
include_directories(include)
add_executable(MyExec
src/main.c
src/other_source.c
include/header1.h
include/header2.h
)
Create an object literal:
const Modes = {
DRAGGING: 'drag',
SCALING: 'scale',
CLICKED: 'click'
};
Firstly, I believe that trying to do several things at once is a bad practice in general and I suggest you think over what you are trying to achieve.
It serves as a good theoretical question though and from what I gather the CopyOnWriteArraySet
implementation of java.util.Set
interface satisfies your rather special requirements.
http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/CopyOnWriteArraySet.html
could you please try below code
<c:forEach var="hash" items="${map['key']}">
<option><c:out value="${hash}"/></option>
</c:forEach>
Edit: Documented by Apple although I couldn't actually get it to work: WKWebView Behavior with Keyboard Displays: "In iOS 10, WKWebView objects match Safari’s native behavior by updating their window.innerHeight property when the keyboard is shown, and do not call resize events" (perhaps can use focus or focus plus delay to detect keyboard instead of using resize).
Edit: code presumes onscreen keyboard, not external keyboard. Leaving it because info may be useful to others that only care about onscreen keyboards. Use http://jsbin.com/AbimiQup/4 to view page params.
We test to see if the document.activeElement
is an element which shows the keyboard (input type=text, textarea, etc).
The following code fudges things for our purposes (although not generally correct).
function getViewport() {
if (window.visualViewport && /Android/.test(navigator.userAgent)) {
// https://developers.google.com/web/updates/2017/09/visual-viewport-api Note on desktop Chrome the viewport subtracts scrollbar widths so is not same as window.innerWidth/innerHeight
return {
left: visualViewport.pageLeft,
top: visualViewport.pageTop,
width: visualViewport.width,
height: visualViewport.height
};
}
var viewport = {
left: window.pageXOffset, // http://www.quirksmode.org/mobile/tableViewport.html
top: window.pageYOffset,
width: window.innerWidth || documentElement.clientWidth,
height: window.innerHeight || documentElement.clientHeight
};
if (/iPod|iPhone|iPad/.test(navigator.platform) && isInput(document.activeElement)) { // iOS *lies* about viewport size when keyboard is visible. See http://stackoverflow.com/questions/2593139/ipad-web-app-detect-virtual-keyboard-using-javascript-in-safari Input focus/blur can indicate, also scrollTop:
return {
left: viewport.left,
top: viewport.top,
width: viewport.width,
height: viewport.height * (viewport.height > viewport.width ? 0.66 : 0.45) // Fudge factor to allow for keyboard on iPad
};
}
return viewport;
}
function isInput(el) {
var tagName = el && el.tagName && el.tagName.toLowerCase();
return (tagName == 'input' && el.type != 'button' && el.type != 'radio' && el.type != 'checkbox') || (tagName == 'textarea');
};
The above code is only approximate: It is wrong for split keyboard, undocked keyboard, physical keyboard. As per comment at top, you may be able to do a better job than the given code on Safari (since iOS8?) or WKWebView (since iOS10) using window.innerHeight
property.
I have found failures under other circumstances: e.g. give focus to input then go to home screen then come back to page; iPad shouldnt make viewport smaller; old IE browsers won't work, Opera didnt work because Opera kept focus on element after keyboard closed.
However the tagged answer (changing scrolltop to measure height) has nasty UI side effects if viewport zoomable (or force-zoom enabled in preferences). I don't use the other suggested solution (changing scrolltop) because on iOS, when viewport is zoomable and scrolling to focused input, there are buggy interactions between scrolling & zoom & focus (that can leave a just focused input outside of viewport - not visible).
You can use default primary key (id) which auto increaments.
Note: When you use first design i.e. use default field (id) as a primary key, initialize object by mentioning column names. e.g.
class User(models.Model):
user_name = models.CharField(max_length = 100)
then initialize,
user = User(user_name="XYZ")
if you initialize in following way,
user = User("XYZ")
then python will try to set id = "XYZ" which will give you error on data type.
php.ini
extension_dir=C:\path\to\server\php\ext
is set and adjust the path (set your PHP extension dir)extension=php_mbstring.dll
is set (uncommented)If this doesn't work and the php_mbstring.dll file is missing, then the PHP installation of this stack is simply broken.
Just for future reference, copying all these extension files to Windows/System or Windows/System32 is unnecessary.
All that is required is a copy of the php.ini file you edit in the PHP dir to copied to the root Windows dir.
phpinfo will clearly explain the below: Configuration File (php.ini) Path C:\Windows
Logical sense will explain that php wants to load a config located in the Windows dir. :-)
I have a Fascinate as well, and had to change the phone's USB communication mode from MODEM to PDA. Use:
**USBUI
(**87284
) to change both USB and UART to PDA mode. I also had to disconnect and reconnect the USB cable. Once Windows re-recognized the device again, "adb devices" started returning my device.
BTW if you use CDMA workshop or the equivalent, you will need to switch the setting back to MODEM.
You can use axis
:
> axis(side=1, at=c(0:23))
That is, something like this:
plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()
The keyup event will detect if the user has cleared the box as well (i.e. backspace raises the event but backspace does not raise the keypress event in IE)
$("#inputname").keyup(function() {
if (!this.value) {
alert('The box is empty');
}});
Here's what i do to FORCE UNLOCK FOR some locked tables in MySQL
1) Enter MySQL
mysql -u your_user -p
2) Let's see the list of locked tables
mysql> show open tables where in_use>0;
3) Let's see the list of the current processes, one of them is locking your table(s)
mysql> show processlist;
4) Let's kill one of these processes
mysql> kill put_process_id_here;
if your using @Aspect an option is add this method inside your Aspect and send the JoinPoint and the name of parameter you need.
private Object getParameter(ProceedingJoinPoint joinPoint, String parameterName) {
Object valueParameter = null;
if (Objects.nonNull(joinPoint) && joinPoint.getSignature() instanceof MethodSignature
&& Objects.nonNull(parameterName) ) {
MethodSignature method = (MethodSignature)joinPoint.getSignature();
String[] parameters = method.getParameterNames();
for (int t = 0; t< parameters.length; t++) {
if( Objects.nonNull(parameters[t]) && parameters[t].equals(parameterName)) {
Object[] obj = joinPoint.getArgs();
valueParameter = obj[t];
}
}
}
return valueParameter;
}
and the call example:
Object parameterObject = getParameter(joinPoint, "nameClient");
if ( Objects.nonNull(parameterObject) ) {
String parametro = String.valueOf(parameterObject);
}
Only need know the type of object for convert
Based up the OP's original request to be able to called a stored proc like this...
using (Entities context = new Entities())
{
context.MyStoreadProcedure(Parameters);
}
Mindless passenger has a project that allows you to call a stored proc from entity frame work like this....
using (testentities te = new testentities())
{
//-------------------------------------------------------------
// Simple stored proc
//-------------------------------------------------------------
var parms1 = new testone() { inparm = "abcd" };
var results1 = te.CallStoredProc<testone>(te.testoneproc, parms1);
var r1 = results1.ToList<TestOneResultSet>();
}
... and I am working on a stored procedure framework (here) which you can call like in one of my test methods shown below...
[TestClass]
public class TenantDataBasedTests : BaseIntegrationTest
{
[TestMethod]
public void GetTenantForName_ReturnsOneRecord()
{
// ARRANGE
const int expectedCount = 1;
const string expectedName = "Me";
// Build the paraemeters object
var parameters = new GetTenantForTenantNameParameters
{
TenantName = expectedName
};
// get an instance of the stored procedure passing the parameters
var procedure = new GetTenantForTenantNameProcedure(parameters);
// Initialise the procedure name and schema from procedure attributes
procedure.InitializeFromAttributes();
// Add some tenants to context so we have something for the procedure to return!
AddTenentsToContext(Context);
// ACT
// Get the results by calling the stored procedure from the context extention method
var results = Context.ExecuteStoredProcedure(procedure);
// ASSERT
Assert.AreEqual(expectedCount, results.Count);
}
}
internal class GetTenantForTenantNameParameters
{
[Name("TenantName")]
[Size(100)]
[ParameterDbType(SqlDbType.VarChar)]
public string TenantName { get; set; }
}
[Schema("app")]
[Name("Tenant_GetForTenantName")]
internal class GetTenantForTenantNameProcedure
: StoredProcedureBase<TenantResultRow, GetTenantForTenantNameParameters>
{
public GetTenantForTenantNameProcedure(
GetTenantForTenantNameParameters parameters)
: base(parameters)
{
}
}
If either of those two approaches are any good?
Really, really, really check if the TCP/IP protocol is enabled in your local SQLEXPRESS instance.
Follow these steps to make sure:
If you have any problem, check this blog post for details, as it contains screenshots and much more info.
Also check if the "SQL Server Browser" windows service is activated and running:
That's it.
After I installed a fresh local SQLExpress, all I had to do was to enable TCP/IP and start the SQL Server Browser service.
Below a code I use to test the SQLEXPRESS local connection. Of course, you should change the IP, DatabaseName and user/password as needed.:
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JtdsSqlExpressInstanceConnect {
public static void main(String[] args) throws SQLException {
Connection conn = null;
ResultSet rs = null;
String url = "jdbc:jtds:sqlserver://127.0.0.1;instance=SQLEXPRESS;DatabaseName=master";
String driver = "net.sourceforge.jtds.jdbc.Driver";
String userName = "user";
String password = "password";
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, userName, password);
System.out.println("Connected to the database!!! Getting table list...");
DatabaseMetaData dbm = conn.getMetaData();
rs = dbm.getTables(null, null, "%", new String[] { "TABLE" });
while (rs.next()) { System.out.println(rs.getString("TABLE_NAME")); }
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.close();
rs.close();
}
}
}
And if you use Maven, add this to your pom.xml:
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.2.4</version>
</dependency>
This link goes to the best comparison chart around, directly from the Microsoft. It compares ALL aspects of all MS SQL server editions. To compare three editions you are asking about, just focus on the last three columns of every table in there.
Summary compiled from the above document:
* = contains the feature SQLEXPR SQLEXPRWT SQLEXPRADV ---------------------------------------------------------------------------- > SQL Server Core * * * > SQL Server Management Studio - * * > Distributed Replay – Admin Tool - * * > LocalDB - * * > SQL Server Data Tools (SSDT) - - * > Full-text and semantic search - - * > Specification of language in query - - * > some of Reporting services features - - *
Using id for this task is not an option in many cases. For example - table with twitter statuses. Here is a variant with specified timestamp field.
delete from table
where access_time >=
(
select access_time from
(
select access_time from table
order by access_time limit 150000,1
) foo
)
I created my own jQuery plugin after becoming frustrated that the existing shims would hide the placeholder on focus, which creates an inferior user experience and also does not match how Firefox, Chrome and Safari handle it. This is especially the case if you want an input to be focused when a page or popup first loads, while still showing the placeholder until text is entered.
git rebase -i HEAD^^^
Now mark the ones you want to amend with edit
or e
(replace pick
). Now save and exit.
Now make your changes, then
git add .
git rebase --continue
If you want to add an extra delete remove the options from the commit command. If you want to adjust the message, omit just the --no-edit
option.
VBA subs are no macros. A VBA sub can be a macro, but it is not a must.
The term "macro" is only used for recorded user actions. from these actions a code is generated and stored in a sub. This code is simple and do not provide powerful structures like loops, for example Do .. until, for .. next, while.. do, and others.
The more elegant way is, to design and write your own VBA code without using the macro features!
VBA is a object based and event oriented language. Subs, or bette call it "sub routines", are started by dedicated events. The event can be the pressing of a button or the opening of a workbook and many many other very specific events.
If you focus to VB6 and not to VBA, then you can state, that there is always a main-window or main form. This form is started if you start the compiled executable "xxxx.exe".
In VBA you have nothing like this, but you have a XLSM file wich is started by Excel. You can attach some code to the Workbook_Open event. This event is generated, if you open your desired excel file which is called a workbook. Inside the workbook you have worksheets.
It is useful to get more familiar with the so called object model of excel. The workbook has several events and methods. Also the worksheet has several events and methods.
In the object based model you have objects, that have events and methods. methods are action you can do with a object. events are things that can happen to an object. An objects can contain another objects, and so on. You can create new objects, like sheets or charts.
It is two problems - is the slashes the right places and is it a valid date. I would suggest you catch input changes and put the slashes in yourself. (annoying for the user)
The interesting problem is whether they put in a valid date and I would suggest exploiting how flexible js is:
function isValidDate(str) {_x000D_
var newdate = new Date();_x000D_
var yyyy = 2000 + Number(str.substr(4, 2));_x000D_
var mm = Number(str.substr(2, 2)) - 1;_x000D_
var dd = Number(str.substr(0, 2));_x000D_
newdate.setFullYear(yyyy);_x000D_
newdate.setMonth(mm);_x000D_
newdate.setDate(dd);_x000D_
return dd == newdate.getDate() && mm == newdate.getMonth() && yyyy == newdate.getFullYear();_x000D_
}_x000D_
console.log(isValidDate('jk'));//false_x000D_
console.log(isValidDate('290215'));//false_x000D_
console.log(isValidDate('290216'));//true_x000D_
console.log(isValidDate('292216'));//false
_x000D_
The manner I have used before is to use a wild color (a color no one in their right mind would use) for the BackColor and then set the transparency key to that.
this.BackColor = Color.LimeGreen;
this.TransparencyKey = Color.LimeGreen;
I'm using something like this and works very well:* :-)
(echo "set schema 'acme';" ; \
cat ~/git/soluvas-framework/schedule/src/main/resources/org/soluvas/schedule/tables_postgres.sql) \
| psql -Upostgres -hlocalhost quikdo_app_dev
Note: Linux/Mac/Bash only, though probably there's a way to do that in Windows/PowerShell too.
Search extension in
/etc/php5/apache2/php.ini
Simple way is generating code as bellow:
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
<style>_x000D_
table, td {_x000D_
border:1px solid black;_x000D_
}_x000D_
</style>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<p>Click on each tr element to alert its index position in the table:</p>_x000D_
<table>_x000D_
<tr onclick="myFunction(this)">_x000D_
<td>Click to show rowIndex</td>_x000D_
</tr>_x000D_
<tr onclick="myFunction(this)">_x000D_
<td>Click to show rowIndex</td>_x000D_
</tr>_x000D_
<tr onclick="myFunction(this)">_x000D_
<td>Click to show rowIndex</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
<script>_x000D_
function myFunction(x) {_x000D_
alert("Row index is: " + x.rowIndex);_x000D_
}_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Another alternative is that you are allowed to have multiple classes in a tag. Consider:
<div class="button big">This is a big button</div>
<div class="button small">This is a small button</div>
And the CSS:
.button {
/* all your common button styles */
}
.big {
height: 60px;
width: 100px;
}
.small {
height: 40px;
width: 70px;
}
and so on.
You can use the function ginv() (Moore-Penrose generalized inverse) in the MASS package
if you are making a RecyclerView and using an adapter, what worked for me was:
@Override
public void onBindViewHolder(ADAPTERVIEWHOLDER holder, int position) {
MODEL model = LIST.get(position);
holder.TEXTVIEW.setText(service.getTitle());
holder.TEXTVIEW.setText(service.getDesc());
Context context = holder.IMAGEVIEW.getContext();
Picasso.with(context).load(model.getImage()).into(holder.IMAGEVIEW);
}
Just for the record in modern times,
1 - Just have updated Xcode on your machine as you normally do
2 - Open terminal and
$ xcode-select --install
it will perform a short install of a minute or two.
3 - Launch Xcode. "New" "Project" ... you have to choose "Command line tool"
Note - confusingly this is under the "macOS" tab.
Select "C" language on the next screen...
4- You'll be asked to save the project somewhere on your desktop. The name you give the project here is just the name of the folder that will hold the project. It does not have any importance in the actual software.
5 - You're golden! You can now enjoy c with Mac and Xcode.
You should have look at http://en.wikipedia.org/wiki/Breadth-first_search first.
Below is a quick implementation, in which I used a list of list to represent the queue of paths.
# graph is in adjacent list representation
graph = {
'1': ['2', '3', '4'],
'2': ['5', '6'],
'5': ['9', '10'],
'4': ['7', '8'],
'7': ['11', '12']
}
def bfs(graph, start, end):
# maintain a queue of paths
queue = []
# push the first path into the queue
queue.append([start])
while queue:
# get the first path from the queue
path = queue.pop(0)
# get the last node from the path
node = path[-1]
# path found
if node == end:
return path
# enumerate all adjacent nodes, construct a new path and push it into the queue
for adjacent in graph.get(node, []):
new_path = list(path)
new_path.append(adjacent)
queue.append(new_path)
print bfs(graph, '1', '11')
Another approach would be maintaining a mapping from each node to its parent, and when inspecting the adjacent node, record its parent. When the search is done, simply backtrace according the parent mapping.
graph = {
'1': ['2', '3', '4'],
'2': ['5', '6'],
'5': ['9', '10'],
'4': ['7', '8'],
'7': ['11', '12']
}
def backtrace(parent, start, end):
path = [end]
while path[-1] != start:
path.append(parent[path[-1]])
path.reverse()
return path
def bfs(graph, start, end):
parent = {}
queue = []
queue.append(start)
while queue:
node = queue.pop(0)
if node == end:
return backtrace(parent, start, end)
for adjacent in graph.get(node, []):
if node not in queue :
parent[adjacent] = node # <<<<< record its parent
queue.append(adjacent)
print bfs(graph, '1', '11')
The above codes are based on the assumption that there's no cycles.
While Andriy's proposal will work well for INSERTs of a small number of records, full table scans will be done on the final join as both 'enumerated' and '@new_super' are not indexed, resulting in poor performance for large inserts.
This can be resolved by specifying a primary key on the @new_super table, as follows:
DECLARE @new_super TABLE (
row_num INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
super_id int
);
This will result in the SQL optimizer scanning through the 'enumerated' table but doing an indexed join on @new_super to get the new key.
I had a similar issue and none of the answers worked for me. Maybe someone finds my solution helpful. In case you do not mind submitting on button click, only attaching to click event setting UseSubmitBehavior="false"
may be worth trying.
Modify the while loop as below. Declare s1 as String s1; one time outside the loop. To end the loop, simply use ctrl+z.
while (sc.hasNext())
{
s1 = sc.next();
System.out.println(s1);
System.out.print("Enter your sentence: ");
}
This is one way to do it:
SQL> set serveroutput on
SQL> CREATE OR REPLACE TYPE MyType AS VARRAY(200) OF VARCHAR2(50);
2 /
Type created
SQL> CREATE OR REPLACE PROCEDURE testing (t_in MyType) IS
2 BEGIN
3 FOR i IN 1..t_in.count LOOP
4 dbms_output.put_line(t_in(i));
5 END LOOP;
6 END;
7 /
Procedure created
SQL> DECLARE
2 v_t MyType;
3 BEGIN
4 v_t := MyType();
5 v_t.EXTEND(10);
6 v_t(1) := 'this is a test';
7 v_t(2) := 'A second test line';
8 testing(v_t);
9 END;
10 /
this is a test
A second test line
To expand on my comment to @dcp's answer, here's how you could implement the solution proposed there if you wanted to use an associative array:
SQL> CREATE OR REPLACE PACKAGE p IS
2 TYPE p_type IS TABLE OF VARCHAR2(50) INDEX BY BINARY_INTEGER;
3
4 PROCEDURE pp (inp p_type);
5 END p;
6 /
Package created
SQL> CREATE OR REPLACE PACKAGE BODY p IS
2 PROCEDURE pp (inp p_type) IS
3 BEGIN
4 FOR i IN 1..inp.count LOOP
5 dbms_output.put_line(inp(i));
6 END LOOP;
7 END pp;
8 END p;
9 /
Package body created
SQL> DECLARE
2 v_t p.p_type;
3 BEGIN
4 v_t(1) := 'this is a test of p';
5 v_t(2) := 'A second test line for p';
6 p.pp(v_t);
7 END;
8 /
this is a test of p
A second test line for p
PL/SQL procedure successfully completed
SQL>
This trades creating a standalone Oracle TYPE (which cannot be an associative array) with requiring the definition of a package that can be seen by all in order that the TYPE it defines there can be used by all.
just add your .jar file in applet tag as an attribute as shown below:
<applet
code="file.class"
archive="file.jar"
height=550
width=1100>
</applet>