Based on kynan's answer, here are the same aliases, modified so they can handle spaces and initial dashes in filenames:
accept-ours = "!f() { [ -z \"$@\" ] && set - '.'; git checkout --ours -- \"$@\"; git add -u -- \"$@\"; }; f"
accept-theirs = "!f() { [ -z \"$@\" ] && set - '.'; git checkout --theirs -- \"$@\"; git add -u -- \"$@\"; }; f"
I just set the timezone with Matthias Bauch answer And it worked for me. else it was adding 18:30 min more.
let cal: NSCalendar = NSCalendar.currentCalendar()
cal.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let newDate: NSDate = cal.dateBySettingHour(1, minute: 0, second: 0, ofDate: NSDate(), options: NSCalendarOptions())!
You use ttk.Frame
, bg
option does not work for it. You should create style and apply it to the frame.
from tkinter import *
from tkinter.ttk import *
root = Tk()
s = Style()
s.configure('My.TFrame', background='red')
mail1 = Frame(root, style='My.TFrame')
mail1.place(height=70, width=400, x=83, y=109)
mail1.config()
root.mainloop()
To automate this, you can use any script or app that can send a string to a socket. I personally like nc (netcat) under cygwin. As I said before, I use it like this:
$ echo kill | nc -w 2 localhost 5554
(that means to send "kill" string to the port 5554 on localhost, and terminate netcat after 2 seconds.)
The problem as I understand it is as follows. You have several libraries, some static, some dynamic and some both static and dynamic. gcc's default behavior is to link "mostly dynamic". That is, gcc links to dynamic libraries when possible but otherwise falls back to static libraries. When you use the -static option to gcc the behavior is to only link static libraries and exit with an error if no static library can be found, even if there is an appropriate dynamic library.
Another option, which I have on several occasions wished gcc had, is what I call -mostly-static and is essentially the opposite of -dynamic (the default). -mostly-static would, if it existed, prefer to link against static libraries but would fall back to dynamic libraries.
This option does not exist but it can be emulated with the following algorithm:
Constructing the link command line with out including -static.
Iterate over the dynamic link options.
Accumulate library paths, i.e. those options of the form -L<lib_dir> in a variable <lib_path>
For each dynamic link option, i.e. those of the form -l<lib_name>, run the command gcc <lib_path> -print-file-name=lib<lib_name>.a and capture the output.
If the command prints something other than what you passed, it will be the full path to the static library. Replace the dynamic library option with the full path to the static library.
Rinse and repeat until you've processed the entire link command line. Optionally the script can also take a list of library names to exclude from static linking.
The following bash script seems to do the trick:
#!/bin/bash
if [ $# -eq 0 ]; then
echo "Usage: $0 [--exclude <lib_name>]. . . <link_command>"
fi
exclude=()
lib_path=()
while [ $# -ne 0 ]; do
case "$1" in
-L*)
if [ "$1" == -L ]; then
shift
LPATH="-L$1"
else
LPATH="$1"
fi
lib_path+=("$LPATH")
echo -n "\"$LPATH\" "
;;
-l*)
NAME="$(echo $1 | sed 's/-l\(.*\)/\1/')"
if echo "${exclude[@]}" | grep " $NAME " >/dev/null; then
echo -n "$1 "
else
LIB="$(gcc $lib_path -print-file-name=lib"$NAME".a)"
if [ "$LIB" == lib"$NAME".a ]; then
echo -n "$1 "
else
echo -n "\"$LIB\" "
fi
fi
;;
--exclude)
shift
exclude+=(" $1 ")
;;
*) echo -n "$1 "
esac
shift
done
echo
For example:
mostlyStatic gcc -o test test.c -ldl -lpthread
on my system returns:
gcc -o test test.c "/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/libdl.a" "/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/libpthread.a"
or with an exclusion:
mostlyStatic --exclude dl gcc -o test test.c -ldl -lpthread
I then get:
gcc -o test test.c -ldl "/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/libpthread.a"
Static fields and methods are connected to the class itself and not its instances. If you have a class A
, a 'normal' method b
, and a static method c
, and you make an instance a
of your class A
, the calls to A.c()
and a.b()
are valid. Method c()
has no idea which instance is connected, so it cannot use non-static fields.
The solution for you is that you either make your fields static or your methods non-static. You main could look like this then:
class Programm {
public static void main(String[] args) {
Programm programm = new Programm();
programm.start();
}
public void start() {
// can now access non-static fields
}
}
There are two ways to add one dictionary to another.
Update (modifies orig
in place)
orig.update(extra) # Python 2.7+
orig |= extra # Python 3.9+
Merge (creates a new dictionary)
# Python 2.7+
dest = collections.ChainMap(orig, extra)
dest = {k: v for d in (orig, extra) for (k, v) in d.items()}
# Python 3
dest = {**orig, **extra}
dest = {**orig, 'D': 4, 'E': 5}
# Python 3.9+
dest = orig | extra
Note that these operations are noncommutative. In all cases, the latter is the winner. E.g.
orig = {'A': 1, 'B': 2} extra = {'A': 3, 'C': 3} dest = orig | extra # dest = {'A': 3, 'B': 2, 'C': 3} dest = extra | orig # dest = {'A': 1, 'B': 2, 'C': 3}
It is also important to note that only from Python 3.7 (and CPython 3.6)
dict
s are ordered. So, in previous versions, the order of the items in the dictionary may vary.
I had a similar problem. The incorrect credentials were cached in OS X's key-chain.
Check out: https://help.github.com/articles/updating-credentials-from-the-osx-keychain
Though this thread is old but still, I feel I should post a good answer from this stackoverflow answer.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
This sure saved me after hours of trying to get things to work. I hope this helps someone.
useEffect has its own state/lifecycle, it will not update until you pass a function in parameters or effect destroyed.
object and array spread or rest will not work inside useEffect.
React.useEffect(() => {
console.log("effect");
(async () => {
try {
let result = await fetch("/query/countries");
const res = await result.json();
let result1 = await fetch("/query/projects");
const res1 = await result1.json();
let result11 = await fetch("/query/regions");
const res11 = await result11.json();
setData({
countries: res,
projects: res1,
regions: res11
});
} catch {}
})(data)
}, [setData])
# or use this
useEffect(() => {
(async () => {
try {
await Promise.all([
fetch("/query/countries").then((response) => response.json()),
fetch("/query/projects").then((response) => response.json()),
fetch("/query/regions").then((response) => response.json())
]).then(([country, project, region]) => {
// console.log(country, project, region);
setData({
countries: country,
projects: project,
regions: region
});
})
} catch {
console.log("data fetch error")
}
})()
}, [setData]);
(SELECT users.username AS posted_by,
users.id AS posted_by_id
FROM users
WHERE users.id = posts.posted_by)
Here you using sub-query but this sub-query must return only one column. Separate it otherwise it will shows error.
TL/DR: GO here-> https://codepen.io/sosuke/pen/Pjoqqp
Explanation:
I'm assuming you have html something like this:
<img src="/img/source.svg" class="myClass">
Definitely go the filter route, ie. your svg is most likely black or white. You can apply a filter to get it to be whatever color you want, for example, I have a black svg that I want mint green. I first invert it to be white (which is technically all RGB colors on full) then play with the hue saturation etc. To get it right:
filter: invert(86%) sepia(21%) saturate(761%) hue-rotate(92deg) brightness(99%) contrast(107%);
Even better is that you could just use a tool to convert the hex you want into a filter for you: https://codepen.io/sosuke/pen/Pjoqqp
SQL Server doesn't allow you to pass parameters to a procedure that you haven't defined. I think the closest you can get to this sort of design is to use optional parameters like so:
CREATE PROCEDURE GetTaskEvents
@TaskName varchar(50),
@ID int = NULL
AS
BEGIN
-- SP Logic
END;
You would need to include every possible parameter that you might use in the definition. Then you'd be free to call the procedure either way:
EXEC GetTaskEvents @TaskName = 'TESTTASK', @ID = 2;
EXEC GetTaskEvents @TaskName = 'TESTTASK'; -- @ID gets NULL here
I hope this example will be helpful for you)
print(type(None)) # NoneType
So, you can check type of the variable name
# Example
name = 12 # name = None
if type(name) is type(None):
print("Can't find name")
else:
print(name)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GuessTheDay
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the Day Number ");
int day = int.Parse(Console.ReadLine());
Console.WriteLine(" Enter The Month");
int month = int.Parse(Console.ReadLine());
Console.WriteLine("Enter Year ");
int year = int.Parse(Console.ReadLine());
DateTime mydate = new DateTime(year,month,day);
string formatteddate = string.Format("{0:dddd}", mydate);
Console.WriteLine("The day should be " + formatteddate);
}
}
}
You can presumably pass-in, as a parameter, a delegate which will convert from string to T.
In your example a credit card is expired on 6/2008.
Without knowing what you are doing I cannot say definitively you should not be validating ahead of time but be aware that sometimes business rules defy all logic.
For example, where I used to work they often did not process a card at all or would continue on transaction failure simply so they could contact the customer and get a different card.
Array elements in Java are initialized to default values when created. For numbers this means they are initialized to 0, for references they are null and for booleans they are false.
To fill the array with something else you can use Arrays.fill() or as part of the declaration
int[] a = new int[] {0, 0, 0, 0};
There are no shortcuts in Java to fill arrays with arithmetic series as in some scripting languages.
In my view the main difference is who says if the tests succeed or fail.
A functional test tests that the system meets predefined requirements. It is carried out and checked by the people responsible for developing the system.
An acceptance test is signed off by the users. Ideally the users will say what they want to test but in practice it is likely to be a sunset of a functional test as users don't invest enough time. Note that this view is from the business users I deal with other sets of users e.g. aviation and other safety critical might well not have this difference,
If you only want to suppress a warning in a single line of code, you can use the suppress
warning specifier:
#pragma warning(suppress: 4101)
// here goes your single line of code where the warning occurs
For a single line of code, this works the same as writing the following:
#pragma warning(push)
#pragma warning(disable: 4101)
// here goes your code where the warning occurs
#pragma warning(pop)
None of the methods presented here worked for me. What finally worked was to set the DevelopmentServerPort to 0 in the .csproj file:
<WebProjectProperties>
<UseIIS>True</UseIIS>
<AutoAssignPort>True</AutoAssignPort>
<DevelopmentServerPort>0</DevelopmentServerPort>
<DevelopmentServerVPath>/</DevelopmentServerVPath>
<IISUrl>http://localhost:52973/</IISUrl>
<NTLMAuthentication>False</NTLMAuthentication>
<UseCustomServer>False</UseCustomServer>
<CustomServerUrl>
</CustomServerUrl>
<SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
</WebProjectProperties>
Is this what you are after? Just index the element and assign a new value.
A[2,1]=150
A
Out[345]:
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 150, 11, 12],
[13, 14, 15, 16]])
Use numeric(n,n) where n has enough resolution to round to 1.00. For instance:
declare @discount numeric(9,9)
, @quantity int
select @discount = 0.999999999
, @quantity = 10000
select convert(money, @discount * @quantity)
public class initials {
public static void main (String [] args) {
char initialA = 'M';
char initialB = 'P';
char initialC = 'T';
System.out.println("" + initialA + initialB + initialC );
}
}
In Ubuntu 12.x, I added the following lines in $HOME/.wgetrc
http_proxy = http://uname:[email protected]:8080
use_proxy = on
For quick and dirty, you can do
import java.awt.Color;
private Color dropPrecision(Color c,int threshold){
return new Color((c.getRed()/threshold),
(c.getGreen()/threshold),
(c.getBlue()/threshold));
}
public boolean inThreshold(Color _1,Color _2,int threshold){
return dropPrecision(_1,threshold)==dropPrecision(_2,threshold);
}
making use of integer division to quantize the colors.
For a Progressive Web App I wrote a script to easily load javascript files async on demand. Scripts are only loaded once. So you can call loadScript as often as you want for the same file. It wouldn't be loaded twice. This script requires JQuery to work.
For example:
loadScript("js/myscript.js").then(function(){
// Do whatever you want to do after script load
});
or when used in an async function:
await loadScript("js/myscript.js");
// Do whatever you want to do after script load
In your case you may execute this after document ready:
$(document).ready(async function() {
await loadScript("js/myscript.js");
// Do whatever you want to do after script is ready
});
Function for loadScript:
function loadScript(src) {
return new Promise(function (resolve, reject) {
if ($("script[src='" + src + "']").length === 0) {
var script = document.createElement('script');
script.onload = function () {
resolve();
};
script.onerror = function () {
reject();
};
script.src = src;
document.body.appendChild(script);
} else {
resolve();
}
});
}
Benefit of this way:
An Ad-Hoc query is:
In MS Windows the temporary directory is set by the environment variable TEMP
. In XP, the temporary directory was set per-user as Local Settings\Temp.
If you change your TEMP environment variable to C:\temp
, then you get the same when you run :
System.out.println(System.getProperty("java.io.tmpdir"));
You can use .sortBy
, it will always return an ascending list:
_.sortBy([2, 3, 1], function(num) {
return num;
}); // [1, 2, 3]
But you can use the .reverse method to get it descending:
var array = _.sortBy([2, 3, 1], function(num) {
return num;
});
console.log(array); // [1, 2, 3]
console.log(array.reverse()); // [3, 2, 1]
Or when dealing with numbers add a negative sign to the return to descend the list:
_.sortBy([-3, -2, 2, 3, 1, 0, -1], function(num) {
return -num;
}); // [3, 2, 1, 0, -1, -2, -3]
Under the hood .sortBy
uses the built in .sort([handler])
:
// Default is ascending:
[2, 3, 1].sort(); // [1, 2, 3]
// But can be descending if you provide a sort handler:
[2, 3, 1].sort(function(a, b) {
// a = current item in array
// b = next item in array
return b - a;
});
Go to the folder in which eclipse is installed then open readme folder followed by the readme txt file. Here you will find all the info you need.
Can also do it this way but other ways seem better, this comes in handy if you only need it the once.
onkeyup="this.value = this.value.toUpperCase();"
here is how you can do it through list comprehension, but this will waste a little bit of your computer's memory as line.strip() has been called twice.
with open('textfile.txt') as file:
lines =[
line.strip()
for line in file
if line.strip() != '']
print("number of lines = {}".format(len(lines)))
[^]
( within [ ] ) is negation in regular expression whereas ^
is "begining of string"
[^a-z]
matches any single character that is not from "a" to "z"
^[a-z]
means string starts with from "a" to "z"
Just reboot the Ec2 Instance once you applied Rules
I've only ever seen this error on Windows and what it seems to mean is that something blocked git from modifying a file at the moment when it tried to a apply a patch.
Windows tends to give processes exclusive access to files when it shouldn't really be necessary, in the past virus checkers have been one source of suspicion but I've never proved this conclusively.
Probably the easiest thing to do is to abort and try again, hoping that it doesn't happen the next time.
git rebase --abort
You can attempt to use git apply
and knowledge of what commit git was actually trying to do before doing a git rebase --continue
but in all honesty I wouldn't recommend this. Most of the times I've seen this tried there's been a better than evens chance that something gets accidentally missed or messed up.
I would go about it somewhat like this:
<html>
<head>
<title>Print Test Page</title>
<script>
printDivCSS = new String ('<link href="myprintstyle.css" rel="stylesheet" type="text/css">')
function printDiv(divId) {
window.frames["print_frame"].document.body.innerHTML=printDivCSS + document.getElementById(divId).innerHTML;
window.frames["print_frame"].window.focus();
window.frames["print_frame"].window.print();
}
</script>
</head>
<body>
<h1><b><center>This is a test page for printing</center></b><hr color=#00cc00 width=95%></h1>
<b>Div 1:</b> <a href="javascript:printDiv('div1')">Print</a><br>
<div id="div1">This is the div1's print output</div>
<br><br>
<b>Div 2:</b> <a href="javascript:printDiv('div2')">Print</a><br>
<div id="div2">This is the div2's print output</div>
<br><br>
<b>Div 3:</b> <a href="javascript:printDiv('div3')">Print</a><br>
<div id="div3">This is the div3's print output</div>
<iframe name="print_frame" width="0" height="0" frameborder="0" src="about:blank"></iframe>
</body>
</html>
Just as zero is a number - just a number that represents none - an empty list is still a list, just a list with nothing in it. null
is no list at all; it's therefore different from an empty list.
Similarly, a list that contains null items is a list, and is not an empty list. Because it has items in it; it doesn't matter that those items are themselves null. As an example, a list with three null values in it, and nothing else: what is its length? Its length is 3. The empty list's length is zero. And, of course, null doesn't have a length.
If using in fragment then simply write
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
// Do something on UiThread
}
});
Chrome and other Browser restrict the access of a server to local files due to security reasons. However you can open the browser in allowed access mode. Just open the terminal and go to the folder where chrome.exe is stored and write the following command.
chrome.exe --allow-file-access-from-files
This way, However, didn't work for me so I made a different route for every file in a particular directory. Therefore, going to that path meant opening that file.
function getroutes(list){
list.forEach(function(element) {
app.get("/"+ element, function(req, res) {
res.sendFile(__dirname + "/public/extracted/" + element);
});
});
}
I called this function passing the list of filename in the directory __dirname/public/extracted
and it created a different route for each filename which I was able to render on server side.
#import <sys/socket.h>
#import <net/if_dl.h>
#import <ifaddrs.h>
#import <sys/xattr.h>
#define IFT_ETHER 0x6
...
- (NSString*)macAddress
{
NSString* result = nil;
char* macAddressString = (char*)malloc(18);
if (macAddressString != NULL)
{
strcpy(macAddressString, "");
struct ifaddrs* addrs = NULL;
struct ifaddrs* cursor;
if (getifaddrs(&addrs) == 0)
{
cursor = addrs;
while (cursor != NULL)
{
if ((cursor->ifa_addr->sa_family == AF_LINK) && (((const struct sockaddr_dl*)cursor->ifa_addr)->sdl_type == IFT_ETHER) && strcmp("en0", cursor->ifa_name) == 0)
{
const struct sockaddr_dl* dlAddr = (const struct sockaddr_dl*) cursor->ifa_addr;
const unsigned char* base = (const unsigned char*)&dlAddr->sdl_data[dlAddr->sdl_nlen];
for (NSInteger index = 0; index < dlAddr->sdl_alen; index++)
{
char partialAddr[3];
sprintf(partialAddr, "%02X", base[index]);
strcat(macAddressString, partialAddr);
}
}
cursor = cursor->ifa_next;
}
}
result = [[[NSString alloc] initWithUTF8String:macAddressString] autorelease];
free(macAddressString);
}
return result;
}
Probably the easiest way to explore your ElasticSearch cluster is to use elasticsearch-head.
You can install it by doing:
cd elasticsearch/
./bin/plugin -install mobz/elasticsearch-head
Then (assuming ElasticSearch is already running on your local machine), open a browser window to:
http://localhost:9200/_plugin/head/
Alternatively, you can just use curl
from the command line, eg:
Check the mapping for an index:
curl -XGET 'http://127.0.0.1:9200/my_index/_mapping?pretty=1'
Get some sample docs:
curl -XGET 'http://127.0.0.1:9200/my_index/_search?pretty=1'
See the actual terms stored in a particular field (ie how that field has been analyzed):
curl -XGET 'http://127.0.0.1:9200/my_index/_search?pretty=1' -d '
{
"facets" : {
"my_terms" : {
"terms" : {
"size" : 50,
"field" : "foo"
}
}
}
}
More available here: http://www.elasticsearch.org/guide
By far the easiest way of writing curl
-style commands for Elasticsearch is the Sense plugin in Marvel.
It comes with source highlighting, pretty indenting and autocomplete.
Note: Sense was originally a standalone chrome plugin but is now part of the Marvel project.
For ListBox / DropDown in MVC5 - i've found this to work for me sofar:
in Model:
[Required(ErrorMessage = "- Select item -")]
public List<string> SelectedItem { get; set; }
public List<SelectListItem> AvailableItemsList { get; set; }
in View:
@Html.ListBoxFor(model => model.SelectedItem, Model.AvailableItemsList)
@Html.ValidationMessageFor(model => model.SelectedItem, "", new { @class = "text-danger" })
string newString = url.Substring(18, (url.LastIndexOf(".") - 18))
If you have a small database and you want to version the entire thing, this batch script might help. It detaches, compresses, and checks a MSSQL database MDF file in to Subversion.
If you mostly want to version your schema and just have a small amount of reference data, you can possibly use SubSonic Migrations to handle that. The benefit there is that you can easily migrate up or down to any specific version.
If is ok for you to index the array you can do this:
<form>
<input type="text" class="form-control" placeholder="Titel" name="levels[0][level]">
<input type="text" class="form-control" placeholder="Titel" name="levels[0][build_time]">
<input type="text" class="form-control" placeholder="Titel" name="levels[1][level]">
<input type="text" class="form-control" placeholder="Titel" name="levels[1][build_time]">
<input type="text" class="form-control" placeholder="Titel" name="levels[2][level]">
<input type="text" class="form-control" placeholder="Titel" name="levels[2][build_time]">
</form>
... to achieve that:
[levels] => Array (
[0] => Array (
[level] => 1
[build_time] => 2
)
[1] => Array (
[level] => 234
[build_time] => 456
)
[2] => Array (
[level] => 111
[build_time] => 222
)
)
But if you remove one pair of inputs (dynamically, I suppose) from the middle of the form then you'll get holes in your array, unless you update the input names...
you should count years by following way :-
select cast(datediff(DAY, '2000-03-01 10:00:01', '2013-03-01 10:00:00') / (365.23076923074) as int) as 'Age'
it's very easy...
OP is using python, but in javascript (something to be careful of since the syntaxes are similar.
// only replaces the first instance of ' ' with '_'
"one two three".replace(' ', '_');
=> "one_two three"
// replaces all instances of ' ' with '_'
"one two three".replace(/\s/g, '_');
=> "one_two_three"
If you have already installed 2.2.5 and set as current ruby version, but still showing the same error even if the Ruby version 2.3.0 is not even installed, then just install the bundler.
gem install bundler
and then:
bundle install
To send a reload call to a React-Native app running in a android device: adb shell input keyboard text "rr"
Avoid nullable unique constraints. You can always put the column in a new table, make it non-null and unique and then populate that table only when you have a value for it. This ensures that any key dependency on the column can be correctly enforced and avoids any problems that could be caused by nulls.
This should do it if memory serves:
List<MyType> fixed = Arrays.asList(new MyType[100]);
Your BlockID
function uses the undefined variable images
, which will lead to an error. Also, you should not use an Array
here - JavaScripts key-value-maps are plain objects:
function BlockID() {
return {
"s": "Images/Block_01.png",
"g": "Images/Block_02.png",
"C": "Images/Block_03.png",
"d": "Images/Block_04.png"
};
}
SELECT * FROM TableName WHERE CHARINDEX('''',ColumnName) > 0
When you have column with large amount of nvarchar data and millions of records, general 'LIKE' kind of search using percentage symbol will degrade the performance of the SQL operation.
While CHARINDEX inbuilt TSQL function is much more faster and there won't be any performance loss.
Reference SO post for comparative view.
The MACAddress property of the Win32_NetworkAdapterConfiguration WMI class can provide you with an adapter's MAC address. (System.Management Namespace)
MACAddress
Data type: string
Access type: Read-only
Media Access Control (MAC) address of the network adapter. A MAC address is assigned by the manufacturer to uniquely identify the network adapter.
Example: "00:80:C7:8F:6C:96"
If you're not familiar with the WMI API (Windows Management Instrumentation), there's a good overview here for .NET apps.
WMI is available across all version of windows with the .Net runtime.
Here's a code example:
System.Management.ManagementClass mc = default(System.Management.ManagementClass);
ManagementObject mo = default(ManagementObject);
mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (var mo in moc) {
if (mo.Item("IPEnabled") == true) {
Adapter.Items.Add("MAC " + mo.Item("MacAddress").ToString());
}
}
An alternative is to use line-height
:
http://jsfiddle.net/DjT37/
.bigbox{
height:40px;
line-height:40px;
padding:0 5px;
}
This tends to be more consistent when you want a specific height as you don't need to calculate padding based on font-size and desired height, etc.
OK, very obvious answer here... basically relative position is relative to previous element or window, while absolute don't care about the other elements unless it's a parent if you using top and left...
Look at the example I create for you to show the differences...
Also you can see it in action, using the css I create for you, you can see how absolute and relative positions behave:
.parent {_x000D_
display: inline-block;_x000D_
width: 180px;_x000D_
height: 160px;_x000D_
border: 1px solid black;_x000D_
}_x000D_
_x000D_
.black {_x000D_
position: relative;_x000D_
width: 100px;_x000D_
height: 30px;_x000D_
margin: 5px;_x000D_
border: 1px solid black;_x000D_
}_x000D_
_x000D_
.red {_x000D_
width: 100px;_x000D_
height: 30px;_x000D_
margin: 5px;_x000D_
top: 16px;_x000D_
background: red;_x000D_
border: 1px solid red;_x000D_
}_x000D_
_x000D_
.red-1 {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.red-2 {_x000D_
position: absolute;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="black">_x000D_
</div>_x000D_
<div class="red red-1">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="parent">_x000D_
<div class="black">_x000D_
</div>_x000D_
<div class="red red-2">_x000D_
</div>_x000D_
</div>
_x000D_
You asked about performance. See this perf test comparing 'concat', '+' and 'join' - in short the + operator wins by far.
If you absolutely must use HTML to give your text color, you have to use the (deprecated) <font>
-tag:
<h2><font color="#006699">Process Report</font></h2>
But otherwise, I strongly recommend you to do as rekire said: use CSS.
Wow! when you use src
then src
of searchPic
must be used also.
document["pic1"].src = searchPic.src
looks better
The error is caused by constrains automatically created from autoresizing mask, they are created because UIView property translatesAutoresizingMaskIntoConstraints is true by default.
Consider using BoxView to get rid of all manual constraint creation boilerplate, and make your code concize and readable. To make layout in question with BoxView is very easy:
boxView.items = [
new_view.boxed.centerX().centerY().relativeWidth(1.0).relativeHeight(1.0)
]
SELECT CAST(FLOOR(CAST(GETDATE() AS float)) as datetime)
or
SELECT CONVERT(datetime,FLOOR(CONVERT(float,GETDATE())))
you can add the Path to coinhsl lib to LD_LIBRARY_PATH
variable. May be that will help.
export LD_LIBRARY_PATH=/xx/yy/zz:$LD_LIBRARY_PATH
where /xx/yy/zz
represent the path to coinhsl
lib.
Go to services (services.msc) and restart the services in the image and then try to connect.
These are ALL great answers if you want to work that hard. But my guess is that you already have the items you want for the list coming from a databound element, and only want to add to the top of that list the "Hey, dude - pick one!" option. Assuming that is the case...
Here's the EASY Answer. And it ALWAYS works...
Now you will get a Drop Down with all of your data items in it, PRECEDED BY your "Select an Item" statement made in the manual item. Try giving it a default value if possible, this will eliminate any errors you may encounter. The default is Zero, so if zero is not a problem, then leave it alone, if zero IS a problem, replace the default zero in the item with something that will NOT crash your code.
And stop working so hard...that's what Visual Studio is for.
I believe there is a simpler solution.
You must use Html.Hidden
instead of Html.HiddenFor
. Look:
@Html.Hidden("CRN", ViewData["crn"]);
This will create an INPUT
tag of type="hidden"
, with id="CRN"
and name="CRN"
, and the correct value inside the value
attribute.
Hope it helps!
If your log4j.properties or log4j.xml file not found under src/main/resources use this PropertyConfigurator.configure("log4j.xml");
PropertyConfigurator.configure("log4j.xml");
Logger logger = LoggerFactory.getLogger(MyClass.class);
logger.error(message);
The next()
method (offcial doc here) simply move the pointer of the result rows set to the next row (if it can). Anyway you can read this from the offcial doc as well:
Moves the cursor down one row from its current position.
This method return true if there's another row or false otherwise.
There is no guarantee that your threads are executing simultaneously regardless of any trivial example anyone else posts. If your OS only gives the java process one processor to work on, your java threads will still be scheduled for each time slice in a round robin fashion. Meaning, no two will ever be executing simultaneously, but the work they do will be interleaved. You can use monitoring tools like Java's Visual VM (standard in the JDK) to observe the threads executing in a Java process.
My problem turned out to be that I was assigning as document.getElementById("myinput").Value = '1';
Notice the capital V in Value? Once I changed it to small case, i.e., value, the data started posting. Odd as it was not giving any JavaScript errors either.
FYI
PyQt is now available on all platforms via conda!
Useconda install pyqt
to get these #Python bindings for the Qt framework. @ 1:02 PM - 1 May 2014
System.exit(ABORT); Quit's the process immediately.
Is it possible to make a search by
querySelectorAll
using multiple unrelated conditions?
Yes, because querySelectorAll
accepts full CSS selectors, and CSS has the concept of selector groups, which lets you specify more than one unrelated selector. For instance:
var list = document.querySelectorAll("form, p, legend");
...will return a list containing any element that is a form
or p
or legend
.
CSS also has the other concept: Restricting based on more criteria. You just combine multiple aspects of a selector. For instance:
var list = document.querySelectorAll("div.foo");
...will return a list of all div
elements that also (and) have the class foo
, ignoring other div
elements.
You can, of course, combine them:
var list = document.querySelectorAll("div.foo, p.bar, div legend");
...which means "Include any div
element that also has the foo
class, any p
element that also has the bar
class, and any legend
element that's also inside a div
."
If you're doing this to several fields, or doing it quite often, then perhaps a plugin is the answer.
Here's the beginnings of a jQuery plugin that formats the value of a field to two decimal places.
It is triggered by the onchange event of the field. You may want something different.
<script type="text/javascript">
// mini jQuery plugin that formats to two decimal places
(function($) {
$.fn.currencyFormat = function() {
this.each( function( i ) {
$(this).change( function( e ){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(2);
});
});
return this; //for chaining
}
})( jQuery );
// apply the currencyFormat behaviour to elements with 'currency' as their class
$( function() {
$('.currency').currencyFormat();
});
</script>
<input type="text" name="one" class="currency"><br>
<input type="text" name="two" class="currency">
I used Windows authentication to connect to local database .mdf file and my local server was sql server 2014. My problem solved using this connection string:
string sqlString = " Data Source = (LocalDB)\\MSSQLLocalDB;" + "AttachDbFilename = F:\\.........\\myDatabase.mdf; Integrated Security = True; Connect Timeout = 30";
Idiomatic Matlab plot(x1,y1,x2,y2)
can be translated in R with ggplot2
for example in this way:
x1 <- seq(1,10,.2)
df1 <- data.frame(x=x1,y=log(x1),type="Log")
x2 <- seq(1,10)
df2 <- data.frame(x=x2,y=cumsum(1/x2),type="Harmonic")
df <- rbind(df1,df2)
library(ggplot2)
ggplot(df)+geom_line(aes(x,y,colour=type))
Inspired by Tingting Zhao's Dual line plots with different range of x-axis Using ggplot2.
A simple solution is to use Microsoft ASP.NET Web API 2.2 Client
from NuGet.
Then you can simply do this and it'll serialize the object to JSON and set the Content-Type
header to application/json; charset=utf-8
:
var data = new
{
name = "Foo",
category = "article"
};
var client = new HttpClient();
client.BaseAddress = new Uri(baseUri);
client.DefaultRequestHeaders.Add("token", token);
var response = await client.PostAsJsonAsync("", data);
If you run your playbook with ansible-playbook -vvv
you'll see the actual command being run, so you can check whether the key is actually being included in the ssh command (and you might discover that the problem was the wrong username rather than the missing key).
I agree with Brian's comment above (and zigam's edit) that the vars section is too late. I also tested including the key in the on-the-fly definition of the host like this
# fails
- name: Add all instance public IPs to host group
add_host: hostname={{ item.public_ip }} groups=ec2hosts ansible_ssh_private_key_file=~/.aws/dev_staging.pem
loop: "{{ ec2.instances }}"
but that fails too.
So this is not an answer. Just some debugging help and things not to try.
I have tried everything, but only this helped:
php artisan route:clear
php artisan cache:clear
Pass the arguments to the run
command from within gdb.
$ gdb ./a.out
(gdb) r < t
Starting program: /dir/a.out < t
It's a simple "&" function.
=cell&"yourtexthere"
Example - your cell says Mickey, and you want Mickey Mouse. Mickey is in A2. In B2, type
=A2&" Mouse"
Then, copy and "paste special" for values.
B2 now reads "Mickey Mouse"
For AWS (RHEL):
sudo yum install php56-soap
(56 here is 5.6 PHP version - put your version here).
you can use the custom datetime by using...
create table noteTable3
(created_at DATETIME DEFAULT (STRFTIME('%d-%m-%Y %H:%M', 'NOW','localtime')),
title text not null, myNotes text not null);
use 'NOW','localtime' to get the current system date else it will show some past or other time in your Database after insertion time in your db.
Thanks You...
You have make div as server control using following code,
<div class="tab-pane active" id="portlet_tab1" runat="server">
then this div will be accessible in code behind.
In bash foo
is the name of the variable, and $
is an operator which means 'get the value of'.
In perl $foo
is the name of the variable.
The AllocConsole Windows API function will create a console window for your application.
I have a similar problem. I need users to submit html content to a profile page with a great WYSIWYG editor (Redactorjs!), i wrote the following function to clean the submitted html:
<?php function filterxss($str) {
//Initialize DOM:
$dom = new DOMDocument();
//Load content and add UTF8 hint:
$dom->loadHTML('<meta http-equiv="content-type" content="text/html; charset=utf-8">'.$str);
//Array holds allowed attributes and validation rules:
$check = array('src'=>'#(http://[^\s]+(?=\.(jpe?g|png|gif)))#i','href'=>'|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i');
//Loop all elements:
foreach($dom->getElementsByTagName('*') as $node){
for($i = $node->attributes->length -1; $i >= 0; $i--){
//Get the attribute:
$attribute = $node->attributes->item($i);
//Check if attribute is allowed:
if( in_array($attribute->name,array_keys($check))) {
//Validate by regex:
if(!preg_match($check[$attribute->name],$attribute->value)) {
//No match? Remove the attribute
$node->removeAttributeNode($attribute);
}
}else{
//Not allowed? Remove the attribute:
$node->removeAttributeNode($attribute);
}
}
}
var_dump($dom->saveHTML()); } ?>
The $check array holds all the allowed attributes and validation rules. Maybe this is useful for some of you. I haven't tested is yet, so tips are welcome
If your code looks like this:
<div class="row">
<div class="span6">
</div>
<div class="span6">
</div>
</div>
Then I'd assume you're using additional DIVS within the "span6" DIVS for holding/styling your content? So...
<div class="row">
<div class="span6">
<div class="mycontent-left">
</div>
</div>
<div class="span6">
<div class="mycontent-right">
</div>
</div>
</div>
So you could simply add some CSS to the "mycontent-left" class to create your divider.
.mycontent-left {
border-right: 1px dashed #333;
}
Here is another way to use SQL SELECT
statement in VBA:
sSQL = "SELECT Variable FROM GroupTable WHERE VariableCode = '" & Me.comboBox & "'"
Set rs = CurrentDb.OpenRecordset(sSQL)
On Error GoTo resultsetError
dbValue = rs!Variable
MsgBox dbValue, vbOKOnly, "RS VALUE"
resultsetError:
MsgBox "Error Retrieving value from database",VbOkOnly,"Database Error"
So, if you have a statement something like the following, you're saying that you get no 'print' result?
select * from sysobjects PRINT 'Just selected * from sysobjects'
If you're using SQL Query Analyzer, you'll see that there are two tabs down at the bottom, one of which is "Messages" and that's where the 'print' statements will show up.
If you're concerned about the timing of seeing the print statements, you may want to try using something like
raiserror ('My Print Statement', 10,1) with nowait
This will give you the message immediately as the statement is reached, rather than buffering the output, as the Query Analyzer will do under most conditions.
If you want connect to user@'%'
from localhost use mysql -h192.168.0.1 -uuser -p
.
Make sure that the R you are pointing to is the correct one. I had a problem very similar to this, where an import got inserted by Eclipse that pointed to the System R file rather than the project one. It took a lot of head scratching. Hope this helps.
I did this every time the problem happens:
https://accounts.google.com/DisplayUnlockCaptcha
The decision to use 1st January 1753 (1753-01-01
) as the minimum date value for a datetime in SQL Server goes back to its Sybase origins.
The significance of the date itself though can be attributed to this man.
Philip Stanhope, 4th Earl of Chesterfield. Who steered the Calendar (New Style) Act 1750 through the British Parliament. This legislated for the adoption of the Gregorian calendar for Britain and its then colonies.
There were some missing days (internet archive link) in the British calendar in 1752 when the adjustment was finally made from the Julian calendar. September 3, 1752 to September 13, 1752 were lost.
Kalen Delaney explained the choice this way
So, with 12 days lost, how can you compute dates? For example, how can you compute the number of days between October 12, 1492, and July 4, 1776? Do you include those missing 12 days? To avoid having to solve this problem, the original Sybase SQL Server developers decided not to allow dates before 1753. You can store earlier dates by using character fields, but you can't use any datetime functions with the earlier dates that you store in character fields.
The choice of 1753 does seem somewhat anglocentric however as many catholic countries in Europe had been using the calendar for 170 years before the British implementation (originally delayed due to opposition by the church). Conversely many countries did not reform their calendars until much later, 1918 in Russia. Indeed the October Revolution of 1917 started on 7 November under the Gregorian calendar.
Both datetime
and the new datetime2
datatype mentioned in Joe's answer do not attempt to account for these local differences and simply use the Gregorian Calendar.
So with the greater range of datetime2
SELECT CONVERT(VARCHAR, DATEADD(DAY,-5,CAST('1752-09-13' AS DATETIME2)),100)
Returns
Sep 8 1752 12:00AM
One final point with the datetime2
data type is that it uses the proleptic Gregorian calendar projected backwards to well before it was actually invented so is of limited use in dealing with historic dates.
This contrasts with other Software implementations such as the Java Gregorian Calendar class which defaults to following the Julian Calendar for dates until October 4, 1582 then jumping to October 15, 1582 in the new Gregorian calendar. It correctly handles the Julian model of leap year before that date and the Gregorian model after that date. The cutover date may be changed by the caller by calling setGregorianChange()
.
A fairly entertaining article discussing some more peculiarities with the adoption of the calendar can be found here.
String[] strings = new String[25000];
for (int i = 0; i < 25000; i++) strings[i] = '1234567';
String result;
result = "";
for (String s : strings) result += s;
//linear +: 5s
result = "";
for (String s : strings) result = result.concat(s);
//linear .concat: 2.5s
result = String.join("", strings);
//Java 8 .join: 3ms
Public String join(String delimiter, String[] s)
{
int ls = s.length;
switch (ls)
{
case 0: return "";
case 1: return s[0];
case 2: return s[0].concat(delimiter).concat(s[1]);
default:
int l1 = ls / 2;
String[] s1 = Arrays.copyOfRange(s, 0, l1);
String[] s2 = Arrays.copyOfRange(s, l1, ls);
return join(delimiter, s1).concat(delimiter).concat(join(delimiter, s2));
}
}
result = join("", strings);
// Divide&Conquer join: 7ms
If you don't have the choise but to use Java 6 or 7 then you should use Divide&Conquer join.
If week 1 always starts on the first Monday
of the month try this formula for week number
=INT((6+DAY(A1+1-WEEKDAY(A1-1)))/7)
That gets the week number from the date in A1 with no intermediate calculations - if you want to use your "Monday's date" in B1 you can use this version
=INT((DAY(B1)+6)/7)
Since your compiler probably doesn't support all of C++11 yet, which supports similar syntax, you're getting these errors because you have to initialize your class members in constructors:
Attribute() : name(5),val(5,0) {}
You need to add else
in your lambda function. Because you are telling what to do in case your condition(here x < 90) is met, but you are not telling what to do in case the condition is not met.
sample['PR'] = sample['PR'].apply(lambda x: 'NaN' if x < 90 else x)
Just going to add a simple example to what everyone has explained,
json.load()
json.load
can deserialize a file itself i.e. it accepts a file
object, for example,
# open a json file for reading and print content using json.load
with open("/xyz/json_data.json", "r") as content:
print(json.load(content))
will output,
{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}
If I use json.loads
to open a file instead,
# you cannot use json.loads on file object
with open("json_data.json", "r") as content:
print(json.loads(content))
I would get this error:
TypeError: expected string or buffer
json.loads()
json.loads()
deserialize string.
So in order to use json.loads
I will have to pass the content of the file using read()
function, for example,
using content.read()
with json.loads()
return content of the file,
with open("json_data.json", "r") as content:
print(json.loads(content.read()))
Output,
{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}
That's because type of content.read()
is string, i.e. <type 'str'>
If I use json.load()
with content.read()
, I will get error,
with open("json_data.json", "r") as content:
print(json.load(content.read()))
Gives,
AttributeError: 'str' object has no attribute 'read'
So, now you know json.load
deserialze file and json.loads
deserialize a string.
Another example,
sys.stdin
return file
object, so if i do print(json.load(sys.stdin))
, I will get actual json data,
cat json_data.json | ./test.py
{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}
If I want to use json.loads()
, I would do print(json.loads(sys.stdin.read()))
instead.
finaly found solution.. method we were looking for is "willShowViewController" which is delegate method of UINavigationController
//IMPORT UINavigationControllerDelegate !!
class PushedController: UIViewController, UINavigationControllerDelegate {
override func viewDidLoad() {
//set delegate to current class (self)
navigationController?.delegate = self
}
func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
//MyViewController shoud be the name of your parent Class
if var myViewController = viewController as? MyViewController {
//YOUR STUFF
}
}
}
On a system like OSX you might not have pgrep so you can try this appraoch, when looking for processes by name:
while ps axg | grep process_name$ > /dev/null; do sleep 1; done
The $
symbol at the end of the process name ensures that grep matches only process_name to the end of line in the ps output and not itself.
I have used "Pattern 2 - the "factory helper pattern"
Pattern 2 - the factory helper pattern
One case where this pattern won't work is if MyClass is final. Most of the Mockito framework doesn't play particularly well with final classes; and this includes the use of spy(). Another case is where MyClass uses getClass() somewhere, and requires the resulting value to be MyClass. This won't work, because the class of a spy is actually a Mockito-generated subclass of the original class.
In either of these cases, you'll need the slightly more robust factory helper pattern, as follows.
public class MyClass{ static class FactoryHelper{ Foo makeFoo( A a, B b, C c ){ return new Foo( a, b, c ); } } //... private FactoryHelper helper; public MyClass( X x, Y y ){ this( x, y, new FactoryHelper()); } MyClass( X x, Y, y, FactoryHelper helper ){ //... this.helper = helper; } //... Foo foo = helper.makeFoo( a, b, c ); }
So, you have a special constructor, just for testing, that has an additional argument. This is used from your test class, when creating the object that you're going to test. In your test class, you mock the FactoryHelper class, as well as the object that you want to create.
@Mock private MyClass.FactoryHelper mockFactoryHelper; @Mock private Foo mockFoo; private MyClass toTest;
and you can use it like this
toTest = new MyClass( x, y, mockFactoryHelper ); when( mockFactoryHelper.makeFoo( any( A.class ), any( B.class ), any( C.class ))) .thenReturn( mockFoo );
You are probably attempting to use Gmail's servers on port 25 to deliver mail to a third party over an unauthenticated connection. Gmail doesn't let you do this, because then anybody could use Gmail's servers to send mail to anybody else. This is called an open relay and was a common enabler of spam in the early days. Open relays are no longer acceptable on the Internet.
You will need to ask your SMTP client to connect to Gmail using an authenticated connection, probably on port 587.
If you do not need to use JavaHL, Subclipse also provides a pure-Java SVN API library -- SVNKit (http://svnkit.com). Just install the SVNKit client adapter and library plugins from the Subclipse update site and then choose it in the preferences under Team > SVN.
In case the container is already running:
docker exec -it container_id_or_name ash
After hours of googling, reading, uninstalling, facepalming! It turned out that a chrome extension for VPN was handling the proxy settings for Chrome!
Betternet to be more specific!
Disabling it, solved my problem.
To make sure it is not the problem, check the proxy settings for Chrome itself. For me it showed me a message, says : Betternet is handling the proxy settings.
You can figure out which proxy server you're using by accessing some websites with a browser and then running the DOS command:
netstat
and you'll see some connections in the Foreign Address column on port 80 or 8080 (common proxy server ports). Ideally you will be able to identify the proxy server by its naming convention.
I am loading html pages from Documents and if they have the same name of css file UIWebView
it seem it does not throw the previous css rules. Maybe because they have the same URL or something.
I tried this:
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
[sharedCache release];
I tried this :
[[NSURLCache sharedURLCache] removeAllCachedResponses];
I am loading the initial page with:
NSURLRequest *appReq = [NSURLRequest requestWithURL:appURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0];
It refuses to throw its cached data! Frustrating!
I am doing this inside a PhoneGap (Cordova) application. I have not tried it in isolated UIWebView.
Update1: I have found this.
Changing the html files, though seems very messy.
As @Veger said, you can make it final
so that the variable can be used in the inner class.
final ViewPager pager = (ViewPager) findViewById(R.id.fieldspager);
I called it pager
rather than mPager
because you are using it as a local variable in the onCreate
method. The m
prefix is cusomarily reserved for class member variables (i.e. variables that are declared at the beginning of the class and are available to all class methods).
If you actually do need a class member variable, it doesn't work to make it final because you can't use findViewById
to set its value until onCreate
. The solution is to not use an anonymous inner class. This way the mPager
variable doesn't need to be declared final and can be used throughout the class.
public class MainActivity extends AppCompatActivity {
private ViewPager mPager;
private Button mButton;
@Override
public void onCreate(Bundle savedInstanceState) {
// ...
mPager = (ViewPager) findViewById(R.id.fieldspager);
// ...
mButton.setOnClickListener(myButtonClickHandler);
}
View.OnClickListener myButtonClickHandler = new View.OnClickListener() {
@Override
public void onClick(View view) {
mPager.setCurrentItem(2, true);
}
};
}
you can use also this way to write css for placeholder
input::placeholder{
text-align: center;
}
Type
chcp
to see your current code page (as Dewfy already said).
Use
nlsinfo
to see all installed code pages and find out what your code page number means.
You need to have Windows Server 2003 Resource kit installed (works on Windows XP) to use nlsinfo
.
Like this:
echo substr($row['style-info'], 0, 200);
Or wrapped in a function:
function echo_200($str){
echo substr($row['style-info'], 0, 200);
}
echo_200($str);
What you need is overflow-y: scroll;
textarea {_x000D_
overflow-y: scroll;_x000D_
height: 100px;_x000D_
resize: none; /* Remove this if you want the user to resize the textarea */_x000D_
}
_x000D_
<textarea></textarea>
_x000D_
This may not be the correct way to do it. But I have solved the problem using substring function.
Select max(start_ts), min(start_ts)from db where SUBSTR(start_ts, 0,9) ='13-may-2016'
using this I was able to retrieve the max and min timestamp.
right click on SQL Server browser and properties, then Connection tab and chose open session with system account and not this account. then apply and chose automatic and finally run the server.
Execute the following command
sudo setfacl -R -m u:<user_name>:rwx /var/www
It will change the permissions of html directory so that you can upload, download and delete the files or directories
No, there's no way to do it. That would essentially be scoping in reverse.
Methods defined inside the constructor have access to private variables because all functions have access to the scope in which they were defined.
Methods defined on a prototype are not defined within the scope of the constructor, and will not have access to the constructor's local variables.
You can still have private variables, but if you want methods defined on the prototype to have access to them, you should define getters and setters on the this
object, which the prototype methods (along with everything else) will have access to. For example:
function Person(name, secret) {
// public
this.name = name;
// private
var secret = secret;
// public methods have access to private members
this.setSecret = function(s) {
secret = s;
}
this.getSecret = function() {
return secret;
}
}
// Must use getters/setters
Person.prototype.spillSecret = function() { alert(this.getSecret()); };
Use a FrameLayout with two children. The two children will be overlapped. This is recommended in one of the tutorials from Android actually, it's not a hack...
Here is an example where a TextView is displayed on top of an ImageView:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="center"
android:src="@drawable/golden_gate" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dip"
android:layout_gravity="center_horizontal|bottom"
android:padding="12dip"
android:background="#AA000000"
android:textColor="#ffffffff"
android:text="Golden Gate" />
</FrameLayout>
import urllib2
mp3file = urllib2.urlopen("http://www.example.com/songs/mp3.mp3")
with open('test.mp3','wb') as output:
output.write(mp3file.read())
The wb
in open('test.mp3','wb')
opens a file (and erases any existing file) in binary mode so you can save data with it instead of just text.
Just echo
the first list of your source file into your target file.
echo $(head -n 1 source.txt) > target.txt
You can use something like this:
note: responseText
returns server response
and statusText
returns the predefined
message for status
error.for e.g:
responseText
returns something like "Not Found (#404)"
in some frameworks like Yii2 but
statusText
returns "Not Found"
.
$.ajax({
cache: false,
url: "addInterview_Code.asp",
type: "POST",
datatype: "text",
data: strData,
success: function (html) {
alert('successful : ' + html);
$("#result").html("Successful");
},
error: function (data) {
console.log(data.status + ':' + data.statusText,data.responseText);
}
});
<form (submit)="addTodo()">_x000D_
<input type="text" [(ngModel)]="text">_x000D_
</form>
_x000D_
I've got a solution working in FF3, Safari and IE6+ with single and multiline text
.ellipsis {
white-space: nowrap;
overflow: hidden;
}
.ellipsis.multiline {
white-space: normal;
}
<div class="ellipsis" style="width: 100px; border: 1px solid black;">Lorem ipsum dolor sit amet, consectetur adipisicing elit</div>
<div class="ellipsis multiline" style="width: 100px; height: 40px; border: 1px solid black; margin-bottom: 100px">Lorem ipsum dolor sit amet, consectetur adipisicing elit</div>
<script type="text/javascript" src="/js/jquery.ellipsis.js"></script>
<script type="text/javascript">
$(".ellipsis").ellipsis();
</script>
jquery.ellipsis.js
(function($) {
$.fn.ellipsis = function()
{
return this.each(function()
{
var el = $(this);
if(el.css("overflow") == "hidden")
{
var text = el.html();
var multiline = el.hasClass('multiline');
var t = $(this.cloneNode(true))
.hide()
.css('position', 'absolute')
.css('overflow', 'visible')
.width(multiline ? el.width() : 'auto')
.height(multiline ? 'auto' : el.height())
;
el.after(t);
function height() { return t.height() > el.height(); };
function width() { return t.width() > el.width(); };
var func = multiline ? height : width;
while (text.length > 0 && func())
{
text = text.substr(0, text.length - 1);
t.html(text + "...");
}
el.html(t.html());
t.remove();
}
});
};
})(jQuery);
This solution is also memory-optimized so you can run it on 10,000's of data items and requests. Some of the other solutions here will crash the server on large data sets.
In TypeScript:
export async function asyncForEach<T>(array: Array<T>, callback: (item: T, index: number) => void) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index);
}
}
How to use?
await asyncForEach(receipts, async (eachItem) => {
await ...
})
In a bootstrap environment none of the top answers helped, but applying the following removed all borders:
.noBorder {
border:none !important;
}
Applied as:
<td class="noBorder">
You are just updating the value of i
in the loop. The value of i
should also be added each time.
It is never a good idea to update the value of i
inside the for
loop. The for
loop index should only be used as a counter. In your case, changing the value of i
inside the loop will cause all sorts of confusion.
Create variable total
that holds the sum of the numbers up to i
.
So
for (int i = 0; i < positiveInteger; i++)
total += i;
Using this code you can get the notification in background/foreground and also put action:
//Data should come in this format from the notification
{
"to": "/xyz/Notifications",
"data": {
"key1": "title notification",
"key2": "description notification"
}
}
In-App use this code:
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String key1Data = remoteMessage.getData().get("key1");
// use key1Data to according to your need
}
You can use this:
<input type="checkbox" [checked]="record.status" (change)="changeStatus(record.id,$event)">
And on your ts file,
changeStatus(id, e) {
var status = e.target.checked;
this.yourseverice.changeStatus(id, status).subscribe(result => {
if (status)
this.notify.success(this.l('AddedAsKeyPeople'));
else
this.notify.success(this.l('RemovedFromKeyPeople'));
});
}
Here, record is the model for current row and status is boolean value.
If you use apachectl to start or stop, then you can find it with this command
apachectl -t -D DUMP_RUN_CFG
for Bootstrap 4 version via CSS:
if you want to change the background color of balloon:
/* change style balloon */
.tooltip-inner {
background-color: green !important;
color: #fff;
}
if you want to change the arrow when appear in bottom position:
/* change style arrow */
.bs-tooltip-auto[x-placement^=bottom] .arrow::before, .bs-tooltip-bottom .arrow::before {
border-bottom-color: #f00;
}
Hope help you
There is an easier method than the other answers here, which require first deserializing into a c# class, and then turning it into a datatable.
It is possible to go directly to a datatable, with JSON.NET and code like this:
DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));
In order to navigate to a different drive/directory you can do it in convenient way (instead of typing cd /e/Study/Codes), just type in cd[Space], and drag-and-drop your directory Codes with your mouse to git bash, hit [Enter].
Well, note that the request contains binary data, so I'm not posting the request as such - instead, I've converted every non-printable-ascii character into a dot (".").
POST /cgi-bin/qtest HTTP/1.1
Host: aram
User-Agent: Mozilla/5.0 Gecko/2009042316 Firefox/3.0.10
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://aram/~martind/banner.htm
Content-Type: multipart/form-data; boundary=2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Length: 514
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile1"; filename="r.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile2"; filename="g.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile3"; filename="b.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f--
Note that every line (including the last one) is terminated by a \r\n sequence.
and
/or
are for control flow.
Ruby will not allow this as valid syntax:
false || raise "Error"
However this is valid:
false or raise "Error"
You can make the first work, with ()
but using or
is the correct method.
false || (raise "Error")
Thank you Ganesh Sanap. sorting items by date field from old to new. Use it
myArray = [{transport: "Air",
load: "Vatican Vaticano",
created: "01/31/2020"},
{transport: "Air",
load: "Paris",
created: "01/30/2020"}]
myAarray.sort(function(a, b) {
var c = new Date(a.created);
var d = new Date(b.created);
return c-d;
});
Following code is a sample. Question based on the same, instead of using IDE based conversion, is there a faster way to implement so that in future the changes occur, we do not need to modify the values over and over again?
@Override
public String toString() {
return "ContractDTO{" +
"contractId='" + contractId + '\'' +
", contractTemplateId='" + contractTemplateId + '\'' +
'}';
}
In a shameless attempt to steal some votes, SecurityProtocol
is an Enum
with the [Flags]
attribute. So you can do this:
[Net.ServicePointManager]::SecurityProtocol =
[Net.SecurityProtocolType]::Tls12 -bor `
[Net.SecurityProtocolType]::Tls11 -bor `
[Net.SecurityProtocolType]::Tls
Or since this is PowerShell, you can let it parse a string for you:
[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"
Then you don't technically need to know the TLS version.
I copied and pasted this from a script I created after reading this answer because I didn't want to cycle through all the available protocols to find one that worked. Of course, you could do that if you wanted to.
Final note - I have the original (minus SO edits) statement in my PowerShell profile so it's in every session I start now. It's not totally foolproof since there are still some sites that just fail but I surely see the message in question much less frequently.
You can use the ScriptManager.RegisterStartupScript();
to call any of your javascript event/Client Event from the server. For example, to display a message using javascript's alert();
, you can do this:
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
Response.write("<script>alert('This is my message');</script>");
//----or alternatively and to be more proper
ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "alert('This is my message')", true);
}
To be exact for you, do this...
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "CalcTotalAmt();", true);
}
You can try this:
:backup
move C:\FilesToBeBackedUp\*.* E:\BackupPlace\
timeout 36000
goto backup
If that doesn't work try to replace "timeout" with sleep. Ik this post is over a year old, just helping anyone with the same problem.
private static String getPreviousMonthDate(Date date){
final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.DATE, -1);
Date preMonthDate = cal.getTime();
return format.format(preMonthDate);
}
private static String getPreToPreMonthDate(Date date){
final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DAY_OF_MONTH,1);
cal.add(Calendar.DATE, -1);
Date preToPreMonthDate = cal.getTime();
return format.format(preToPreMonthDate);
}
All of the answers so far are good, and get at different aspects of how a hashtable works. Here is a simple example that might be helpful. Lets say we want to store some items with lower case alphabetic strings as a keys.
As simon explained, the hash function is used to map from a large space to a small space. A simple, naive implementation of a hash function for our example could take the first letter of the string, and map it to an integer, so "alligator" has a hash code of 0, "bee" has a hash code of 1, "zebra" would be 25, etc.
Next we have an array of 26 buckets (could be ArrayLists in Java), and we put the item in the bucket that matches the hash code of our key. If we have more than one item that has a key that begins with the same letter, they will have the same hash code, so would all go in the bucket for that hash code so a linear search would have to be made in the bucket to find a particular item.
In our example, if we just had a few dozen items with keys spanning the alphabet, it would work very well. However, if we had a million items or all the keys all started with 'a' or 'b', then our hash table would not be ideal. To get better performance, we would need a different hash function and/or more buckets.
try this script..
#!/bin/bash
NULL="_"
for f in `svn st|grep -v ^\?|sed s/.\ *//`;
do LIST="${LIST} $f $NULL on";
done
dialog --checklist "Select files to commit" 30 60 30 $LIST 2>/tmp/svnlist.txt
svn ci `cat /tmp/svnlist.txt|sed 's/"//g'`
I had this issue on Android 10,
Changed targetSdkVersion 29
to targetSdkVersion 28
issue resolved. Not sure what is the actual problem.
I think not a good practice, but it worked.
before:
compileSdkVersion 29
minSdkVersion 14
targetSdkVersion 29
Now:
compileSdkVersion 29
minSdkVersion 14
targetSdkVersion 28
The question is tagged SQL Server 2000 but for the benefit of people developing on the latest version I'll address that first.
SQL Server 2014
In addition to the methods of adding constraint based indexes discussed below SQL Server 2014 also allows non unique indexes to be specified directly with inline syntax on table variable declarations.
Example syntax for that is below.
/*SQL Server 2014+ compatible inline index syntax*/
DECLARE @T TABLE (
C1 INT INDEX IX1 CLUSTERED, /*Single column indexes can be declared next to the column*/
C2 INT INDEX IX2 NONCLUSTERED,
INDEX IX3 NONCLUSTERED(C1,C2) /*Example composite index*/
);
Filtered indexes and indexes with included columns can not currently be declared with this syntax however SQL Server 2016 relaxes this a bit further. From CTP 3.1 it is now possible to declare filtered indexes for table variables. By RTM it may be the case that included columns are also allowed but the current position is that they "will likely not make it into SQL16 due to resource constraints"
/*SQL Server 2016 allows filtered indexes*/
DECLARE @T TABLE
(
c1 INT NULL INDEX ix UNIQUE WHERE c1 IS NOT NULL /*Unique ignoring nulls*/
)
SQL Server 2000 - 2012
Can I create a index on Name?
Short answer: Yes.
DECLARE @TEMPTABLE TABLE (
[ID] [INT] NOT NULL PRIMARY KEY,
[Name] [NVARCHAR] (255) COLLATE DATABASE_DEFAULT NULL,
UNIQUE NONCLUSTERED ([Name], [ID])
)
A more detailed answer is below.
Traditional tables in SQL Server can either have a clustered index or are structured as heaps.
Clustered indexes can either be declared as unique to disallow duplicate key values or default to non unique. If not unique then SQL Server silently adds a uniqueifier to any duplicate keys to make them unique.
Non clustered indexes can also be explicitly declared as unique. Otherwise for the non unique case SQL Server adds the row locator (clustered index key or RID for a heap) to all index keys (not just duplicates) this again ensures they are unique.
In SQL Server 2000 - 2012 indexes on table variables can only be created implicitly by creating a UNIQUE
or PRIMARY KEY
constraint. The difference between these constraint types are that the primary key must be on non nullable column(s). The columns participating in a unique constraint may be nullable. (though SQL Server's implementation of unique constraints in the presence of NULL
s is not per that specified in the SQL Standard). Also a table can only have one primary key but multiple unique constraints.
Both of these logical constraints are physically implemented with a unique index. If not explicitly specified otherwise the PRIMARY KEY
will become the clustered index and unique constraints non clustered but this behavior can be overridden by specifying CLUSTERED
or NONCLUSTERED
explicitly with the constraint declaration (Example syntax)
DECLARE @T TABLE
(
A INT NULL UNIQUE CLUSTERED,
B INT NOT NULL PRIMARY KEY NONCLUSTERED
)
As a result of the above the following indexes can be implicitly created on table variables in SQL Server 2000 - 2012.
+-------------------------------------+-------------------------------------+
| Index Type | Can be created on a table variable? |
+-------------------------------------+-------------------------------------+
| Unique Clustered Index | Yes |
| Nonunique Clustered Index | |
| Unique NCI on a heap | Yes |
| Non Unique NCI on a heap | |
| Unique NCI on a clustered index | Yes |
| Non Unique NCI on a clustered index | Yes |
+-------------------------------------+-------------------------------------+
The last one requires a bit of explanation. In the table variable definition at the beginning of this answer the non unique non clustered index on Name
is simulated by a unique index on Name,Id
(recall that SQL Server would silently add the clustered index key to the non unique NCI key anyway).
A non unique clustered index can also be achieved by manually adding an IDENTITY
column to act as a uniqueifier.
DECLARE @T TABLE
(
A INT NULL,
B INT NULL,
C INT NULL,
Uniqueifier INT NOT NULL IDENTITY(1,1),
UNIQUE CLUSTERED (A,Uniqueifier)
)
But this is not an accurate simulation of how a non unique clustered index would normally actually be implemented in SQL Server as this adds the "Uniqueifier" to all rows. Not just those that require it.
Based on my highly scientific and accurate experiment, it tops out on my machine well before 1,000,000,000 characters. (I'm still running the code below to get a better pinpoint).
UPDATE:
After a few hours, I've given up. Final results: Can go a lot bigger than 100,000,000 characters, instantly given System.OutOfMemoryException
at 1,000,000,000 characters.
using System;
using System.Collections.Generic;
public class MyClass
{
public static void Main()
{
int i = 100000000;
try
{
for (i = i; i <= int.MaxValue; i += 5000)
{
string value = new string('x', i);
//WL(i);
}
}
catch (Exception exc)
{
WL(i);
WL(exc);
}
WL(i);
RL();
}
#region Helper methods
private static void WL(object text, params object[] args)
{
Console.WriteLine(text.ToString(), args);
}
private static void RL()
{
Console.ReadLine();
}
private static void Break()
{
System.Diagnostics.Debugger.Break();
}
#endregion
}
you don’t need a select … from dual
, just write:
SELECT t.*, dbms_random.value(1,9) RandomNumber
FROM myTable t
In Sequel Pro, access the User Accounts window. Note that any MySQL administration program could be substituted in place of Sequel Pro.
Add the following accounts and privileges:
GRANT SUPER ON *.* TO 'user'@'%' IDENTIFIED BY PASSWORD
First check your listener is on or off. Go to net manager then Local -> service naming -> orcl. Then change your HOST NAME and put your PC name. Now go to LISTENER and change the HOST and put your PC name.
data['result'] = data['result'].map(lambda x: x.lstrip('+-').rstrip('aAbBcC'))
From the documentation on http://curl.haxx.se/docs/httpscripting.html :
HTTP Authentication
curl --user name:password http://www.example.com
Put a file to a HTTP server with curl:
curl --upload-file uploadfile http://www.example.com/receive.cgi
Send post data with curl:
curl --data "birthyear=1905&press=%20OK%20" http://www.example.com/when.cgi
You're using the exec form of ENTRYPOINT. Unlike the shell form, the exec form does not invoke a command shell. This means that normal shell processing does not happen. For example, ENTRYPOINT [ "echo", "$HOME" ]
will not do variable substitution on $HOME. If you want shell processing then either use the shell form or execute a shell directly, for example: ENTRYPOINT [ "sh", "-c", "echo $HOME" ]
.
When using the exec form and executing a shell directly, as in the case for the shell form, it is the shell that is doing the environment variable expansion, not docker.(from Dockerfile reference)
In your case, I would use shell form
ENTRYPOINT ./greeting --message "Hello, $ADDRESSEE\!"
I would like to cite a paragraph which describes the major difference between greedy algorithms and dynamic programming algorithms stated in the book Introduction to Algorithms (3rd edition) by Cormen, Chapter 15.3, page 381:
One major difference between greedy algorithms and dynamic programming is that instead of first finding optimal solutions to subproblems and then making an informed choice, greedy algorithms first make a greedy choice, the choice that looks best at the time, and then solve a resulting subproblem, without bothering to solve all possible related smaller subproblems.
First, the replies are correct that what the OP is requesting is a contradiction in terms: virtual methods depend on the run-time type of an instance; static functions specifically don't depend on an instance -- just on a type. That said, it makes sense to have static functions return something specific to a type. For example, I had a family of MouseTool classes for the State pattern and I started having each one have a static function returning the keyboard modifier that went with it; I used those static functions in the factory function that made the correct MouseTool instance. That function checked the mouse state against MouseToolA::keyboardModifier(), MouseToolB::keyboardModifier(), etc. and then instantiated the appropriate one. Of course later I wanted to check if the state was right so I wanted write something like "if (keyboardModifier == dynamic_type(*state)::keyboardModifier())" (not real C++ syntax), which is what this question is asking.
So, if you find yourself wanting this, you may want to rething your solution. Still, I understand the desire to have static methods and then call them dynamically based on the dynamic type of an instance. I think the Visitor Pattern can give you what you want. It gives you what you want. It's a bit of extra code, but it could be useful for other visitors.
See: http://en.wikipedia.org/wiki/Visitor_pattern for background.
struct ObjectVisitor;
struct Object
{
struct TypeInformation;
static TypeInformation GetTypeInformation();
virtual void accept(ObjectVisitor& v);
};
struct SomeObject : public Object
{
static TypeInformation GetTypeInformation();
virtual void accept(ObjectVisitor& v) const;
};
struct AnotherObject : public Object
{
static TypeInformation GetTypeInformation();
virtual void accept(ObjectVisitor& v) const;
};
Then for each concrete Object:
void SomeObject::accept(ObjectVisitor& v) const {
v.visit(*this); // The compiler statically picks the visit method based on *this being a const SomeObject&.
}
void AnotherObject::accept(ObjectVisitor& v) const {
v.visit(*this); // Here *this is a const AnotherObject& at compile time.
}
and then define the base visitor:
struct ObjectVisitor {
virtual ~ObjectVisitor() {}
virtual void visit(const SomeObject& o) {} // Or = 0, depending what you feel like.
virtual void visit(const AnotherObject& o) {} // Or = 0, depending what you feel like.
// More virtual void visit() methods for each Object class.
};
Then the concrete visitor that selects the appropriate static function:
struct ObjectVisitorGetTypeInfo {
Object::TypeInformation result;
virtual void visit(const SomeObject& o) {
result = SomeObject::GetTypeInformation();
}
virtual void visit(const AnotherObject& o) {
result = AnotherObject::GetTypeInformation();
}
// Again, an implementation for each concrete Object.
};
finally, use it:
void printInfo(Object& o) {
ObjectVisitorGetTypeInfo getTypeInfo;
Object::TypeInformation info = o.accept(getTypeInfo).result;
std::cout << info << std::endl;
}
Notes:
If you want to avoid copy-paste errors where one of your visit methods calls the wrong static function, you could use a templated helper function (which can't itself be virtual) t your visitor with a template like this:
struct ObjectVisitorGetTypeInfo {
Object::TypeInformation result;
virtual void visit(const SomeObject& o) { doVisit(o); }
virtual void visit(const AnotherObject& o) { doVisit(o); }
// Again, an implementation for each concrete Object.
private:
template <typename T>
void doVisit(const T& o) {
result = T::GetTypeInformation();
}
};
Not surprisingly, this error can arise when another process is listening on the desired port. This happened today when I started an instance of the Apache Web server, listening on its default port (80), having forgotten that I already had IIS 7 running, and listening on that port. This is well explained in Port 80 is being used by SYSTEM (PID 4), what is that? Better yet, that article points to Stop http.sys from listening on port 80 in Windows, which explains a very simple way to resolve it, with just a tad of help from an elevated command prompt and a one-line edit of my hosts file.
This code sends array of integer values
Initialize array List
List<Integer> test = new ArrayList<Integer>();
Add values to array List
test.add(1);
test.add(2);
test.add(3);
Intent intent=new Intent(this, targetActivty.class);
Send the array list values to target activity
intent.putIntegerArrayListExtra("test", (ArrayList<Integer>) test);
startActivity(intent);
here you get values on targetActivty
Intent intent=getIntent();
ArrayList<String> test = intent.getStringArrayListExtra("test");
Oracle Client version 11 cannot connect to 8i databases. You will need a client in version 10 at most.
public class Person
{
// Before C# 6.0
[Display(Name = "Age", ResourceType = typeof(Testi18n.Resource))]
public string Age { get; set; }
// After C# 6.0
// [Display(Name = nameof(Resource.Age), ResourceType = typeof(Resource))]
}
Define Name of the attribute which is used for the key of resource, after C# 6.0, you can use nameof
for strong typed support instead of hard coding the key.
Set the culture of current thread in the controller.
Resource.Culture = CultureInfo.GetCultureInfo("zh-CN");
Set the accessibility of the resource to public
Display the label in cshtml like this
@Html.DisplayNameFor(model => model.Age)
I have done it in the following way and it has worked perfectly for me.
First declared a global variable in the header.php, assigning the ID of the post or page before it changes, since the LOOP assigns it the ID of the last entry shown:
$GLOBALS['pageid] = $wp_query->get_queried_object_id();
And to use anywhere in the template, example in the footer.php:
echo $GLOBALS['pageid];
What Harley said, except the last point - it's not actually necessary to change the '/'s into '\'s before calling open. Windows is quite happy to accept paths with forward slashes.
infile = open('c:/folder/subfolder/file.txt')
The only time you're likely to need the string normpathed is if you're passing to to another program via the shell (using os.system
or the subprocess
module).
I don't know what qualifies as best but zxing has a qr code generator for java, is actively developed, and is liberally licensed.
Using Partitions in Hive table is highly recommended for below reason -
Example :-
Assume that Input File (100 GB) is loaded into temp-hive-table and it contains bank data from across different geographies.
Hive table without Partition
Insert into Hive table Select * from temp-hive-table
/hive-table-path/part-00000-1 (part size ~ hdfs block size)
/hive-table-path/part-00000-2
....
/hive-table-path/part-00000-n
Problem with this approach is - It will scan whole data for any query you run on this table. Response time will be high compare to other approaches where partitioning and Bucketing are used.
Hive table with Partition
Insert into Hive table partition(country) Select * from temp-hive-table
/hive-table-path/country=US/part-00000-1 (file size ~ 10 GB)
/hive-table-path/country=Canada/part-00000-2 (file size ~ 20 GB)
....
/hive-table-path/country=UK/part-00000-n (file size ~ 5 GB)
Pros - Here one can access data faster when it comes to querying data for specific geography transactions. Cons - Inserting/querying data can further be improved by splitting data within each partition. See Bucketing option below.
Hive table with Partition and Bucketing
Note: Create hive table ..... with "CLUSTERED BY(Partiton_Column) into 5 buckets
Insert into Hive table partition(country) Select * from temp-hive-table
/hive-table-path/country=US/part-00000-1 (file size ~ 2 GB)
/hive-table-path/country=US/part-00000-2 (file size ~ 2 GB)
/hive-table-path/country=US/part-00000-3 (file size ~ 2 GB)
/hive-table-path/country=US/part-00000-4 (file size ~ 2 GB)
/hive-table-path/country=US/part-00000-5 (file size ~ 2 GB)
/hive-table-path/country=Canada/part-00000-1 (file size ~ 4 GB)
/hive-table-path/country=Canada/part-00000-2 (file size ~ 4 GB)
/hive-table-path/country=Canada/part-00000-3 (file size ~ 4 GB)
/hive-table-path/country=Canada/part-00000-4 (file size ~ 4 GB)
/hive-table-path/country=Canada/part-00000-5 (file size ~ 4 GB)
....
/hive-table-path/country=UK/part-00000-1 (file size ~ 1 GB)
/hive-table-path/country=UK/part-00000-2 (file size ~ 1 GB)
/hive-table-path/country=UK/part-00000-3 (file size ~ 1 GB)
/hive-table-path/country=UK/part-00000-4 (file size ~ 1 GB)
/hive-table-path/country=UK/part-00000-5 (file size ~ 1 GB)
Pros - Faster Insert. Faster Query.
Cons - Bucketing will creating more files. There could be issue with many small files in some specific cases
Hope this will help !!
We face this error when we are selecting data from more than one tables by joining tables and at least one of the selected columns (it will also happen when use * to select all columns) exist with same name in more than one tables (our selected/joined tables). In that case we must have to specify from which table we are selecting out column.
Following is a an example solution implementation of concept explained above
I think you have ambiguity only in InvoiceID
that exists both in InvoiceLineItems
and Invoices
Other fields seem distinct. So try This
I just replace InvoiceID with Invoices.InvoiceID
SELECT
VendorName, Invoices.InvoiceID, InvoiceSequence, InvoiceLineItemAmount
FROM Vendors
JOIN Invoices ON (Vendors.VendorID = Invoices.VendorID)
JOIN InvoiceLineItems ON (Invoices.InvoiceID = InvoiceLineItems.InvoiceID)
WHERE
Invoices.InvoiceID IN
(SELECT InvoiceSequence
FROM InvoiceLineItems
WHERE InvoiceSequence > 1)
ORDER BY
VendorName, Invoices.InvoiceID, InvoiceSequence, InvoiceLineItemAmount
You can use tablename.columnnae for all columns (in selection,where,group by and order by) without using any alias. However you can use an alias as guided by other answers
The cleanest solution I've found is as follows:
This example is to perform two very different actions; the basic premise is to use the value to pass data to the action.
In your view:
@using (Html.BeginForm("DliAction", "Dli", FormMethod.Post, new { id = "mainForm" }))
{
if (isOnDli)
{
<button name="removeDli" value="@result.WeNo">Remove From DLI</button>
}
else
{
<button name="performDli" value="@result.WeNo">Perform DLI</button>
}
}
Then in your action:
public ActionResult DliAction(string removeDli, string performDli)
{
if (string.IsNullOrEmpty(performDli))
{
...
}
else if (string.IsNullOrEmpty(removeDli))
{
...
}
return View();
}
This code should be easy to alter in order to achieve variations along the theme, e.g. change the button's name to be the same, then you only need one parameter on the action etc, as can be seen below:
In your view:
@using (Html.BeginForm("DliAction", "Dli", FormMethod.Post, new { id = "mainForm" }))
{
<button name="weNo" value="@result.WeNo">Process This WeNo</button>
<button name="weNo" value="@result.WeNo">Process A Different WeNo This Item</button>
}
Then in your action:
public ActionResult DliAction(string weNo)
{
// Process the weNo...
return View();
}
man ssh
gives me this options would could be useful.
-i identity_file Selects a file from which the identity (private key) for RSA or DSA authentication is read. The default is ~/.ssh/identity for protocol version 1, and ~/.ssh/id_rsa and ~/.ssh/id_dsa for pro- tocol version 2. Identity files may also be specified on a per- host basis in the configuration file. It is possible to have multiple -i options (and multiple identities specified in config- uration files).
So you could create an alias in your bash config with something like
alias ssh="ssh -i /path/to/private_key"
I haven't looked into a ssh configuration file, but like the -i
option this too could be aliased
-F configfile Specifies an alternative per-user configuration file. If a configuration file is given on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored. The default for the per-user configuration file is ~/.ssh/config.
$(this)
instead of $this
$("tr.item").each(function() {
var quantity1 = $(this).find("input.name").val(),
quantity2 = $(this).find("input.id").val();
});
Some of the system headers provide a forward declaration of std::stringstream
without the definition. This makes it an 'incomplete type'. To fix that you need to include the definition, which is provided in the <sstream>
header:
#include <sstream>
According to JVM specification, fields and methods in a Interface can have only Public, Static, Final and Abstract. Ref from Inside Java VM
By default, all the methods in interface is abstract even tough you didn't mention it explicitly.
Interfaces are meant to give only specification. It can not contain any implementations. So To avoid implementing classes to change the specification, it is made final. Since Interface cannot be instantiated, they are made static to access the field using interface name.
dtList = dtList.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList()
I assumed empty string and whitespace are like null. If not you can use IsNullOrEmpty
(allow whitespace), or s != null
I have observed on Windows 2008 the Windows Error Reporting crash dumps get staged in the folder:
C:\Users\All Users\Microsoft\Windows\WER\ReportQueue
Which, starting with Windows Vista, is an alias for:
C:\ProgramData\Microsoft\Windows\WER\ReportQueue
Based on Michael Scharf's comment:
You can leave out the password so that it won't be logged in your Bash history file:
git clone https://[email protected]/username/repository.git
It will prompt you for your password.
Alternatively, you may use:
git clone https://username:[email protected]/username/repository.git
This way worked for me from a GitHub repository.
For MS SQL CEILING(your number) will round it up. FLOOR(your number) will round it down
After looking for an answer for the question for months, I finally find a really best solution: writing a simple script.
#!/usr/bin/expect
set timeout 20
set cmd [lrange $argv 1 end]
set password [lindex $argv 0]
eval spawn $cmd
expect "assword:" # matches both 'Password' and 'password'
send "$password\r";
interact
Put it to /usr/bin/exp
, then you can use:
exp <password> ssh <anything>
exp <password> scp <anysrc> <anydst>
Done!
I also meet the same error in vbscript.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Solution:
Open command line, run :
regsvr32 /i "c:\windows\system32\scrrun.dll"
and it works
First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.
Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.
Instead, I would move all of the "application" content to a separate component, like a JPanel
for example and simply move this between the applet or frame as required...
ps- You can use f.setLocationRelativeTo(null)
to center the window on the screen ;)
Updated
You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...
Within the constructor of GalzyTable2
you are doing...
JApplet app = new JApplet(); add(app); app.init(); app.start();
...Why are you adding another applet to an applet??
Case in point...
Within the main
method, you are trying to add the instance of JFrame
to itself...
f.getContentPane().add(f, button2);
Instead, create yourself a class that extends from something like JPanel
, add your UI logical to this, using compound components if required.
Then, add this panel to whatever top level container you need.
Take the time to read through Creating a GUI with Swing
Updated with example
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class GalaxyTable2 extends JPanel { private static final int PREF_W = 700; private static final int PREF_H = 600; String[] columnNames = {"Phone Name", "Brief Description", "Picture", "price", "Buy"}; // Create image icons ImageIcon Image1 = new ImageIcon( getClass().getResource("s1.png")); ImageIcon Image2 = new ImageIcon( getClass().getResource("s2.png")); ImageIcon Image3 = new ImageIcon( getClass().getResource("s3.png")); ImageIcon Image4 = new ImageIcon( getClass().getResource("s4.png")); ImageIcon Image5 = new ImageIcon( getClass().getResource("note.png")); ImageIcon Image6 = new ImageIcon( getClass().getResource("note2.png")); ImageIcon Image7 = new ImageIcon( getClass().getResource("note3.png")); Object[][] rowData = { {"Galaxy S", "3G Support,CPU 1GHz", Image1, 120, false}, {"Galaxy S II", "3G Support,CPU 1.2GHz", Image2, 170, false}, {"Galaxy S III", "3G Support,CPU 1.4GHz", Image3, 205, false}, {"Galaxy S4", "4G Support,CPU 1.6GHz", Image4, 230, false}, {"Galaxy Note", "4G Support,CPU 1.4GHz", Image5, 190, false}, {"Galaxy Note2 II", "4G Support,CPU 1.6GHz", Image6, 190, false}, {"Galaxy Note 3", "4G Support,CPU 2.3GHz", Image7, 260, false},}; MyTable ss = new MyTable( rowData, columnNames); // Create a table JTable jTable1 = new JTable(ss); public GalaxyTable2() { jTable1.setRowHeight(70); add(new JScrollPane(jTable1), BorderLayout.CENTER); JPanel buttons = new JPanel(); JButton button = new JButton("Home"); buttons.add(button); JButton button2 = new JButton("Confirm"); buttons.add(button2); add(buttons, BorderLayout.SOUTH); } @Override public Dimension getPreferredSize() { return new Dimension(PREF_W, PREF_H); } public void actionPerformed(ActionEvent e) { new AMainFrame7().setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new GalaxyTable2()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } }
You also seem to have a lack of understanding about how to use layout managers.
Take the time to read through Creating a GUI with Swing and Laying components out in a container
Encode or decode byte arrays:
byte[] encoded = Base64.getEncoder().encode("Hello".getBytes());
println(new String(encoded)); // Outputs "SGVsbG8="
byte[] decoded = Base64.getDecoder().decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
String encoded = Base64.getEncoder().encodeToString("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = new String(Base64.getDecoder().decode(encoded.getBytes()));
println(decoded) // Outputs "Hello"
For more info, see Base64.
Base64 is not bundled with Java versions less than 8. I recommend using Apache Commons Codec.
For direct byte arrays:
Base64 codec = new Base64();
byte[] encoded = codec.encode("Hello".getBytes());
println(new String(encoded)); // Outputs "SGVsbG8="
byte[] decoded = codec.decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
Base64 codec = new Base64();
String encoded = codec.encodeBase64String("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = new String(codec.decodeBase64(encoded));
println(decoded) // Outputs "Hello"
If you're working in a Spring project already, you may find their org.springframework.util.Base64Utils
class more ergonomic:
For direct byte arrays:
byte[] encoded = Base64Utils.encode("Hello".getBytes());
println(new String(encoded)) // Outputs "SGVsbG8="
byte[] decoded = Base64Utils.decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
String encoded = Base64Utils.encodeToString("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = Base64Utils.decodeFromString(encoded);
println(new String(decoded)) // Outputs "Hello"
If you are using the Android SDK before Java 8 then your best option is to use the bundled android.util.Base64
.
For direct byte arrays:
byte[] encoded = Base64.encode("Hello".getBytes());
println(new String(encoded)) // Outputs "SGVsbG8="
byte [] decoded = Base64.decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
String encoded = Base64.encodeToString("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = new String(Base64.decode(encoded));
println(decoded) // Outputs "Hello"
I was in a weird situation in VS2019 where choosing View -> Report Data did nothing, and pressing Ctrl-Alt-D did nothing. The Report Data window had just strangely appeared on the left for no reason, when it was supposed to be on the right, and so I had moved it back to the right and then made it auto-hide. Not long after that it disappeared and would refuse to reappear. Possibly it was off-screen but hard to say.
To fix, I had to resort to using Window -> Reset Window Layout which restored its position and I was able to use it again.
Well, as others have stated, ambiguity in type is the issue. So the answer is no, C# doesn't let that happen because it's a strongly typed language, and it deals only with compile time known types. The compiler could have been designed to infer it as of type object
, but the designers chose to avoid the extra complexity (in C# null
has no type).
One alternative is
var foo = new { }; //anonymous type
Again note that you're initializing to a compile time known type, and at the end its not null
, but anonymous object. It's only a few lines shorter than new object()
. You can only reassign the anonymous type to foo
in this one case, which may or may not be desirable.
Initializing to null
with type not being known is out of question.
Unless you're using dynamic
.
dynamic foo = null;
//or
var foo = (dynamic)null; //overkill
Of course it is pretty useless, unless you want to reassign values to foo
variable. You lose intellisense support as well in Visual Studio.
Lastly, as others have answered, you can have a specific type declared by casting;
var foo = (T)null;
So your options are:
//initializes to non-null; I like it; cant be reassigned a value of any type
var foo = new { };
//initializes to non-null; can be reassigned a value of any type
var foo = new object();
//initializes to null; dangerous and finds least use; can be reassigned a value of any type
dynamic foo = null;
var foo = (dynamic)null;
//initializes to null; more conventional; can be reassigned a value of any type
object foo = null;
//initializes to null; cannot be reassigned a value of any type
var foo = (T)null;
template <class outType, class inType>
outType safe_cast(inType pointer)
{
void* temp = static_cast<void*>(pointer);
return static_cast<outType>(temp);
}
I tried to conclude and wrote a simple safe cast using templates. Note that this solution doesn't guarantee to cast pointers on a functions.
Once you have a JArray you can treat it just like any other Enumerable object, and using linq you can access them, check them, verify them, and select them.
var str = @"[1, 2, 3]";
var jArray = JArray.Parse(str);
Console.WriteLine(String.Join("-", jArray.Where(i => (int)i > 1).Select(i => i.ToString())));
To reset your keyring.
Go into your home folder.
Press ctrl & h to show your hidden folders.
Now look in your .gnome2/keyrings directory.
Find the default.keyring file.
Move that file to a different folder.
Once done, reboot your computer.
I've had to do something like this when using commons-httpclient to access an internal https server with a self-signed certificate. Yes, our solution was to create a custom TrustManager that simply passed everything (logging a debug message).
This comes down to having our own SSLSocketFactory that creates SSL sockets from our local SSLContext, which is set up to have only our local TrustManager associated with it. You don't need to go near a keystore/certstore at all.
So this is in our LocalSSLSocketFactory:
static {
try {
SSL_CONTEXT = SSLContext.getInstance("SSL");
SSL_CONTEXT.init(null, new TrustManager[] { new LocalSSLTrustManager() }, null);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Unable to initialise SSL context", e);
} catch (KeyManagementException e) {
throw new RuntimeException("Unable to initialise SSL context", e);
}
}
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
LOG.trace("createSocket(host => {}, port => {})", new Object[] { host, new Integer(port) });
return SSL_CONTEXT.getSocketFactory().createSocket(host, port);
}
Along with other methods implementing SecureProtocolSocketFactory. LocalSSLTrustManager is the aforementioned dummy trust manager implementation.
check this tip. worked for here http://mobeer.blogspot.com/2009/01/excel-2007-cannot-empty-clipboard.html:
This might save somebody some time and headaches if google picks it up. I was getting a 'Cannot empty the Clipboard' error every time I moved cells around in Excel - eventually I mucked around with the settings and made it go away. Here's how; In the excel main menu (glass globe w/logo), click Excel options, then Advanced, then turn off 'Show paste options buttons'
How exciting was this as my first post of the year?
Update: I still haven't found a permanent solution but I found another thing that seems to help. In Excel 2007, from the "home" tab, the first thing on the left is the clipboard tool panel. Expand the panel to view the clipboard and in the clipboard you might find "cannot empty clipboard" as an entry. Empty the clipboard, keep the panel open for a second or two while you do a few cut and pastes/drags etc. and then the bogey seems to go away.
I call this the cable dance because back in the day I had a printer that only worked if you unplugged the cable, shook it out and plugged it back in.
edit the init.py file in your project origin directory
import pymysql
pymysql.install_as_MySQLdb()
If you have arrived here via google, please make sure to check that you have given self as the first parameter to a class function. Especially if you try to reference values for that object instance inside the class function.
def foo():
print(self.bar)
>NameError: name 'self' is not defined
def foo(self):
print(self.bar)
It's working as intended. Your MySQL server has been started with --secure-file-priv option which basically limits from which directories you can load files using LOAD DATA INFILE
.
You may use SHOW VARIABLES LIKE "secure_file_priv";
to see the directory that has been configured.
You have two options:
secure-file-priv
.secure-file-priv
. This must be removed from startup and cannot be modified dynamically. To do this check your MySQL start up parameters (depending on platform) and my.ini.You can just adjust your constraints:
where T : class
Then returning null is allowed.
One of the problem with this code is here :
name += contactName[];
This instruction won't insert anything in the array. Instead it will concatenate the current value of the variable name with the string representation of the contactName array.
Instead use this:
contactName[index] = name;
this instruction will store the variable name in the contactName array at the index index
.
The second problem you have is that you don't have the variable index
.
What you can do is a loop with 12 iterations to fill all your arrays. (and index
will be your iteration variable)
If you are using tortoise git you can right-click on a file and git a diff by: Right-clicking on the first file and through the tortoisegit submenu select "Diff later" Then on the second file you can also right-click on this, go to the tortoisegit submenu and then select "Diff with yourfilenamehere.txt"
One of reasons why you will get this Notice: Array to string conversion in… is that you are combining group of arrays. Example, sorting out several first and last names.
To echo elements of array properly, you can use the function, implode(separator, array)
Example:
implode(' ', $var)
result:
first name[1], last name[1]
first name[2], last name[2]
More examples from W3C.
Here is a dplyr
way to go about it:
#df[ -c(1,3:6, 12) ] # original
df.cut <- df %>% select(-col.to.drop.1, -col.to.drop.2, ..., -col.to.drop.6) # with dplyr::select()
I like this because it's intuitive to read & understand without annotation and robust to columns changing position within the data frame. It also follows the vectorized idiom using -
to remove elements.
You can use any of the following methods for setting the Drawable on TextView:
1- setCompoundDrawablesWithIntrinsicBounds(int, int, int, int)
2- setCompoundDrawables(Left_Drawable, Top_Drawable, Right_Drawable, Bottom_Drawable)
And to get drawable from resources you can use:
getResources().getDrawable(R.drawable.your_drawable_id);
Here is an example :
=begin
print "Give me a number:"
number = gets.chomp.to_f
total = number * 10
puts "The total value is : #{total}"
=end
Everything you place in between =begin
and =end
will be treated as a comment regardless of how many lines of code it contains between.
Note: Make sure there is no space between =
and begin
:
=begin
= begin
Short answer: You can't. rm
removes files blindly, with no concept of 'trash'.
Some Unix and Linux systems try to limit its destructive ability by aliasing it to rm -i
by default, but not all do.
Long answer: Depending on your filesystem, disk activity, and how long ago the deletion occured, you may be able to recover some or all of what you deleted. If you're using an EXT3 or EXT4 formatted drive, you can check out extundelete
.
In the future, use rm
with caution. Either create a del
alias that provides interactivity, or use a file manager.
If you paste the listing into your word processor instead of Notepad, (since each file name is in quotation marks with the full path name), you can highlight all the stuff you don't want on the first file, then use Find and Replace to replace every occurrence of that with nothing. Same with the ending quote (").
It makes a nice clean list of file names.
I wrote the following function in order to determine if an multidimensional array partially contains a certain value.
function findKeyValue ($array, $needle, $value, $found = false){
foreach ($array as $key => $item){
// Navigate through the array completely.
if (is_array($item)){
$found = $this->findKeyValue($item, $needle, $value, $found);
}
// If the item is a node, verify if the value of the node contains
// the given search parameter. E.G.: 'value' <=> 'This contains the value'
if ( ! empty($key) && $key == $needle && strpos($item, $value) !== false){
return true;
}
}
return $found;
}
Call the function like this:
$this->findKeyValue($array, $key, $value);
Using the Java client of Kafka 2.11-1.0.0, you can do the following thing :
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Collections.singletonList("test"));
while(true) {
ConsumerRecords<String, String> records = consumer.poll(100);
for (ConsumerRecord<String, String> record : records) {
System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
// after each message, query the number of messages of the topic
Set<TopicPartition> partitions = consumer.assignment();
Map<TopicPartition, Long> offsets = consumer.endOffsets(partitions);
for(TopicPartition partition : offsets.keySet()) {
System.out.printf("partition %s is at %d\n", partition.topic(), offsets.get(partition));
}
}
}
Output is something like this :
offset = 10, key = null, value = un
partition test is at 13
offset = 11, key = null, value = deux
partition test is at 13
offset = 12, key = null, value = trois
partition test is at 13
I finally understood the problem:
methodA() {
methodB()
}
@Transactional(noRollbackFor = Exception.class)
methodB() {
...
try {
methodC()
} catch (...) {...}
log("OK");
}
@Transactional
methodC() {
throw new ...();
}
What happens is that even though the methodB
has the right annotation, the methodC
does not. When the exception is thrown, the second @Transactional
marks the first transaction as Rollback only anyway.