This works for me every time:
navigator.geolocation.getCurrentPosition(getCoor, errorCoor, {maximumAge:60000, timeout:5000, enableHighAccuracy:true});
Though it isn't very accurate. The funny thing is that on the same device if I run this it puts me off about 100 meters (every time), but if I go to google's maps it finds my location exactly. So although I think the enableHighAccuracy: true helps it to work consistently, it doesn't seem to make it any more accurate...
If it is a string
then use the built in float
on it to do the conversion for instance:
print( "%.5f" % float("1.43572e-03"))
answer:0.00143572
Why not just use:
$("#foo span")
or
$("#foo > span")
$('span', $('#foo'));
works fine on my machine ;)
function(url,callback){
request(url).on('data',(data) => {
try{
var json = JSON.parse(data);
}
catch(error){
callback("");
}
callback(json);
})
}
You can also use this. This is to async flow. The error comes when the response is not a JSON. Also in 404 status code .
Do not forget that to draw shadow you must use hardwareAccelerated
drawing
hardwareAccelerated = true
hardwareAccelerated = false
See Android Hardware Acceleration for details
You need to add junit
library to the classpath of your project. There are several choices to achieve it depending on your development setup.
Command line: In the case of command line invocations, you will have to add junit.jar
to the classpath of your application with java -cp /path/to/junit.jar
. Take a look at the answers here.
Using eclipse: Eclipse distributions are bundled with this library and this is how you can use it for your project. Right click on the eclipse project and navigate:
Properties -> Java Build Path -> Libraries -> Add Library -> JUnit -> Junit 3/4
In the scenarios where you want to use a different version of the jar, instead of clicking on Add Library above you should click on Add External Jar and locate the library on the file system.
Using show()
adds display:block
in place of display:hide
which might break things.
To avoid that, you can have a class with property display:none
and toggle that class for that element with toggleClass()
.
$("button").on('click', function(event){ $("div").toggleClass("hide"); });
_x000D_
.hide{_x000D_
display:none;_x000D_
}_x000D_
_x000D_
div{_x000D_
width:40px;_x000D_
height:40px;_x000D_
background:#000;_x000D_
margin-bottom:20px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div></div>_x000D_
<button>Toggle Box</button>
_x000D_
None of the answers mentioned this.
Simply you cannot do it with FF3.
The other option could be using applet or other controls to select and upload files.
While there are many ways to skin this cat, I prefer to wrap such code into reusable extension methods that make it trivial to do going forward. When using extension methods, you can also avoid RegEx as it is slower than a direct character check. I like using the extensions in the Extensions.cs NuGet package. It makes this check as simple as:
using Extensions;
" to the top of your code."smith23".IsAlphaNumeric()
will return True whereas "smith 23".IsAlphaNumeric(false)
will return False. By default the .IsAlphaNumeric()
method ignores spaces, but it can also be overridden as shown above. If you want to allow spaces such that "smith 23".IsAlphaNumeric()
will return True, simple default the arg.MyString.IsAlphaNumeric()
.I got this sort of message when I had two files that depended on each other. The tricky thing here is that you'll get a circular reference if you just try to import each other (class A imports class B, class B imports class A) from their header files. So what you would do is instead place a forward (@class A
) declaration in one of the classes' (class B's) header file. However, when attempting to use an ivar of class A within the implementation of class B, this very error comes up, merely adding an #import "A.h"
in the .m file of class B fixed the problem for me.
Give name and values to those submit buttons like:
<td>
<input type="submit" name='mybutton' class="noborder" id="save" value="save" alt="Save" tabindex="4" />
</td>
<td>
<input type="submit" name='mybutton' class="noborder" id="publish" value="publish" alt="Publish" tabindex="5" />
</td>
and then in your php script you could check
if($_POST['mybutton'] == 'save')
{
///do save processing
}
elseif($_POST['mybutton'] == 'publish')
{
///do publish processing here
}
Here are the various ways to do this so you can compare how it looks and choose what you like. I've ordered them in a way that I think is most "pythonic", and commented the pros and cons that might not be obvious at first glance:
Using collections.defaultdict
:
import collections
dict_x = collections.defaultdict(list)
...
dict_x[key].append(value)
Pros: Probably best performance. Cons: Not available in Python 2.4.x.
Using dict().setdefault()
:
dict_x = {}
...
dict_x.setdefault(key, []).append(value)
Cons: Inefficient creation of unused list()
s.
Using try ... except
:
dict_x = {}
...
try:
values = dict_x[key]
except KeyError:
values = dict_x[key] = []
values.append(value)
Or:
try:
dict_x[key].append(value)
except KeyError:
dict_x[key] = [value]
You can do this easily with the KoGrid plugin for KnockoutJS.
<script type="text/javascript">
$(function () {
window.viewModel = {
myObsArray: ko.observableArray([
{ id: 1, firstName: 'John', lastName: 'Doe', createdOn: '1/1/2012', birthday: '1/1/1977', salary: 40000 },
{ id: 1, firstName: 'Jane', lastName: 'Harper', createdOn: '1/2/2012', birthday: '2/1/1976', salary: 45000 },
{ id: 1, firstName: 'Jim', lastName: 'Carrey', createdOn: '1/3/2012', birthday: '3/1/1985', salary: 60000 },
{ id: 1, firstName: 'Joe', lastName: 'DiMaggio', createdOn: '1/4/2012', birthday: '4/1/1991', salary: 70000 }
])
};
ko.applyBindings(viewModel);
});
</script>
<div data-bind="koGrid: { data: myObsArray }">
Building off @Warewolf's answer, the next step is to create your own custom cell.
Go to File -> New -> File -> User Interface -> Empty -> Call
this nib "customNib"
.
In your customNib
drag a UICollectionView
Cell in. Give it reuse cell identifier @"Cell"
.
File -> New -> File -> Cocoa Touch Class -> Class
named "CustomCollectionViewCell"
subclass if UICollectionViewCell
.
Go back to the custom nib, click cell and make this custom class "CustomCollectionViewCell"
.
Go to your viewDidLoad
viewcontroller
and instead of
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
have
UINib *nib = [UINib nibWithNibName:@"customNib" bundle:nil];
[_collectionView registerNib:nib forCellWithReuseIdentifier:@"Cell"];
Also, change (to your new cell identifier)
UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
http://www.cplusplus.com/reference/clibrary/cstring/strtok/
Take a look at this, and use whitespace characters as the delimiter. If you need more hints let me know.
From the website:
char * strtok ( char * str, const char * delimiters );
On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of last token as the new starting location for scanning.
Once the terminating null character of str is found in a call to strtok, all subsequent calls to this function (with a null pointer as the first argument) return a null pointer.
Parameters
- str
- C string to truncate.
- Notice that this string is modified by being broken into smaller strings (tokens). Alternativelly [sic], a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended.
- delimiters
- C string containing the delimiter characters.
- These may vary from one call to another.
Return Value
A pointer to the last token found in string. A null pointer is returned if there are no tokens left to retrieve.
Example
/* strtok example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
return 0;
}
You just missed an extra pair of brackets for the "OR" symbol. The following should do the trick:
([0-9]+)\s+((\bseconds\b)|(\bminutes\b))
Without those you were either matching a number followed by seconds OR just the word minutes
Since this question not satisfied with provided answer, I would like to add this answer :)
public class CustomArrayList<T>
{
private T[] arr; private int count;
public int Count
{
get
{
return this.count;
}
}
private const int INITIAL_CAPACITY = 4;
public CustomArrayList(int capacity = INITIAL_CAPACITY)
{
this.arr = new T[capacity]; this.count = 0;
}
public void Add(T item)
{
GrowIfArrIsFull();
this.arr[this.count] = item; this.count++;
}
public void Insert(int index, T item)
{
if (index > this.count || index < 0)
{
throw new IndexOutOfRangeException( "Invalid index: " + index);
}
GrowIfArrIsFull();
Array.Copy(this.arr, index, this.arr, index + 1, this.count - index);
this.arr[index] = item; this.count++; }
private void GrowIfArrIsFull()
{
if (this.count + 1 > this.arr.Length)
{
T[] extendedArr = new T[this.arr.Length * 2];
Array.Copy(this.arr, extendedArr, this.count);
this.arr = extendedArr;
}
}
}
}
Running
git remote set-head origin --auto
followed by
git gc
If you're searching for hits within a larger text, you don't want to use ^
and $
as some other responders have said; those match the beginning and end of the text. Try this instead:
\bdbo\.\w+_fn\b
\b
is a word boundary: it matches a position that is either preceded by a word character and not followed by one, or followed by a word character and not preceded by one. This regex will find what you're looking for in any of these strings:
dbo.functionName_fn
foo dbo.functionName_fn bar
(dbo.functionName_fn)
...but not in this one:
foodbo.functionName_fnbar
\w+
matches one or more "word characters" (letters, digits, or _
). If you need something more inclusive, you can try \S+
(one or more non-whitespace characters) or .+?
(one or more of any characters except linefeeds, non-greedily). The non-greedy +?
prevents it from accidentally matching something like dbo.func1_fn dbo.func2_fn
as if it were just one hit.
Select everything, or whatever you want to re-indent and do Alt+ E+L+R. This is really quick and painless.
You can revert a commit using git revert HEAD^
for reverting to the next-to-last commit. You can also specify the commit to revert using the id instead of HEAD^
Try replacing the string literal for date '1989-12-09'
with TO_DATE('1989-12-09','YYYY-MM-DD')
JavaScript's forEach works a bit different from how one might be used to from other languages for each loops. If reading on the MDN, it says that a function is executed for each of the elements in the array, in ascending order. To continue to the next element, that is, run the next function, you can simply return the current function without having it do any computation.
Adding a return and it will go to the next run of the loop:
var myArr = [1,2,3,4];_x000D_
_x000D_
myArr.forEach(function(elem){_x000D_
if (elem === 3) {_x000D_
return;_x000D_
}_x000D_
_x000D_
console.log(elem);_x000D_
});
_x000D_
Output: 1, 2, 4
I chose to strip these characters out of the string by doing this -
ini_set('mbstring.substitute_character', "none");
$text= mb_convert_encoding($text, 'UTF-8', 'UTF-8');
PreparedStatement ps=con.prepareStatement("select * from stud");
ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
System.out.println("columns: "+rsmd.getColumnCount());
System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));
This example might be seem a bit lengthy, but its intention should be quite clear.
It uses 3 Boolean properties in the ViewModel called, FlagForValue1
, FlagForValue2
and FlagForValue3
.
Each of these 3 properties is backed by a single private field called _intValue
.
The 3 Radio buttons of the view (xaml) are each bound to its corresponding Flag property in the view model. This means the radio button displaying "Value 1" is bound to the FlagForValue1
bool property in the view model and the other two accordingly.
When setting one of the properties in the view model (e.g. FlagForValue1
), its important to also raise property changed events for the other two properties (e.g. FlagForValue2
, and FlagForValue3
) so the UI (WPF INotifyPropertyChanged
infrastructure) can selected / deselect each radio button correctly.
private int _intValue;
public bool FlagForValue1
{
get
{
return (_intValue == 1) ? true : false;
}
set
{
_intValue = 1;
RaisePropertyChanged("FlagForValue1");
RaisePropertyChanged("FlagForValue2");
RaisePropertyChanged("FlagForValue3");
}
}
public bool FlagForValue2
{
get
{
return (_intValue == 2) ? true : false;
}
set
{
_intValue = 2;
RaisePropertyChanged("FlagForValue1");
RaisePropertyChanged("FlagForValue2");
RaisePropertyChanged("FlagForValue3");
}
}
public bool FlagForValue3
{
get
{
return (_intValue == 3) ? true : false;
}
set
{
_intValue = 3;
RaisePropertyChanged("FlagForValue1");
RaisePropertyChanged("FlagForValue2");
RaisePropertyChanged("FlagForValue3");
}
}
The xaml looks like this:
<RadioButton GroupName="Search" IsChecked="{Binding Path=FlagForValue1, Mode=TwoWay}"
>Value 1</RadioButton>
<RadioButton GroupName="Search" IsChecked="{Binding Path=FlagForValue2, Mode=TwoWay}"
>Value 2</RadioButton>
<RadioButton GroupName="Search" IsChecked="{Binding Path=FlagForValue3, Mode=TwoWay}"
>Value 3</RadioButton>
If the string has always the same format, a simple substr()
should suffice.
var newString = originalStrint.substr(4)
I believe this would be somewhere close.
INSERT INTO Files
(FileId, FileData)
SELECT 1, * FROM OPENROWSET(BULK N'C:\Image.jpg', SINGLE_BLOB) rs
Something to note, the above runs in SQL Server 2005 and SQL Server 2008 with the data type as varbinary(max)
. It was not tested with image as data type.
operator bool() const
{
return col != 0;
}
Defines how the class is convertable to a boolean value, the const
after the ()
is used to indicate this method does not mutate (change the members of this class).
You would usually use such operators as follows:
airplaysdk sdkInstance;
if (sdkInstance) {
std::cout << "Instance is active" << std::endl;
} else {
std::cout << "Instance is in-active error!" << std::endl;
}
from datetime import datetime
a = datetime.strptime(f, "%Y-%m-%d")
Try this:
$('#parent').on('click', '#child', function() {
// Code
});
From the $.on()
documentation:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to
.on()
.
Your #child
element doesn't exist when you call $.on()
on it, so the event isn't bound (unlike $.live()
). #parent
, however, does exist, so binding the event to that is fine.
The second argument in my code above acts as a 'filter' to only trigger if the event bubbled up to #parent
from #child
.
Either add an event listener, or have the image announce itself with onload. Then figure out the dimensions from there.
<img id="photo"
onload='loaded(this.id)'
src="a_really_big_file.jpg"
alt="this is some alt text"
title="this is some title text" />
Have you tried:
pip install <package>
or
conda install -c conda-forge <package>
document.location is deprecated in favor of window.location, which can be accessed by just location, since it's a global object.
The location object has multiple properties and methods. If you try to use it as a string then it acts like location.href.
If you mean HashCode as in .GetHashCode()
, I'm afraid you can't go back. Hash functions are not bi-directional, you can go 'forward' only, not back.
Follow Oded's suggestion if you need to get the color based on the hexadecimal value of the color.
If you really want the runtime type to be util.Date then just do this:
java.util.Date utilDate = new java.util.Date(sqlDate.getTime());
Brian.
This is my way of doing it. It may be useful to others :
private void updateType(){
// Log.i(TAG,"updateType");
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// running on main thread-------
try {
JSONObject res = new JSONObject(response);
res.getString("result");
System.out.println("Response:" + res.getString("result"));
}else{
CustomTast ct=new CustomTast(context);
ct.showCustomAlert("Network/Server Disconnected",R.drawable.disconnect);
}
} catch (Exception e) {
e.printStackTrace();
//Log.e("Response", "==> " + e.getMessage());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
// running on main thread-------
VolleyLog.d(TAG, "Error: " + volleyError.getMessage());
}
}) {
protected Map<String, String> getParams() {
HashMap<String, String> hashMapParams = new HashMap<String, String>();
hashMapParams.put("key", "value");
hashMapParams.put("key", "value");
hashMapParams.put("key", "value"));
hashMapParams.put("key", "value");
System.out.println("Hashmap:" + hashMapParams);
return hashMapParams;
}
};
AppController.getInstance().addToRequestQueue(request);
}
Github is required if you want to collaborate across developers. If you are a single contributor git is enough, make sure you backup your code on regular basis
If the servers are clustered and there is a clustered DTC you have to disable security on the clustered DTC not the local DTC.
For text area we can use below css to fix size
<textarea class="form-control" style=" min-width:500px; max-width:100%;min-height:50px;height:100%;width:100%;" ></textarea>
Tested in angularjs and angular7
I run it like AndroidStudio does:
am start -n "com.example.app.dev/com.example.app.phonebook.PhoneBookActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
If you have product flavour like dev
, it should occur only in application package name but shouldn't occur in activity package name.
For emulator, it works without android:exported="true"
flag on activity in AndroidManifest.xml
but I found it useful to add it for unrooted physical device to make it work.
PHP also has money_format().
Here's an example:
echo money_format('$%i', 3.4); // echos '$3.40'
This function actually has tons of options, go to the documentation I linked to to see them.
Note: money_format is undefined in Windows.
UPDATE: Via the PHP manual: https://www.php.net/manual/en/function.money-format.php
WARNING: This function [money_format] has been DEPRECATED as of PHP 7.4.0. Relying on this function is highly discouraged.
Instead, look into NumberFormatter::formatCurrency.
$number = "123.45";
$formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
return $formatter->formatCurrency($number, 'USD');
By dynamically allocating a Movie object with new Movie()
, you get a pointer to the new object. You do not need a second vector for the movies, just store the pointers and you can access them. Like Brian wrote, the vector would be defined as
std::vector<Movie *> movies
But be aware that the vector will not delete your objects afterwards, which will result in a memory leak. It probably doesn't matter for your homework, but normally you should delete all pointers when you don't need them anymore.
For some reason no one has mentioned the fact that the bashrc needs to be re-sourced after editing. You can either log out and log back in (like mentioned above) but you can also use the commands: source ~/.bashrc
or . ~/.bashrc
.
/WebKit/.test(navigator.userAgent)
— that's it.
If you mean, you want to scroll through multiple items in your stackpanel, try putting a grid around it. By definition, a stackpanel has infinite length.
So try something like this:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<StackPanel Width="311">
<TextBlock Text="{Binding A}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" FontStretch="Condensed" FontSize="28" />
<TextBlock Text="{Binding B}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
</StackPanel>
</Grid>
You could even make this work with a ScrollViewer
Being form
a block element, you can center-align it by setting its side margins to auto:
form { margin: 0 auto; }
EDIT:
As @moomoochoo correctly pointed out, this rule will only work if the block element (your form, in this case) has been assigned a specific width.
Also, this 'trick' will not work for floating elements.
View controls (TextView, EditText, Button, Image, etc) all have a visibility property. This can be set to one of three values:
Visible - Displayed
android:visibility="visible"
Invisible - Hidden but space reserved
android:visibility="invisible"
Gone - Hidden completely
android:visibility="gone"
To set the visibility in code use the public constant available in the static View class:
Button button1 = (TextView)findViewById(R.id.button1);
button1.setVisibility(View.VISIBILE);
Check via Google, there are lots of examples, see here for one.
Inlined for ease of viewing:
import win32com.client
def send_mail_via_com(text, subject, recipient, profilename="Outlook2003"):
s = win32com.client.Dispatch("Mapi.Session")
o = win32com.client.Dispatch("Outlook.Application")
s.Logon(profilename)
Msg = o.CreateItem(0)
Msg.To = recipient
Msg.CC = "moreaddresses here"
Msg.BCC = "address"
Msg.Subject = subject
Msg.Body = text
attachment1 = "Path to attachment no. 1"
attachment2 = "Path to attachment no. 2"
Msg.Attachments.Add(attachment1)
Msg.Attachments.Add(attachment2)
Msg.Send()
Just use the function plot
as follows
figure()
...
plot(t, a)
plot(t, b)
plot(t, c)
Use this way so that result will not be displayed while running stored procedure.
The query:
SELECT a.strUserID FROM tblUsers a WHERE a.lngUserID = lngUserID LIMIT 1 INTO @strUserID;
Well, even the accepted answer does not exactly output what op has asked for. It outputs the JSON string but with "
characters escaped. So, although might be a little late, I am answering hopeing it will help people! Here is how I do it:
StringWriter writer = new StringWriter();
JsonGenerator jgen = new JsonFactory().createGenerator(writer);
jgen.setCodec(new ObjectMapper());
jgen.writeObject(object);
jgen.close();
System.out.println(writer.toString());
You could try this:
find. -name *.ear -exec du {} \;
This will give you the size in bytes. But the du command also accepts the parameters -k for KB and -m for MB. It will give you an output like
5000 ./dir1/dir2/earFile1.ear
5400 ./dir1/dir2/earFile2.ear
5400 ./dir1/dir3/earFile1.ear
Sounds easier to do with the standard classes:
std::complex<double> vecA(0,1);
std::complex<double> i(0,1); // 90 degrees
std::complex<double> r45(sqrt(2.0),sqrt(2.0));
vecA *= i;
vecA *= r45;
Vector rotation is a subset of complex multiplication. To rotate over an angle alpha
, you multiply by std::complex<double> { cos(alpha), sin(alpha) }
Put the APK file into the tools folder in the Android SDK and give the path to tools in the command prompt and use the command:
adb install "name".apk file
To get the definition of the SQL codes, the easiest way is to use db2 cli!
at the unix or dos command prompt, just type
db2 "? SQL302"
this will give you the required explanation of the particular SQL code that you normally see in the java exception or your db2 sql output :)
hope this helped.
The Flexible
does the trick
new Container(
child: Row(
children: <Widget>[
Flexible(
child: new Text("A looooooooooooooooooong text"))
],
));
This is the official doc https://flutter.dev/docs/development/ui/layout#lay-out-multiple-widgets-vertically-and-horizontally on how to arrange widgets.
Remember that Flexible
and also Expanded
, should only be used within a Column
, Row
or Flex
, because of the Incorrect use of ParentDataWidget
.
The solution is not the mere Flexible
To draw a centered text:
TextRenderer.DrawText(g, "my text", Font, Bounds, ForeColor, BackColor,
TextFormatFlags.HorizontalCenter |
TextFormatFlags.VerticalCenter |
TextFormatFlags.GlyphOverhangPadding);
Determining optimal font size to fill an area is a bit more difficult. One working soultion I found is trial-and-error: start with a big font, then repeatedly measure the string and shrink the font until it fits.
Font FindBestFitFont(Graphics g, String text, Font font,
Size proposedSize, TextFormatFlags flags)
{
// Compute actual size, shrink if needed
while (true)
{
Size size = TextRenderer.MeasureText(g, text, font, proposedSize, flags);
// It fits, back out
if ( size.Height <= proposedSize.Height &&
size.Width <= proposedSize.Width) { return font; }
// Try a smaller font (90% of old size)
Font oldFont = font;
font = new Font(font.FontFamily, (float)(font.Size * .9));
oldFont.Dispose();
}
}
You'd use this as:
Font bestFitFont = FindBestFitFont(g, text, someBigFont, sizeToFitIn, flags);
// Then do your drawing using the bestFitFont
// Don't forget to dispose the font (if/when needed)
If you want a good format the next statement is the best:
dataframe_prediction.to_csv('filename.csv', sep=',', encoding='utf-8', index=False)
In this case you have got a csv file with ',' as separate between columns and utf-8 format. In addition, numerical index won't appear.
if ( ( single conditional expression A )
&& ( single conditional expression B )
&& ( single conditional expression C )
)
{
opAllABC();
}
else
{
opNoneABC();
}
Formatting a multiple conditional expressions in an if-else statement this way:
// disable any single conditional test with just a pre-pended '//'
// set a break point before any individual test
// syntax '(1 &&' and '(0 ||' usually never creates any real code
if ( 1
&& ( single conditional expression A )
&& ( single conditional expression B )
&& ( 0
|| ( single conditional expression C )
|| ( single conditional expression D )
)
)
{
... ;
}
else
{
... ;
}
This alternative seems the most appropriate.
$('input[type="file"]').change(function(e){
var fileName = e.target.files[0].name;
alert('The file "' + fileName + '" has been selected.');
});
Finally, Anaconda3-2020.07 is out and its core is Python 3.8!
You can now download Anaconda packed with Python 3.8 goodness at:
Uhm, what's wrong with this:
#include <iostream>
using namespace std;
int main(int, char **)
{
char c = 'A';
int x = c; // Look ma! No cast!
cout << "The character '" << c << "' has an ASCII code of " << x << endl;
return 0;
}
Easy, just define your own function that does what you want:
def enum(seq, start=0):
for i, x in enumerate(seq):
yield i+start, x
It might just be a connection string error, which is solved by the above process, but if you are using the dll's in multiple projects then making sure the connection string is named properly will fix the error for sure.
Dictionaries are for look ups. It makes sense to ask if an entry exists or not. Lists are usually iterated. It isn't common to ask if L[10] exists but rather if the length of L is 11.
Here's a VB.NET version I created, inspired by Joel Coehoorn's answer, Oliver's edit, and shaunmartin's comment:
<Extension()>
Public Function PadCenter(ByVal [string] As String, ByVal width As Integer, ByVal c As Char) As String
If [string] Is Nothing Then [string] = String.Empty
If (width <= [string].Length) Then Return [string]
Dim padding = width - [string].Length
Return [string].PadLeft([string].Length + (padding \ 2), c).PadRight(width, c)
End Function
<Extension()>
Public Function PadCenter(ByVal [string] As String, ByVal width As Integer) As String
If [string] Is Nothing Then [string] = String.Empty
If (width <= [string].Length) Then Return [string]
Dim padding = width - [string].Length
Return [string].PadLeft([string].Length + (padding \ 2)).PadRight(width)
End Function
This is set up as a string extension, inside a Public Module (the way you do Extensions in VB.NET, a bit different than C#). My slight change is that it treats a null string as an empty string, and it pads an empty string with the width value (meets my particular needs). Hopefully this will convert easily to C# for anyone who needs it. If there's a better way to reference the answers, edits, and comments I mentioned above, which inspired my post, please let me know and I'll do it - I'm relatively new to posting, and I couldn't figure out to leave a comment (might not have enough rep yet).
If you need to handle values that cannot be converted separately, you can use this method:
try {
$valueToUse = trim($stringThatMightBeNumeric) + 0;
} catch (\Throwable $th) {
// bail here if you need to
}
Another way is to use:
@model Tuple<LoginViewModel,RegisterViewModel>
I have explained how to use this method both in the view and controller for another example: Two models in one view in ASP MVC 3
In your case you could implement it using the following code:
In the view:
@using YourProjectNamespace.Models;
@model Tuple<LoginViewModel,RegisterViewModel>
@using (Html.BeginForm("Login1", "Auth", FormMethod.Post))
{
@Html.TextBoxFor(tuple => tuple.Item2.Name, new {@Name="Name"})
@Html.TextBoxFor(tuple => tuple.Item2.Email, new {@Name="Email"})
@Html.PasswordFor(tuple => tuple.Item2.Password, new {@Name="Password"})
}
@using (Html.BeginForm("Login2", "Auth", FormMethod.Post))
{
@Html.TextBoxFor(tuple => tuple.Item1.Email, new {@Name="Email"})
@Html.PasswordFor(tuple => tuple.Item1.Password, new {@Name="Password"})
}
Note that I have manually changed the Name attributes for each property when building the form. This needs to be done, otherwise it wouldn't get properly mapped to the method's parameter of type model when values are sent to the associated method for processing. I would suggest using separate methods to process these forms separately, for this example I used Login1 and Login2 methods. Login1 method requires to have a parameter of type RegisterViewModel and Login2 requires a parameter of type LoginViewModel.
if an actionlink is required you can use:
@Html.ActionLink("Edit", "Edit", new { id=Model.Item1.Id })
in the controller's method for the view, a variable of type Tuple needs to be created and then passed to the view.
Example:
public ActionResult Details()
{
var tuple = new Tuple<LoginViewModel, RegisterViewModel>(new LoginViewModel(),new RegisterViewModel());
return View(tuple);
}
or you can fill the two instances of LoginViewModel and RegisterViewModel with values and then pass it to the view.
You can use fs.promises
available natively since Node v11.0.0
import fs from 'fs';
const readFile = async filePath => {
try {
const data = await fs.promises.readFile(filePath, 'utf8')
return data
}
catch(err) {
console.log(err)
}
}
new Guid(string)
You could also look at using a TypeConverter
.
jQuery syntax mentioned above by Danilo Valente is not working. It should be as following-
$.extend(myFunction,{
bookName:'mybook',
bookdesc: 'new'
});
It seems don't find wsdl file..
I've solved adding wsdlLocation parameter at javax.jws.WebService annotation
You can find more information about the date pipe here, such as formats.
If you want to use it in your component, you can simply do
pipe = new DatePipe('en-US'); // Use your own locale
Now, you can simply use its transform method, which will be
const now = Date.now();
const myFormattedDate = this.pipe.transform(now, 'short');
My implementation)
const items = Array.from(document.querySelectorAll('.item'));_x000D_
items.forEach(item =>{_x000D_
item.style.color = checkEllipsis(item) ? 'red': 'black'_x000D_
})_x000D_
_x000D_
function checkEllipsis(el){_x000D_
const styles = getComputedStyle(el);_x000D_
const widthEl = parseFloat(styles.width);_x000D_
const ctx = document.createElement('canvas').getContext('2d');_x000D_
ctx.font = `${styles.fontSize} ${styles.fontFamily}`;_x000D_
const text = ctx.measureText(el.innerText);_x000D_
return text.width > widthEl;_x000D_
}
_x000D_
.item{_x000D_
width: 60px;_x000D_
overflow: hidden;_x000D_
text-overflow: ellipsis;_x000D_
}
_x000D_
<div class="item">Short</div>_x000D_
<div class="item">Loooooooooooong</div>
_x000D_
Create a file named jaxp.properties
(if it doesn’t exist) under path to your "JDK version/jre/lib" and then add the following line in it.
javax.xml.accessExternalSchema = all
Errors in the execution of aapt in task processDebugResources or processReleaseResources generally happen when one or more resources of your project are unsupported.
To find out go to the root dir of your project and run:
gradle processDebugResources --debug
This will print aapt specific error. In my case it was a file in the assets folder whose name had invalid character (LEÃO.jpg). aapt doesn't support some characters in the Latin alphabet.
But, as I explained your problem can be other than that. To know for sure you have to run processDebugResources with the option --debug.
It's equivalent to
def tag_names
@tag_names || tags.map { |tag| tag.name }.join(' ')
end
Try to use createChild() method of DOM or insertRow() and insertCell() method of table object in script tag.
In XML add one line inside <Toolbar/>
<com.google.android.material.appbar.MaterialToolbar
app:menu="@menu/main_menu"/>
In java file, replace this:
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle("Main Page");
}
with this:
toolbar.setTitle("Main Page")
byte[] bytes = new byte[100];
Initializes all byte elements with default values, which for byte is 0. In fact, all elements of an array when constructed, are initialized with default values for the array element's type.
If each file only has one sequence of aminoacids, I wouldn't use regular expressions at all. Just something like this:
def read_amino_acid_sequence(path):
with open(path) as sequence_file:
title = sequence_file.readline() # read 1st line
aminoacid_sequence = sequence_file.read() # read the rest
# some cleanup, if necessary
title = title.strip() # remove trailing white spaces and newline
aminoacid_sequence = aminoacid_sequence.replace(" ","").replace("\n","")
return title, aminoacid_sequence
If you want to host multiple websites in a single server in different ports then, method mentioned by MRVDOG won't work. Because browser won't resolve SRV records and will always hit :80
port.
For example if your requirement is:
site1.domain.com maps to domain.com:8080
site2.domain.com maps to domain.com:8081
Because often you want to fully utilize the server space you have bought. Then you can try the following:
Step 1: Install proxy server. I will use Nginx here.
apt-get install nginx
Step 2:
Edit /etc/nginx/nginx.conf
file to add the port mappings. To do so, add the following lines:
server {
listen 80;
server_name site1.domain.com;
location / {
proxy_pass http://localhost:8080;
}
}
server {
listen 80;
server_name site2.domain.com;
location / {
proxy_pass http://localhost:8081;
}
}
This does the magic. So the file will end up looking like following:
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;
events {
worker_connections 768;
# multi_accept on;
}
http {
##
# Basic Settings
##
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# server_tokens off;
# server_names_hash_bucket_size 64;
# server_name_in_redirect off;
include /etc/nginx/mime.types;
default_type application/octet-stream;
##
# SSL Settings
##
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_ciphers on;
##
# Logging Settings
##
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
##
# Gzip Settings
##
gzip on;
# gzip_vary on;
# gzip_proxied any;
# gzip_comp_level 6;
# gzip_buffers 16 8k;
# gzip_http_version 1.1;
# gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
##
# Virtual Host Configs
##
server {
listen 80;
server_name site1.domain.com;
location / {
proxy_pass http://localhost:8080;
}
}
server {
listen 80;
server_name site2.domain.com;
location / {
proxy_pass http://localhost:8081;
}
}
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
#mail {
# # See sample authentication script at:
# # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
# # auth_http localhost/auth.php;
# # pop3_capabilities "TOP" "USER";
# # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
# server {
# listen localhost:110;
# protocol pop3;
# proxy on;
# }
#
# server {
# listen localhost:143;
# protocol imap;
# proxy on;
# }
#}
Step 3: Start nginx:
/etc/init.d/nginx start
.
Whenever you make any changes to configuration, you need to restart nginx:
/etc/init.d/nginx restart
Finally: Don't forget to add A records in your DNS configuration. All subdomains should point to domain. Like this:
Put your static ip instead of 111.11.111.111
Further details:
The basic difference between Linear Regression and Logistic Regression is : Linear Regression is used to predict a continuous or numerical value but when we are looking for predicting a value that is categorical Logistic Regression come into picture.
Logistic Regression is used for binary classification.
It can be achieved using RelativeLayout
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:src="@drawable/icon"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true" />
</RelativeLayout>
You can use SEPARATOR and ORDER BY inside the GROUP_CONCAT function in this way:
SELECT li.client_id, group_concat(li.percentage ORDER BY li.views ASC SEPARATOR ',')
AS views, group_concat(li.percentage ORDER BY li.percentage ASC SEPARATOR ',') FROM li
GROUP BY client_id;
Properties prop = new Properties();
prop.load(...); // FileInputStream
prop.setProperty("key", "value");
prop.store(...); // FileOutputStream
Use
git show --summary `git merge-base foo master`
If you’d rather see it in context using gitk, then use
gitk --all --select-commit=`git merge-base foo master`
(where foo is the name of the branch you are looking for.)
I assume you have proper xml encoding and matching with Schema.
If you still get this error, check code that unmarshalls the xml and input type you have used. Because XML documents declare their own encoding, it is preferable to create a StreamSource object from an InputStream instead of from a Reader, so that XML processor can correctly handle the declared encoding [Ref Book: Java in A Nutshell ]
Hope this helps!
in kotlin do it as below by using html
HtmlCompat.fromHtml("<html><body><h1>This is Large Heading :-</h1><br>This is normal size<body></html>",HtmlCompat.FROM_HTML_MODE_LEGACY)
For fire base to install properly all the versions of the fire base compiles must be in same version so
compile 'com.google.firebase:firebase-messaging:11.0.4'
compile 'com.google.android.gms:play-services-maps:11.0.4'
compile 'com.google.android.gms:play-services-location:11.0.4'
this is the correct way to do it.
If you trying to fit the content according to the forms than the following will help. It helps me while I was trying to fit the content on the form to fit when ever the forms were resized.
this.contents.Size = new Size(this.ClientRectangle.Width, this.ClientRectangle.Height);
The first argument is the file you wish to execute, and the second argument is an array of null-terminated strings that represent the appropriate arguments to the file as specified in the man page.
For example:
char *cmd = "ls";
char *argv[3];
argv[0] = "ls";
argv[1] = "-la";
argv[2] = NULL;
execvp(cmd, argv); //This will run "ls -la" as if it were a command
First Create Bitmap Image
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.image);
now set bitmap in Notification Builder Icon....
Notification.Builder.setLargeIcon(bmp);
SELECT chargeId, chargeType, MAX(serviceMonth) AS serviceMonth
FROM invoice
GROUP BY chargeId, chargeType
There is no direct indexOf function in java arrays.
In bash, you can do pattern replacement in a string with the ${VARIABLE//PATTERN/REPLACEMENT}
construct. Use just /
and not //
to replace only the first occurrence. The pattern is a wildcard pattern, like file globs.
string='foo bar qux'
one="${string/ /.}" # sets one to 'foo.bar qux'
all="${string// /.}" # sets all to 'foo.bar.qux'
I do the following in my application:
Process process = new Process();
process.StartInfo.FileName = executable;
process.StartInfo.Arguments = arguments;
process.StartInfo.ErrorDialog = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
process.Start();
process.WaitForExit(1000 * 60 * 5); // Wait up to five minutes.
There are a few extra features in there which you might find useful...
I prefer to suppress an exception rather than checking for the file's existence, to avoid a TOCTTOU bug. Matt's answer is a good example of this, but we can simplify it slightly under Python 3, using contextlib.suppress()
:
import contextlib
with contextlib.suppress(FileNotFoundError):
os.remove(filename)
If filename
is a pathlib.Path
object instead of a string, we can call its .unlink()
method instead of using os.remove()
. In my experience, Path objects are more useful than strings for filesystem manipulation.
Since everything in this answer is exclusive to Python 3, it provides yet another reason to upgrade.
foreach($i=0; $i<10; $i++){
$v = @(array)$v;
// this could help defining $v as an array.
//@ is to supress undefined variable $v
array_push($v, $i);
}
If you are running your application on an emulator, and if this problem persists, check your notification manager. If it shows you an icon and notification about "Phone memory is full", that means you have already installed so many applications on your emulator. Uninstall several applications which you don't want currently from "Settings >> Manage Application >> Select Application >> Uninstall".
That Set.
Now re-run the program.
I done it, below code is working for me....
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.hello_world, container, false);
Button newPage = (Button)v.findViewById(R.id.click);
newPage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), HomeActivity.class);
startActivity(intent);
}
});
return v;
}
and Please make sure that your destination activity should be register in Manifest.xml file,
but in my case all tabs are not shown in HomeActivity, is any solution for that ?
One rather bad thing about singletons is that you can't extend them very easily. You basically have to build in some kind of decorator pattern or some such thing if you want to change their behavior. Also, if one day you want to have multiple ways of doing that one thing, it can be rather painful to change, depending on how you lay out your code.
One thing to note, if you DO use singletons, try to pass them in to whoever needs them rather than have them access it directly... Otherwise if you ever choose to have multiple ways of doing the thing that singleton does, it will be rather difficult to change as each class embeds a dependency if it accesses the singleton directly.
So basically:
public MyConstructor(Singleton singleton) {
this.singleton = singleton;
}
rather than:
public MyConstructor() {
this.singleton = Singleton.getInstance();
}
I believe this sort of pattern is called dependency injection and is generally considered a good thing.
Like any pattern though... Think about it and consider if its use in the given situation is inappropriate or not... Rules are made to be broken usually, and patterns should not be applied willy nilly without thought.
Yes, as @ggkmath said, sometimes a good old restart is exactly what you need. Like when "contact the author and have him rewrite the app, meanwhile wait" is not an option.
This happens when an application is not written (yet) in a way that it can handle restarts of the underlying database.
There are 2 ways you may install any package with version:- A). pip install -Iv package-name == version B). pip install -v package-name == version
For A
Here, if you're using -I option while installing(when you don't know if the package is already installed) (like 'pip install -Iv pyreadline == 2.* 'or something), you would be installing a new separate package with the same existing package having some different version.
For B
2.and then see what's already installed by pip list
3.if the list of the packages contain any package that you wish to install with specific version then the better option is to uninstall the package of this version first, by pip uninstall package-name
4.And now you can go ahead to reinstall the same package with a specific version, by pip install -v package-name==version e.g. pip install -v pyreadline == 2.*
Maybe you're not doing it as root?
Try sudo nginx -s reload
, if it still doesn't work, you might want to try sudo pkill -HUP nginx
.
This is probably what you need:
$text = str_replace(' ', '_', substr($text, 0, 10));
You can not alter constraints ever but you can drop them and then recreate.
Have look on this
ALTER TABLE your_table DROP CONSTRAINT ACTIVEPROG_FKEY1;
and then recreate it with ON DELETE CASCADE
like this
ALTER TABLE your_table
add CONSTRAINT ACTIVEPROG_FKEY1 FOREIGN KEY(ActiveProgCode) REFERENCES PROGRAM(ActiveProgCode)
ON DELETE CASCADE;
hope this help
You can use LinkedBlockingQueue I use it in my projects. It's part of standard java and quite easy to use
If you know some unix you could try the following:
Notes: $ means the command prompt
Say you have a file my_data.txt with content as such:
$ cat my_data.txt
This is a data file
with all of my data in it.
Then using the os
module you can use the usual sed
commands
import os
# Identifiers used are:
my_data_file = "my_data.txt"
command = "sed -i 's/all/none/' my_data.txt"
# Execute the command
os.system(command)
If you aren't aware of sed, check it out, it is extremely useful.
Here's an example script which demonstrates certificate validation:
import httplib
import re
import socket
import sys
import urllib2
import ssl
class InvalidCertificateException(httplib.HTTPException, urllib2.URLError):
def __init__(self, host, cert, reason):
httplib.HTTPException.__init__(self)
self.host = host
self.cert = cert
self.reason = reason
def __str__(self):
return ('Host %s returned an invalid certificate (%s) %s\n' %
(self.host, self.reason, self.cert))
class CertValidatingHTTPSConnection(httplib.HTTPConnection):
default_port = httplib.HTTPS_PORT
def __init__(self, host, port=None, key_file=None, cert_file=None,
ca_certs=None, strict=None, **kwargs):
httplib.HTTPConnection.__init__(self, host, port, strict, **kwargs)
self.key_file = key_file
self.cert_file = cert_file
self.ca_certs = ca_certs
if self.ca_certs:
self.cert_reqs = ssl.CERT_REQUIRED
else:
self.cert_reqs = ssl.CERT_NONE
def _GetValidHostsForCert(self, cert):
if 'subjectAltName' in cert:
return [x[1] for x in cert['subjectAltName']
if x[0].lower() == 'dns']
else:
return [x[0][1] for x in cert['subject']
if x[0][0].lower() == 'commonname']
def _ValidateCertificateHostname(self, cert, hostname):
hosts = self._GetValidHostsForCert(cert)
for host in hosts:
host_re = host.replace('.', '\.').replace('*', '[^.]*')
if re.search('^%s$' % (host_re,), hostname, re.I):
return True
return False
def connect(self):
sock = socket.create_connection((self.host, self.port))
self.sock = ssl.wrap_socket(sock, keyfile=self.key_file,
certfile=self.cert_file,
cert_reqs=self.cert_reqs,
ca_certs=self.ca_certs)
if self.cert_reqs & ssl.CERT_REQUIRED:
cert = self.sock.getpeercert()
hostname = self.host.split(':', 0)[0]
if not self._ValidateCertificateHostname(cert, hostname):
raise InvalidCertificateException(hostname, cert,
'hostname mismatch')
class VerifiedHTTPSHandler(urllib2.HTTPSHandler):
def __init__(self, **kwargs):
urllib2.AbstractHTTPHandler.__init__(self)
self._connection_args = kwargs
def https_open(self, req):
def http_class_wrapper(host, **kwargs):
full_kwargs = dict(self._connection_args)
full_kwargs.update(kwargs)
return CertValidatingHTTPSConnection(host, **full_kwargs)
try:
return self.do_open(http_class_wrapper, req)
except urllib2.URLError, e:
if type(e.reason) == ssl.SSLError and e.reason.args[0] == 1:
raise InvalidCertificateException(req.host, '',
e.reason.args[1])
raise
https_request = urllib2.HTTPSHandler.do_request_
if __name__ == "__main__":
if len(sys.argv) != 3:
print "usage: python %s CA_CERT URL" % sys.argv[0]
exit(2)
handler = VerifiedHTTPSHandler(ca_certs = sys.argv[1])
opener = urllib2.build_opener(handler)
print opener.open(sys.argv[2]).read()
import re
fancy = u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')'
print re.compile( "\((.*)\)" ).search( fancy ).group( 1 )
Assuming you are programming in Java, this works:
if (90 >= angle && angle <= 180 ) {
(don't you mean 90 is less than angle
? If so: 90 <= angle
)
their is no need to create asset directory and under it images directory and then you put image. Better is to just create Images directory inside your project where pubspec.yaml exist and put images inside it and access that images just like as shown in tutorial/documention
assets: - images/lake.jpg // inside pubspec.yaml
Set the z-index
of the :before
or :after
pseudo element to -1 and give it a position
that honors the z-index
property (absolute
, relative
, or fixed
). This works because the pseudo element's z-index
is relative to its parent element, rather than <html>
, which is the default for other elements. Which makes sense because they are child elements of <html>
.
The problem I was having (that lead me to this question and the accepted answer above) was that I was trying to use a :after
pseudo element to get fancy with a background to an element with z-index
of 15, and even when set with a z-index
of 14, it was still being rendered on top of its parent. This is because, in that stacking context, it's parent has a z-index
of 0.
Hopefully that helps clarify a little what's going on.
I couldn't respond to Mark above, but I just made one modification which fixed the error which was caused if data in the cells was not unicode, i.e. float or int data. I replaced this line into the UnicodeWriter function: "self.writer.writerow([s.encode("utf-8") if type(s)==types.UnicodeType else s for s in row])" so that it became:
class UnicodeWriter:
def __init__(self, f, dialect=csv.excel, encoding="utf-8-sig", **kwds):
self.queue = cStringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
self.encoder = codecs.getincrementalencoder(encoding)()
def writerow(self, row):
'''writerow(unicode) -> None
This function takes a Unicode string and encodes it to the output.
'''
self.writer.writerow([s.encode("utf-8") if type(s)==types.UnicodeType else s for s in row])
data = self.queue.getvalue()
data = data.decode("utf-8")
data = self.encoder.encode(data)
self.stream.write(data)
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
You will also need to "import types".
JFrame.dispose()
public void dispose()
Releases all of the native screen resources used by this Window, its subcomponents, and all of its owned children. That is, the resources for these Components will be destroyed, any memory they consume will be returned to the OS, and they will be marked as undisplayable. The Window and its subcomponents can be made displayable again by rebuilding the native resources with a subsequent call to pack or show. The states of the recreated Window and its subcomponents will be identical to the states of these objects at the point where the Window was disposed (not accounting for additional modifications between those actions).
Note: When the last displayable window within the Java virtual machine (VM) is disposed of, the VM may terminate. See AWT Threading Issues for more information.
System.exit()
public static void exit(int status)
Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination. This method calls the exit method in class Runtime. This method never returns normally.
The call System.exit(n)
is effectively equivalent to the call:
Runtime.getRuntime().exit(n)
The default (when created with the designer) is:
label.ForeColor = SystemColors.ControlText;
This should respect the system color settings (e.g. these "high contrast" schemes for visual impaired).
Try this just a little search in Google
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
I know, it is an old question, but no solution worked for me. Here is what I did:
USE master
GO
GRANT CREATE TABLE TO PUBLIC
Repeat this with every permission you need, for example GRANT CREATE DATABASE TO PUBLIC
, ...
You must have the server role "public" (yes, I am captain obvious).
Note 1: GRANT ALL TO PUBLIC
is deprecated, does not work anymore in 2017.
Note 2: I tried to build an msi installer using the wix toolset. This toolset calls a powershell file, wich creates the databases, ... Just to give you some background information :)
Shockingly, the syntax has changed yet again in the latest version of Angular :-) From the Angular 6 docs:
Beginning with Angular 6.0, the preferred way to create a singleton services is to specify on the service that it should be provided in the application root. This is done by setting providedIn to root on the service's @Injectable decorator:
src/app/user.service.0.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class UserService {
}
i had same problem i fix this using if developing jsp, put mysql connetor into WEB-INF->lib folder after puting that in eclipse right click and go build-path -> configure build patha in library tab add external jar file give location where lib folder is
For get response in JSON format :
1.$response = (string) $res->getBody();
$response =json_decode($response); // Using this you can access any key like below
$key_value = $response->key_name; //access key
2. $response = json_decode($res->getBody(),true);
$key_value = $response['key_name'];//access key
Using only CSS it is not possible at all to add links :) It is not possible to link a background-image, nor a part of it, using HTML/CSS. However, it can be staged using this method:
<div class="wrapWithBackgroundImage">
<a href="#" class="invisibleLink"></a>
</div>
.wrapWithBackgroundImage {
background-image: url(...);
}
.invisibleLink {
display: block;
left: 55px; top: 55px;
position: absolute;
height: 55px width: 55px;
}
You simply cannot. DataFrames
, same as other distributed data structures, are not iterable and can be accessed using only dedicated higher order function and / or SQL methods.
You can of course collect
for row in df.rdd.collect():
do_something(row)
or convert toLocalIterator
for row in df.rdd.toLocalIterator():
do_something(row)
and iterate locally as shown above, but it beats all purpose of using Spark.
This is probably the easiest way, not the prettiest though:
SELECT *,
(SELECT Count(*) FROM eventsTable WHERE columnName = 'Business') as RowCount
FROM eventsTable
WHERE columnName = 'Business'
This will also work without having to use a group by
SELECT *, COUNT(*) OVER () as RowCount
FROM eventsTables
WHERE columnName = 'Business'
Completeness
You need to check both $mysqli
and $statement
. If they are false, you need to output $mysqli->error
or $statement->error
respectively.
Efficiency
For simple scripts that may terminate, I use simple one-liners that trigger a PHP error with the message. For a more complex application, an error warning system should be activated instead, for example by throwing an exception.
Usage example 1: Simple script
# This is in a simple command line script
$mysqli = new mysqli('localhost', 'buzUser', 'buzPassword');
$q = "UPDATE foo SET bar=1";
($statement = $mysqli->prepare($q)) or trigger_error($mysqli->error, E_USER_ERROR);
$statement->execute() or trigger_error($statement->error, E_USER_ERROR);
Usage example 2: Application
# This is part of an application
class FuzDatabaseException extends Exception {
}
class Foo {
public $mysqli;
public function __construct(mysqli $mysqli) {
$this->mysqli = $mysqli;
}
public function updateBar() {
$q = "UPDATE foo SET bar=1";
$statement = $this->mysqli->prepare($q);
if (!$statement) {
throw new FuzDatabaseException($mysqli->error);
}
if (!$statement->execute()) {
throw new FuzDatabaseException($statement->error);
}
}
}
$foo = new Foo(new mysqli('localhost','buzUser','buzPassword'));
try {
$foo->updateBar();
} catch (FuzDatabaseException $e)
$msg = $e->getMessage();
// Now send warning emails, write log
}
That's a very complex question for a simple answer.
You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.
Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.
At the very top level I think quality REST API docs require at least the following:
Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.
lsof and fuser didn't give me anything either.
After a process of renaming all possible directories to .old and rebooting the system every time after I made changes I found one particular directory (relating to postfix) that was responsible.
It turned out that I had once made a symlink from /var/spool/postfix to /disk2/pers/mail/postfix/varspool in order to minimise disk writes on an SDCARD-based root filesystem (Sheeva Plug).
With this symlink, even after stopping the postfix and dovecot services (both ps aux as well as netstat -tuanp didn't show anything related) I was not able to unmount /disk2/pers.
When I removed the symlink and updated the postfix and dovecot config files to point directly to the new dirs on /disk2/pers/ I was able to successfully stop the services and unmount the directory.
Next time I will look more closely at the output of:
ls -lR /var | grep ^l | grep disk2
The above command will recursively list all symbolic links in a directory tree (here starting at /var) and filter out those names that point to a specific target mount point (here disk2).
PHP regex strings need delimiters. Try:
$numpattern="/^([0-9]+)$/";
Also, note that you have a lower case o, not a zero. In addition, if you're just validating, you don't need the capturing group, and can simplify the regex to /^\d+$/
.
Example: http://ideone.com/Ec3zh
See also: PHP - Delimiters
Andrey's answer (the highest voted at the time of writing) is slightly incorrect. I would have added this as comment but I am not reputable enough.
In Andrey's answer:
char[] chars = {'c', 'h', 'a', 'r', 's'}
byte[] bytes = Charset.forName("UTF-8").encode(CharBuffer.wrap(chars)).array();
the call to array() may not return the desired value, for example:
char[] c = "aaaaaaaaaa".toCharArray();
System.out.println(Arrays.toString(Charset.forName("UTF-8").encode(CharBuffer.wrap(c)).array()));
output:
[97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 0]
As can be seen a zero byte has been added. To avoid this use the following:
char[] c = "aaaaaaaaaa".toCharArray();
ByteBuffer bb = Charset.forName("UTF-8").encode(CharBuffer.wrap(c));
byte[] b = new byte[bb.remaining()];
bb.get(b);
System.out.println(Arrays.toString(b));
output:
[97, 97, 97, 97, 97, 97, 97, 97, 97, 97]
As the answer also alluded to using passwords it might be worth blanking out the array that backs the ByteBuffer (accessed via the array() function):
ByteBuffer bb = Charset.forName("UTF-8").encode(CharBuffer.wrap(c));
byte[] b = new byte[bb.remaining()];
bb.get(b);
blankOutByteArray(bb.array());
System.out.println(Arrays.toString(b));
Use:
reader.ReadString('\n')
\n
at the end of the string returned.reader.ReadLine()
I tested the various solutions suggested by writing a program to test the scenarios which are identified as problems in other answers:
I found that:
Scanner
solution does not handle long lines.ReadLine
solution is complex to implement.ReadString
solution is the simplest and works for long lines.Here is code which demonstrates each solution, it can be run via go run main.go
, or at https://play.golang.org/p/RAW3sGblbas
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
)
func readFileWithReadString(fn string) (err error) {
fmt.Println("readFileWithReadString")
file, err := os.Open(fn)
if err != nil {
return err
}
defer file.Close()
// Start reading from the file with a reader.
reader := bufio.NewReader(file)
var line string
for {
line, err = reader.ReadString('\n')
if err != nil && err != io.EOF {
break
}
// Process the line here.
fmt.Printf(" > Read %d characters\n", len(line))
fmt.Printf(" > > %s\n", limitLength(line, 50))
if err != nil {
break
}
}
if err != io.EOF {
fmt.Printf(" > Failed with error: %v\n", err)
return err
}
return
}
func readFileWithScanner(fn string) (err error) {
fmt.Println("readFileWithScanner (scanner fails with long lines)")
// Don't use this, it doesn't work with long lines...
file, err := os.Open(fn)
if err != nil {
return err
}
defer file.Close()
// Start reading from the file using a scanner.
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
// Process the line here.
fmt.Printf(" > Read %d characters\n", len(line))
fmt.Printf(" > > %s\n", limitLength(line, 50))
}
if scanner.Err() != nil {
fmt.Printf(" > Failed with error %v\n", scanner.Err())
return scanner.Err()
}
return
}
func readFileWithReadLine(fn string) (err error) {
fmt.Println("readFileWithReadLine")
file, err := os.Open(fn)
if err != nil {
return err
}
defer file.Close()
// Start reading from the file with a reader.
reader := bufio.NewReader(file)
for {
var buffer bytes.Buffer
var l []byte
var isPrefix bool
for {
l, isPrefix, err = reader.ReadLine()
buffer.Write(l)
// If we've reached the end of the line, stop reading.
if !isPrefix {
break
}
// If we're at the EOF, break.
if err != nil {
if err != io.EOF {
return err
}
break
}
}
line := buffer.String()
// Process the line here.
fmt.Printf(" > Read %d characters\n", len(line))
fmt.Printf(" > > %s\n", limitLength(line, 50))
if err == io.EOF {
break
}
}
if err != io.EOF {
fmt.Printf(" > Failed with error: %v\n", err)
return err
}
return
}
func main() {
testLongLines()
testLinesThatDoNotFinishWithALinebreak()
}
func testLongLines() {
fmt.Println("Long lines")
fmt.Println()
createFileWithLongLine("longline.txt")
readFileWithReadString("longline.txt")
fmt.Println()
readFileWithScanner("longline.txt")
fmt.Println()
readFileWithReadLine("longline.txt")
fmt.Println()
}
func testLinesThatDoNotFinishWithALinebreak() {
fmt.Println("No linebreak")
fmt.Println()
createFileThatDoesNotEndWithALineBreak("nolinebreak.txt")
readFileWithReadString("nolinebreak.txt")
fmt.Println()
readFileWithScanner("nolinebreak.txt")
fmt.Println()
readFileWithReadLine("nolinebreak.txt")
fmt.Println()
}
func createFileThatDoesNotEndWithALineBreak(fn string) (err error) {
file, err := os.Create(fn)
if err != nil {
return err
}
defer file.Close()
w := bufio.NewWriter(file)
w.WriteString("Does not end with linebreak.")
w.Flush()
return
}
func createFileWithLongLine(fn string) (err error) {
file, err := os.Create(fn)
if err != nil {
return err
}
defer file.Close()
w := bufio.NewWriter(file)
fs := 1024 * 1024 * 4 // 4MB
// Create a 4MB long line consisting of the letter a.
for i := 0; i < fs; i++ {
w.WriteRune('a')
}
// Terminate the line with a break.
w.WriteRune('\n')
// Put in a second line, which doesn't have a linebreak.
w.WriteString("Second line.")
w.Flush()
return
}
func limitLength(s string, length int) string {
if len(s) < length {
return s
}
return s[:length]
}
I tested on:
The test program outputs:
Long lines
readFileWithReadString
> Read 4194305 characters
> > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
> Read 12 characters
> > Second line.
readFileWithScanner (scanner fails with long lines)
> Failed with error bufio.Scanner: token too long
readFileWithReadLine
> Read 4194304 characters
> > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
> Read 12 characters
> > Second line.
> Read 0 characters
> >
No linebreak
readFileWithReadString
> Read 28 characters
> > Does not end with linebreak.
readFileWithScanner (scanner fails with long lines)
> Read 28 characters
> > Does not end with linebreak.
readFileWithReadLine
> Read 28 characters
> > Does not end with linebreak.
> Read 0 characters
> >
This works for me:
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:"));
intent.putExtra(Intent.EXTRA_EMAIL , new String[] { "[email protected]" });
intent.putExtra(Intent.EXTRA_SUBJECT, "My subject");
startActivity(Intent.createChooser(intent, "Email via..."));
i.e. use the ACTION_SENDTO
action rather than the ACTION_SEND
action. I've tried it on a couple of Android 4.4 devices and it limits the chooser pop-up to only display email applications (Email, Gmail, Yahoo Mail etc) and it correctly inserts the email address and subject into the email.
My guess is that here
<context:component-scan base-package="pl.com.radzikowski.webmail" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
all annotations are first disabled by use-default-filters="false" and then only @Controller annotation enabled. Thus, your @Component annotation is not enabled.
Like @takeshin said .d stands for declaration file for typescript (.ts).
Few points to be clarified before proceeding to answer this post -
If you are thinking if typescript is just syntactic superset, what benefits does it offer - https://basarat.gitbooks.io/typescript/docs/why-typescript.html#the-typescript-type-system
To Answer this post -
As we discussed, typescript is superset of javascript and needs to be transpiled into javascript. So if a library or third party code is written in typescript, it eventually gets converted to javascript which can be used by javascript project but vice versa does not hold true.
For ex -
If you install javascript library -
npm install --save mylib
and try importing it in typescript code -
import * from "mylib";
you will get error.
"Cannot find module 'mylib'."
As mentioned by @Chris, many libraries like underscore, Jquery are already written in javascript. Rather than re-writing those libraries for typescript projects, an alternate solution was needed.
In order to do this, you can provide type declaration file in javascript library named as *.d.ts, like in above case mylib.d.ts. Declaration file only provides type declarations of functions and variables defined in respective javascript file.
Now when you try -
import * from "mylib";
mylib.d.ts gets imported which acts as an interface between javascript library code and typescript project.
You can do that by applying your rotate CSS to an inner element and then adjusting the height of the element to match its width since the element was rotated to fit it into the <td>
.
Also make sure you change your id
#rotate
to a class since you have multiple.
$(document).ready(function() {_x000D_
$('.rotate').css('height', $('.rotate').width());_x000D_
});
_x000D_
td {_x000D_
border-collapse: collapse;_x000D_
border: 1px black solid;_x000D_
}_x000D_
tr:nth-of-type(5) td:nth-of-type(1) {_x000D_
visibility: hidden;_x000D_
}_x000D_
.rotate {_x000D_
/* FF3.5+ */_x000D_
-moz-transform: rotate(-90.0deg);_x000D_
/* Opera 10.5 */_x000D_
-o-transform: rotate(-90.0deg);_x000D_
/* Saf3.1+, Chrome */_x000D_
-webkit-transform: rotate(-90.0deg);_x000D_
/* IE6,IE7 */_x000D_
filter: progid: DXImageTransform.Microsoft.BasicImage(rotation=0.083);_x000D_
/* IE8 */_x000D_
-ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)";_x000D_
/* Standard */_x000D_
transform: rotate(-90.0deg);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table cellpadding="0" cellspacing="0" align="center">_x000D_
<tr>_x000D_
<td>_x000D_
<div class='rotate'>10kg</div>_x000D_
</td>_x000D_
<td>B</td>_x000D_
<td>C</td>_x000D_
<td>D</td>_x000D_
<td>E</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
<div class='rotate'>20kg</div>_x000D_
</td>_x000D_
<td>G</td>_x000D_
<td>H</td>_x000D_
<td>I</td>_x000D_
<td>J</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
<div class='rotate'>30kg</div>_x000D_
</td>_x000D_
<td>L</td>_x000D_
<td>M</td>_x000D_
<td>N</td>_x000D_
<td>O</td>_x000D_
</tr>_x000D_
_x000D_
_x000D_
</table>
_x000D_
JavaScript
The equivalent to the above in pure JavaScript is as follows:
window.addEventListener('load', function () {
var rotates = document.getElementsByClassName('rotate');
for (var i = 0; i < rotates.length; i++) {
rotates[i].style.height = rotates[i].offsetWidth + 'px';
}
});
I think it is a lot easier now.
Additionally, I use Sql Backup and FTP (https://sqlbackupandftp.com/) to do daily backups to a secure FTP server. I simply pull a recent BACPAC file from there and it import it in the same dialog, which is faster and easier to create a local database.
Just be sure that you have include python to windows PATH variable, then run python -m ensurepip
This is a right answer. you need to import FormsMoudle
first in app.module.ts
**
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
FormsModule,
ReactiveFormsModule ,
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
** second in app.component.spec.ts
import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule,
FormsModule
],
declarations: [
AppComponent
],
}).compileComponents();
}));
Best regards and hope will be helpfull
You can also try and provide an Id for the main layout and change the background of that through basic manipulation and retrieval. E.g:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/hello"
Which can then be followed by accessing through R.id.hello.... Pretty basic and I hope this does help :)
The above is correct but for a more general answer it is not enough. I needed to nest ng-repeat, but stay on the same html level, meaning write the elements in the same parent. The tags array contain tag(s) that also have a tags array. It is actually a tree.
[{ name:'name1', tags: [
{ name: 'name1_1', tags: []},
{ name: 'name1_2', tags: []}
]},
{ name:'name2', tags: [
{ name: 'name2_1', tags: []},
{ name: 'name2_2', tags: []}
]}
]
So here is what I eventually did.
<div ng-repeat-start="tag1 in tags" ng-if="false"></div>
{{tag1}},
<div ng-repeat-start="tag2 in tag1.tags" ng-if="false"></div>
{{tag2}},
<div ng-repeat-end ng-if="false"></div>
<div ng-repeat-end ng-if="false"></div>
Note the ng-if="false" that hides the start and end divs.
It should print
name1,name1_1,name1_2,name2,name2_1,name2_2,
even with the environment variables set, I found that ant -version
does not work in scripts. Try call ant -version
Mirko Froehlich's answer worked for me, except when i wanted to use custom colors. The trick is to specify UI color with Hue, saturation and brightness instead of RGB.
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = myView.bounds;
UIColor *startColour = [UIColor colorWithHue:.580555 saturation:0.31 brightness:0.90 alpha:1.0];
UIColor *endColour = [UIColor colorWithHue:.58333 saturation:0.50 brightness:0.62 alpha:1.0];
gradient.colors = [NSArray arrayWithObjects:(id)[startColour CGColor], (id)[endColour CGColor], nil];
[myView.layer insertSublayer:gradient atIndex:0];
To get the Hue, Saturation and Brightness of a color, use the in built xcode color picker and go to the HSB tab. Hue is measured in degrees in this view, so divide the value by 360 to get the value you will want to enter in code.
Unless the variable k
is defined, that's probably what's causing your trouble. Something like this will do what you want:
var new_tweets = { };
new_tweets.k = { };
new_tweets.k.tweet_id = 98745521;
new_tweets.k.user_id = 54875;
new_tweets.k.data = { };
new_tweets.k.data.in_reply_to_screen_name = 'other_user';
new_tweets.k.data.text = 'tweet text';
// Will create the JSON string you're looking for.
var json = JSON.stringify(new_tweets);
You can also do it all at once:
var new_tweets = {
k: {
tweet_id: 98745521,
user_id: 54875,
data: {
in_reply_to_screen_name: 'other_user',
text: 'tweet_text'
}
}
}
A little bit late, but here's an extension that enable you to find a responder of any type, including ViewController.
extension NSObject{
func findNext(type: AnyClass) -> Any{
var resp = self as! UIResponder
while !resp.isKind(of: type.self) && resp.next != nil
{
resp = resp.next!
}
return resp
}
}
I found that "phpseclib" should help you with this (SFTP and many more features). http://phpseclib.sourceforge.net/
To Put the file to the server, simply call (Code example from http://phpseclib.sourceforge.net/sftp/examples.html#put)
<?php
include('Net/SFTP.php');
$sftp = new Net_SFTP('www.domain.tld');
if (!$sftp->login('username', 'password')) {
exit('Login Failed');
}
// puts a three-byte file named filename.remote on the SFTP server
$sftp->put('filename.remote', 'xxx');
// puts an x-byte file named filename.remote on the SFTP server,
// where x is the size of filename.local
$sftp->put('filename.remote', 'filename.local', NET_SFTP_LOCAL_FILE);
I found a very weird thing in Java today, so it goes like -
If you are inputting more than 1 thing from the user, say
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
So, it might look like if we run this program, it will ask for these 3 inputs and say our input values are 10, 2.5, "Welcome to java" The program should print these 3 values as it is, as we have used nextLine() so it shouldn't ignore the text after spaces that we have entered in our variable s
But, the output that you will get is -
10
2.5
And that's it, it doesn't even prompt for the String input. Now I was reading about it and to be very honest there are still some gaps in my understanding, all I could figure out was after taking the int input and then the double input when we press enter, it considers that as the prompt and ignores the nextLine().
So changing my code to something like this -
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
sc.nextLine();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
does the job perfectly, so it is related to something like "\n" being stored in the keyboard buffer in the previous example which we can bypass using this.
Please if anybody knows help me with an explanation for this.
If you're not wanting to save changes set savechanges to false
Sub CloseBook2()
ActiveWorkbook.Close savechanges:=False
End Sub
for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used
ActiveWorkbook.Close False
An unsigned char uses the bit that is reserved for the sign of a regular char as another number. This changes the range to [0 - 255] as opposed to [-128 - 127].
Generally unsigned chars are used when you don't want a sign. This will make a difference when doing things like shifting bits (shift extends the sign) and other things when dealing with a char as a byte rather than using it as a number.
If maven is not creating Local Repository i.e .m2/repository folder then try below step.
In your Eclipse\Spring Tool Suite, Go to Window->preferences-> maven->user settings-> click on Restore Defaults-> Apply->Apply and close
You can use the next code:
JS
function showname () {
var name = document.getElementById('fileInput');
alert('Selected file: ' + name.files.item(0).name);
alert('Selected file: ' + name.files.item(0).size);
alert('Selected file: ' + name.files.item(0).type);
};
HTML
<body>
<p>
<input type="file" id="fileInput" multiple onchange="showname()"/>
</p>
</body>
1.Just Disable signing from the properties of your project it will solve issue :)
2.The other method is to purchase the certificate for your product from Digicert or Comodo or any other you want. You can get some free certificates for One pc use.
I understand that there is a 4000 max set for
NVARCHAR(MAX)
Your understanding is wrong. nvarchar(max)
can store up to (and beyond sometimes) 2GB of data (1 billion double byte characters).
From nchar and nvarchar in Books online the grammar is
nvarchar [ ( n | max ) ]
The |
character means these are alternatives. i.e. you specify either n
or the literal max
.
If you choose to specify a specific n
then this must be between 1 and 4,000 but using max
defines it as a large object datatype (replacement for ntext
which is deprecated).
In fact in SQL Server 2008 it seems that for a variable the 2GB limit can be exceeded indefinitely subject to sufficient space in tempdb
(Shown here)
Regarding the other parts of your question
varchar(n) + varchar(n)
will truncate at 8,000 characters.nvarchar(n) + nvarchar(n)
will truncate at 4,000 characters.varchar(n) + nvarchar(n)
will truncate at 4,000 characters. nvarchar
has higher precedence so the result is nvarchar(4,000)
[n]varchar(max)
+ [n]varchar(max)
won't truncate (for < 2GB).varchar(max)
+ varchar(n)
won't truncate (for < 2GB) and the result will be typed as varchar(max)
.varchar(max)
+ nvarchar(n)
won't truncate (for < 2GB) and the result will be typed as nvarchar(max)
.nvarchar(max)
+ varchar(n)
will first convert the varchar(n)
input to nvarchar(n)
and then do the concatenation. If the length of the varchar(n)
string is greater than 4,000 characters the cast will be to nvarchar(4000)
and truncation will occur.If you use the N
prefix and the string is <= 4,000 characters long it will be typed as nvarchar(n)
where n
is the length of the string. So N'Foo'
will be treated as nvarchar(3)
for example. If the string is longer than 4,000 characters it will be treated as nvarchar(max)
If you don't use the N
prefix and the string is <= 8,000 characters long it will be typed as varchar(n)
where n
is the length of the string. If longer as varchar(max)
For both of the above if the length of the string is zero then n
is set to 1.
1. The CONCAT
function doesn't help here
DECLARE @A5000 VARCHAR(5000) = REPLICATE('A',5000);
SELECT DATALENGTH(@A5000 + @A5000),
DATALENGTH(CONCAT(@A5000,@A5000));
The above returns 8000 for both methods of concatenation.
2. Be careful with +=
DECLARE @A VARCHAR(MAX) = '';
SET @A+= REPLICATE('A',5000) + REPLICATE('A',5000)
DECLARE @B VARCHAR(MAX) = '';
SET @B = @B + REPLICATE('A',5000) + REPLICATE('A',5000)
SELECT DATALENGTH(@A),
DATALENGTH(@B);`
Returns
-------------------- --------------------
8000 10000
Note that @A
encountered truncation.
You are getting truncation either because you are concatenating two non max
datatypes together or because you are concatenating a varchar(4001 - 8000)
string to an nvarchar
typed string (even nvarchar(max)
).
To avoid the second issue simply make sure that all string literals (or at least those with lengths in the 4001 - 8000 range) are prefaced with N
.
To avoid the first issue change the assignment from
DECLARE @SQL NVARCHAR(MAX);
SET @SQL = 'Foo' + 'Bar' + ...;
To
DECLARE @SQL NVARCHAR(MAX) = '';
SET @SQL = @SQL + N'Foo' + N'Bar'
so that an NVARCHAR(MAX)
is involved in the concatenation from the beginning (as the result of each concatenation will also be NVARCHAR(MAX)
this will propagate)
Make sure you have "results to grid" mode selected then you can use
select @SQL as [processing-instruction(x)] FOR XML PATH
The SSMS options allow you to set unlimited length for XML
results. The processing-instruction
bit avoids issues with characters such as <
showing up as <
.
Try this:
export HTTPS_PROXY_REQUEST_FULLURI=false
solved this issue for me working behind a proxy at a company few weeks ago.
the best way (for me) to make it it's the next infrastructure:
<form method="POST">
<input type="submit" formaction="default_url_when_press_enter" style="visibility: hidden; display: none;">
<!-- all your inputs -->
<input><input><input>
<!-- all your inputs -->
<button formaction="action1">Action1</button>
<button formaction="action2">Action2</button>
<input type="submit" value="Default Action">
</form>
with this structure you will send with enter a direction and the infinite possibilities for the rest of buttons.
The man
page has very detailed descriptions of all of the various options (the status bar is highly configurable). Your best bet is to read through man tmux
and pay particular attention to those options that begin with status-
.
So, for example, status-bg red
would set the background colour of the bar.
The three components of the bar, the left and right sections and the window-list in the middle, can all be configured to suit your preferences. status-left
and status-right
, in addition to having their own variables (like #S
to list the session name) can also call custom scripts to display, for example, system information like load average or battery time.
The option to rename windows or panes based on what is currently running in them is automatic-rename
. You can set, or disable it globally with:
setw -g automatic-rename [on | off]
The most straightforward way to become comfortable with building your own status bar is to start with a vanilla one and then add changes incrementally, reloading the config as you go.1
You might also want to have a look around on github or bitbucket for other people's conf files to provide some inspiration. You can see mine here2.
1 You can automate this by including this line in your .tmux.conf
:
bind R source-file ~/.tmux.conf \; display-message "Config reloaded..."
You can then test your new functionality with Ctrlb,Shiftr. tmux
will print a helpful error message—including a line number of the offending snippet—if you misconfigure an option.
2 Note: I call a different status bar depending on whether I am in X or the console - I find this quite useful.
Basic Example Code, learning to code is easy. Check Style CSS comments.
table tr {_x000D_
display: flex;_x000D_
}_x000D_
table tr td {_x000D_
/* start */_x000D_
display: inline-block; /* <- Prevent <tr> in a display css */_x000D_
text-overflow: ellipsis;_x000D_
white-space: nowrap;_x000D_
/* end */_x000D_
padding: 10px;_x000D_
width: 150px; /* Space size limit */_x000D_
border: 1px solid black;_x000D_
overflow: hidden;_x000D_
}
_x000D_
<table>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla egestas erat ut luctus posuere. Praesent et commodo eros. Vestibulum eu nisl vel dui ultrices ultricies vel in tellus._x000D_
</td>_x000D_
<td>_x000D_
Praesent vitae tempus nulla. Donec vel porta velit. Fusce mattis enim ex. Mauris eu malesuada ante. Aenean id aliquet leo, nec ultricies tortor. Curabitur non mollis elit. Morbi euismod ante sit amet iaculis pharetra. Mauris id ultricies urna. Cras ut_x000D_
nisi dolor. Curabitur tellus erat, condimentum ac enim non, varius tempor nisi. Donec dapibus justo odio, sed consequat eros feugiat feugiat._x000D_
</td>_x000D_
<td>_x000D_
Pellentesque mattis consequat ipsum sed sagittis. Pellentesque consectetur vestibulum odio, aliquet auctor ex elementum sed. Suspendisse porta massa nisl, quis molestie libero auctor varius. Ut erat nibh, fringilla sed ligula ut, iaculis interdum sapien._x000D_
Ut dictum massa mi, sit amet interdum mi bibendum nec._x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
Sed viverra massa laoreet urna dictum, et fringilla dui molestie. Duis porta, ligula ut venenatis pretium, sapien tellus blandit felis, non lobortis orci erat sed justo. Vivamus hendrerit, quam at iaculis vehicula, nibh nisi fermentum augue, at sagittis_x000D_
nibh dui et erat._x000D_
</td>_x000D_
<td>_x000D_
Nullam mollis nulla justo, nec tincidunt urna suscipit non. Donec malesuada dolor non dolor interdum, id ultrices neque egestas. Integer ac ante sed magna gravida dapibus sit amet eu diam. Etiam dignissim est sit amet libero dapibus, in consequat est_x000D_
aliquet._x000D_
</td>_x000D_
<td>_x000D_
Vestibulum mollis, dui eu eleifend tincidunt, erat eros tempor nibh, non finibus quam ante nec felis. Fusce egestas, orci in volutpat imperdiet, risus velit convallis sapien, sodales lobortis risus lectus id leo. Nunc vel diam vel nunc congue finibus._x000D_
Vestibulum turpis tortor, pharetra sed ipsum eu, tincidunt imperdiet lorem. Donec rutrum purus at tincidunt sagittis. Quisque nec hendrerit justo._x000D_
</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
This solved my problem when I had to deal with HTML page with embedded JavaScript
WebElement empSalary = driver.findElement(By.xpath(PayComponentAmount));
Actions mouse2 = new Actions(driver);
mouse2.clickAndHold(empSalary).sendKeys(Keys.chord(Keys.CONTROL, "a"), "1234").build().perform();
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].onchange()", empSalary);
I have modified the UILabel by following code:
label.font=[label.font fontWithSize:25];
Try this and see whether is it working in your case or not???
It's definitely worth the effort.
There's one obvious reason that anyone who uses Vi(m)
will tell you, and two others that people never seem to mention.
Here's the obvious one:
vi
is at once ubiquitous and incredibly powerful, and by learning it once, you gain the ability to exercise that power on pretty much any computer that has a keyboard.And these are the lesser known reasons to learn Vim
:
It's not half as much effort as you think it's going to be. Run through the Vim tutor once (vimtutor
at a shell, or in Windows run it from the Vim folder in the Start Menu), and you'll already be well on your way to competence, and it's all downhill from there. I was up to the level where I could use Vim
at work without taking any noticeable productivity hit within less than a week's worth of lunchtimes.
It's fun! Editing text is like a game to me now. I actively enjoy it--which is pretty ridiculous, when you think about it.
There's also two good reasons not to learn Vim
:
It's addictive, and you'll find yourself wishing you could use Vim
commands in all your computing, and cursing whenever you can't. Fortunately, at least for some situations, there's ways to get around this.
Again, it's addictive, and although you won't lose any productivity from actually using Vim
, you will waste hours searching for good tips to make your Vim
experience even better, and reading the Vim tag on Stack Overflow.
TCC and TCC/LE from JPSoft are CMD.EXE replacements that add significant functionality. Relevant to the OP's question, which
is a builtin command for TCC family command processors.
Oddly enough it was an Intel thing not a Microsoft thing. X86 referred to the Intel CPU series from the 8086 to the 80486. The Pentium series still use the same addressing system. The x64 refers to the I64 addressing system that Intel came out with later for the 64-bit CPUs. So Windows was just following Intel's architecture naming.
The traceback indicates that probably you have an empty line at the end of the file. You can fix it like this:
f = open('test.txt','r')
g = open('test1.txt','w')
while True:
x = f.readline()
x = x.rstrip()
if not x: break
print >> g, int(x, 16)
On the other hand it would be better to use for x in f
instead of readline
. Do not forget to close your files or better to use with
that close them for you:
with open('test.txt','r') as f:
with open('test1.txt','w') as g:
for x in f:
x = x.rstrip()
if not x: continue
print >> g, int(x, 16)
Code to avoid returning an empty string ( when input is like "00000").
string myStr = "00012345";
myStr = myStr.TrimStart('0');
myStr = myStr.Length > 0 ? myStr : "0";
In my case I had to increase the "Maximum received message size" of the Receive Location in BizTalk. That also has a default value of 64K and so every message was bounced by BizTAlk regardless of what I configured in my web.config
How about:
foreach(var s in listBox1.Items.ToArray())
{
MessageBox.Show(s);
//do stuff with (s);
listBox1.Items.Remove(s);
}
The ToArray makes a copy of the list, so you don't need to worry about it changing the list while you are processing it.
Server is trying to read data from the request, but its taking longer than the timeout value for the data to arrive from the client. Timeout here would typically be tomcat connector -> connectionTimeout attribute.
Correct.
Client has a read timeout set, and server is taking longer than that to respond.
No. That would cause a timeout at the client.
One of the threads i went through, said this can happen with high concurrency and if the keepalive is enabled.
That is obviously guesswork, and completely incorrect. It happens if and only if no data arrives within the timeout. Period. Load and keepalive and concurrency have nothing to do with it whatsoever.
It just means the client isn't sending. You don't need to worry about it. Browser clients come and go in all sorts of strange ways.
ZoneId here = ZoneId.of("Europe/Kiev");
ZonedDateTime hereAndNow = Instant.now().atZone(here);
String.format("%tz", hereAndNow);
will give you a standardized string representation like "+0300"
To show child or sibling elements it's possible with CSS only. If you use :hover
before combinators (+
, ~
, >
, space
). Then the style applies not to hovered element.
HTML
<body>
<div class="trigger">
Hover here.
</div>
<div class="hidden">
This message shows up.
</div>
</body>
CSS
.hidden { display: none; }
.trigger:hover + .hidden { display: inline; }
Bit
is also an option if tinyint
isn't to your liking. A few links:
Not surprisingly, more info about numeric types is available in the manual.
One more link: http://blog.mclaughlinsoftware.com/2010/02/26/mysql-boolean-data-type/
And a quote from the comment section of the article above:
- TINYINT(1) isn’t a synonym for bit(1).
- TINYINT(1) can store -9 to 9.
- TINYINT(1) UNSIGNED: 0-9
- BIT(1): 0, 1. (Bit, literally).
Edit: This edit (and answer) is only remotely related to the original question...
Additional quotes by Justin Rovang and the author maclochlainn (comment section of the linked article).
Excuse me, seems I’ve fallen victim to substr-ism: TINYINT(1): -128-+127 TINYINT(1) UNSIGNED: 0-255 (Justin Rovang 25 Aug 11 at 4:32 pm)
True enough, but the post was about what PHPMyAdmin listed as a Boolean, and there it only uses 0 or 1 from the entire wide range of 256 possibilities. (maclochlainn 25 Aug 11 at 11:35 pm)
I have found problems when applying classes inside table elements when I had one class already applied to the whole table (for example, a color applied to the odd rows <myClass tbody tr:nth-child(even) td>
). It seems that when you inspect the element with Developer Tools, the element.style
has no style assigned. So instead of using ng-class
, I have tried using ng-style
, and in this case, the new CSS attribute does appear inside element.style
. This code works great for me:
<tr ng-repeat="element in collection">
[...amazing code...]
<td ng-style="myvar === 0 && {'background-color': 'red'} ||
myvar === 1 && {'background-color': 'green'} ||
myvar === 2 && {'background-color': 'yellow'}">{{ myvar }}</td>
[...more amazing code...]
</tr>
Myvar is what I am evaluating, and in each case I apply a style to each <td>
depending on myvar value, that overwrites the current style applied by the CSS class for the whole table.
UPDATE
If you want to apply a class to the table for example, when visiting a page or in other cases, you can use this structure:
<li ng-class="{ active: isActive('/route_a') || isActive('/route_b')}">
Basically, what we need to activate a ng-class is the class to apply and a true or false statement. True applies the class and false doesn't. So here we have two checks of the route of the page and an OR between them, so if we are in /route_a
OR we are in route_b
, the active class will be applied.
This works just having a logic function on the right that returns true or false.
So in the first example, ng-style is conditioned by three statements. If all of them are false, no style is applied, but following our logic, at least one is going to be applied, so, the logic expression will check which variable comparison is true and because a non empty array is always true, that will left an array as return and with only one true, considering we are using OR for the whole response, the style remaining will be applied.
By the way, I forgot to give you the function isActive():
$rootScope.isActive = function(viewLocation) {
return viewLocation === $location.path();
};
NEW UPDATE
Here you have something I find really useful. When you need to apply a class depending on the value of a variable, for example, an icon depending on the contents of the div
, you can use the following code (very useful in ng-repeat
):
<i class="fa" ng-class="{ 'fa-github' : type === 0,
'fa-linkedin' : type === 1,
'fa-skype' : type === 2,
'fa-google' : type === 3 }"></i>
Icons from Font Awesome
Yes they do.
You shouldn't really be overriding the constructor anyway. You should have a newInstance()
static method defined and pass any parameters via arguments (bundle)
For example:
public static final MyFragment newInstance(int title, String message) {
MyFragment f = new MyFragment();
Bundle bdl = new Bundle(2);
bdl.putInt(EXTRA_TITLE, title);
bdl.putString(EXTRA_MESSAGE, message);
f.setArguments(bdl);
return f;
}
And of course grabbing the args this way:
@Override
public void onCreate(Bundle savedInstanceState) {
title = getArguments().getInt(EXTRA_TITLE);
message = getArguments().getString(EXTRA_MESSAGE);
//...
//etc
//...
}
Then you would instantiate from your fragment manager like so:
@Override
public void onCreate(Bundle savedInstanceState) {
if (savedInstanceState == null){
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content, MyFragment.newInstance(
R.string.alert_title,
"Oh no, an error occurred!")
)
.commit();
}
}
This way if detached and re-attached the object state can be stored through the arguments. Much like bundles attached to Intents.
Reason - Extra reading
I thought I would explain why for people wondering why.
If you check: https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/app/Fragment.java
You will see the instantiate(..)
method in the Fragment
class calls the newInstance
method:
public static Fragment instantiate(Context context, String fname, @Nullable Bundle args) {
try {
Class<?> clazz = sClassMap.get(fname);
if (clazz == null) {
// Class not found in the cache, see if it's real, and try to add it
clazz = context.getClassLoader().loadClass(fname);
if (!Fragment.class.isAssignableFrom(clazz)) {
throw new InstantiationException("Trying to instantiate a class " + fname
+ " that is not a Fragment", new ClassCastException());
}
sClassMap.put(fname, clazz);
}
Fragment f = (Fragment) clazz.getConstructor().newInstance();
if (args != null) {
args.setClassLoader(f.getClass().getClassLoader());
f.setArguments(args);
}
return f;
} catch (ClassNotFoundException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": make sure class name exists, is public, and has an"
+ " empty constructor that is public", e);
} catch (java.lang.InstantiationException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": make sure class name exists, is public, and has an"
+ " empty constructor that is public", e);
} catch (IllegalAccessException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": make sure class name exists, is public, and has an"
+ " empty constructor that is public", e);
} catch (NoSuchMethodException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": could not find Fragment constructor", e);
} catch (InvocationTargetException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": calling Fragment constructor caused an exception", e);
}
}
http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#newInstance() Explains why, upon instantiation it checks that the accessor is public
and that that class loader allows access to it.
It's a pretty nasty method all in all, but it allows the FragmentManger
to kill and recreate Fragments
with states. (The Android subsystem does similar things with Activities
).
Example Class
I get asked a lot about calling newInstance
. Do not confuse this with the class method. This whole class example should show the usage.
/**
* Created by chris on 21/11/2013
*/
public class StationInfoAccessibilityFragment extends BaseFragment implements JourneyProviderListener {
public static final StationInfoAccessibilityFragment newInstance(String crsCode) {
StationInfoAccessibilityFragment fragment = new StationInfoAccessibilityFragment();
final Bundle args = new Bundle(1);
args.putString(EXTRA_CRS_CODE, crsCode);
fragment.setArguments(args);
return fragment;
}
// Views
LinearLayout mLinearLayout;
/**
* Layout Inflater
*/
private LayoutInflater mInflater;
/**
* Station Crs Code
*/
private String mCrsCode;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCrsCode = getArguments().getString(EXTRA_CRS_CODE);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mInflater = inflater;
return inflater.inflate(R.layout.fragment_station_accessibility, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mLinearLayout = (LinearLayout)view.findViewBy(R.id.station_info_accessibility_linear);
//Do stuff
}
@Override
public void onResume() {
super.onResume();
getActivity().getSupportActionBar().setTitle(R.string.station_info_access_mobility_title);
}
// Other methods etc...
}
In Python 3.
>>> D1 = {2:3, 1:89, 4:5, 3:0}
>>> for key in sorted(D1):
print (key, D1[key])
gives
1 89
2 3
3 0
4 5
If you've already initialized the form, you can use the initial property of the field. For example,
form = CustomForm()
form.fields["Email"].initial = GetEmailString()
<button id="fwdbtn" style="color:red">Submit</button>
I had this other answer but this one, based on Jack's answer, is significantly faster might be preferred since it works asynchronously, although slightly slower.
public static class StringExtensionMethods
{
public static IEnumerable<string> GetLines(this string str, bool removeEmptyLines = false)
{
using (var sr = new StringReader(str))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (removeEmptyLines && String.IsNullOrWhiteSpace(line))
{
continue;
}
yield return line;
}
}
}
}
Usage:
input.GetLines() // keeps empty lines
input.GetLines(true) // removes empty lines
Test:
Action<Action> measure = (Action func) =>
{
var start = DateTime.Now;
for (int i = 0; i < 100000; i++)
{
func();
}
var duration = DateTime.Now - start;
Console.WriteLine(duration);
};
var input = "";
for (int i = 0; i < 100; i++)
{
input += "1 \r2\r\n3\n4\n\r5 \r\n\r\n 6\r7\r 8\r\n";
}
measure(() =>
input.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None)
);
measure(() =>
input.GetLines()
);
measure(() =>
input.GetLines().ToList()
);
Output:
00:00:03.9603894
00:00:00.0029996
00:00:04.8221971
An accessed dictionary value (a list in this case) is the original value, separate from the dictionary which is used to access it. You would increment the values in the list the same way whether it's in a dictionary or not:
l = dictionary.get('C1')
for i in range(len(l)):
l[i] += 10
If you simply want to see the column names this one line should provide it without changing any settings:
describe database.tablename;
However, if that doesn't work for your version of hive this code will provide it, but your default database will now be the database you are using:
use database;
describe tablename;
Consider the hex() method of the bytes
type on Python 3.5 and up:
>>> array_alpha = [ 133, 53, 234, 241 ]
>>> print(bytes(array_alpha).hex())
8535eaf1
EDIT: it's also much faster than hexlify
(modified @falsetru's benchmarks above)
from timeit import timeit
N = 10000
print("bytearray + hexlify ->", timeit(
'binascii.hexlify(data).decode("ascii")',
setup='import binascii; data = bytearray(range(255))',
number=N,
))
print("byte + hex ->", timeit(
'data.hex()',
setup='data = bytes(range(255))',
number=N,
))
Result:
bytearray + hexlify -> 0.011218150997592602
byte + hex -> 0.005952142993919551
I found that it was necessary to enter the architecture names by hand:
I don't know why this was necessary, i.e. why these values were not inherited from Xcode itself. But as soon as I did this, the problem went away.
EDIT: If you're a designer then Papyrus is your best choice it's very advanced and full of features, but if you just want to sketch out some UML diagrams and easy installation then ObjectAid is pretty cool and it doesn't require any plugins I just installed it over Eclipse-Java EE and works great !.
UPDATE Oct 11th, 2013
My original post was in June 2012 a lot of things have changed many tools has grown and others didn't. Since I'm going back to do some modeling and also getting some replies to the post I decided to install papyrus again and will investigate other possible UML modeling solutions again. UML generation (with synchronization feature) is really important not to software designer but to the average developer.
I wish papyrus had straightforward way to Reverse Engineer classes into UML class diagram and It would be super cool if that reverse engineering had a synchronization feature, but unfortunately papyrus project is full of features and I think developers there have already much at hand since also many actions you do over papyrus might not give you any response and just nothing happens but that's out of this question scope anyway.
The Answer (Oct 11th, 2013)
Tools
Steps
Right click on MyProject_kdm.xmi -> Discovery -> Discoverer -> Discover UML model from KDM code again you'll get a property dialog set the serialization prop to TRUE to generate a file named MyProject.uml
Move generated MyProject.uml which was generated at root, to UML folder, Eclipse will ask you If you wanted to replace it click yes. What we did in here was that we replaced an empty model with a generated one.
ALT+W -> show view -> papyrus -> model explorer
In that view, you'll find your classes like in the picture
In the view Right click root model -> New diagram
Then start grabbing classes to the diagram from the view
Some features
To show the class elements (variables, functions etc) Right click on any class -> Filters -> show/hide contents Voila !!
You can have default friendly color settings from Window -> pereferences -> papyrus -> class diagram
one very important setting is Arrange when you drop the classes they get a cramped right click on any empty space at a class diagram and click Arrange All
Arrows in the model explorer view can be grabbed to the diagram to show generalization, realization etc
After all of that your settings will show diagrams like
Synchronization isn't available as far as I know you'll need to manually import any new classes.
That's all, And don't buy commercial products unless you really need it, papyrus is actually great and sophisticated instead donate or something.
Disclaimer: I've no relation to the papyrus people, in fact, I didn't like papyrus at first until I did lots of research and experienced it with some patience. And will get back to this post again when I try other free tools.
As part of htmlAttributes,e.g.
Html.BeginForm(
action, controller, FormMethod.Post, new { enctype="multipart/form-data"})
Or you can pass null
for action and controller to get the same default target as for BeginForm() without any parameters:
Html.BeginForm(
null, null, FormMethod.Post, new { enctype="multipart/form-data"})
I would change the query in the following ways:
group by
.left outer join
to ensure that all data is available.count(<fieldname>)
you can eliminate the comparisons to is null
. This is important for the second and third calculated values.mde
table. These use mde.mdeid
.The following version follows your example by using union all
:
SELECT CAST(Detail.ReceiptDate AS DATE) AS "Date",
SUM(TOTALMAILED) as TotalMailed,
SUM(TOTALUNDELINOTICESRECEIVED) as TOTALUNDELINOTICESRECEIVED,
SUM(TRACEUNDELNOTICESRECEIVED) as TRACEUNDELNOTICESRECEIVED
FROM ((select SentDate AS "ReceiptDate", COUNT(*) as TotalMailed,
NULL as TOTALUNDELINOTICESRECEIVED, NULL as TRACEUNDELNOTICESRECEIVED
from MailDataExtract
where SentDate is not null
group by SentDate
) union all
(select MDE.ReturnMailDate AS ReceiptDate, 0,
COUNT(distinct mde.mdeid) as TOTALUNDELINOTICESRECEIVED,
SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
from MailDataExtract MDE left outer join
DTSharedData.dbo.ScanData SD
ON SD.ScanDataID = MDE.ReturnScanDataID
group by MDE.ReturnMailDate;
)
) detail
GROUP BY CAST(Detail.ReceiptDate AS DATE)
ORDER BY 1;
The following does something similar using full outer join
:
SELECT coalesce(sd.ReceiptDate, mde.ReceiptDate) AS "Date",
sd.TotalMailed, mde.TOTALUNDELINOTICESRECEIVED,
mde.TRACEUNDELNOTICESRECEIVED
FROM (select cast(SentDate as date) AS "ReceiptDate", COUNT(*) as TotalMailed
from MailDataExtract
where SentDate is not null
group by cast(SentDate as date)
) sd full outer join
(select cast(MDE.ReturnMailDate as date) AS ReceiptDate,
COUNT(distinct mde.mdeID) as TOTALUNDELINOTICESRECEIVED,
SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
from MailDataExtract MDE left outer join
DTSharedData.dbo.ScanData SD
ON SD.ScanDataID = MDE.ReturnScanDataID
group by cast(MDE.ReturnMailDate as date)
) mde
on sd.ReceiptDate = mde.ReceiptDate
ORDER BY 1;
Try the following:
sudo rm /var/lib/mongodb/mongod.lock
sudo service mongodb restart
This is more robust:
mi = location.href.split(/(\d+)/);
no = mi.length - 2;
os = mi[no];
mi[no]++;
if ((mi[no] + '').length < os.length) mi[no] = os.match(/0+/) + mi[no];
location.href = mi.join('');
When the URL has multiple numbers, it will change the last one:
http://mywebsite.com/8815/1.html
It supports numbers with leading zeros:
http://mywebsite.com/0001.html
Concerning the answer by BoltClock and John, I personally had issues with the initial keyword when using IE11. It works fine in Chrome, but in IE it seems to have no effect.
According to this answer IE does not support the initial keyword: Div display:initial not working as intended in ie10 and chrome 29
I tried setting it blank instead as suggested here: how to revert back to normal after display:none for table row
This worked and was good enough for my scenario. Of course to set the real initial value the above answer is the only good one I could find.
Let's bring this question back from the dead ;) There is a reason Google doesn't give you a simple solution. Special cases and browser quirks affect the calculation, and it is not as trivial as it seems to be.
Unfortunately, there are problems with the solutions outlined here so far. I don't mean to disparage them at all - they are great starting points and touch on all the key properties needed for a more robust approach. But I wouldn't recommend copying and pasting the code from any of the other answers because
$( document ).width()
and .height()
fall prey to jQuery's buggy detection of document size.window.innerWidth
, if the browser supports it, makes your code fail to detect scroll bars in mobile browsers, where the width of the scroll bar is generally 0. They are just shown temporarily as an overlay and don't take up space in the document. Zooming on mobile also becomes a problem that way (long story).html
and body
element to non-default values (what happens then is a little involved - see this description). I have spent more time than I would have imagined on a finding a solution that "just works" (cough). The algorithm I have come up with is now part of a plugin, jQuery.isInView, which exposes a .hasScrollbar
method. Have a look at the source if you wish.
In a scenario where you are in full control of the page and don't have to deal with unknown CSS, using a plugin may be overkill - after all, you know which edge cases apply, and which don't. However, if you need reliable results in an unknown environment, then I don't think the solutions outlined here will be enough. You are better off using a well-tested plugin - mine or anybody elses.
You could add necessary properties to catalina.properties
file in <tomcat installation directory>/conf
directory.
Reference: https://tomcat.apache.org/tomcat-8.0-doc/config/index.html
All system properties are available including those set using the -D syntax, those automatically made available by the JVM and those configured in the $CATALINA_BASE/conf/catalina.properties file.
IFS=', ' read -r -a array <<< "$string"
Note that the characters in $IFS
are treated individually as separators so that in this case fields may be separated by either a comma or a space rather than the sequence of the two characters. Interestingly though, empty fields aren't created when comma-space appears in the input because the space is treated specially.
To access an individual element:
echo "${array[0]}"
To iterate over the elements:
for element in "${array[@]}"
do
echo "$element"
done
To get both the index and the value:
for index in "${!array[@]}"
do
echo "$index ${array[index]}"
done
The last example is useful because Bash arrays are sparse. In other words, you can delete an element or add an element and then the indices are not contiguous.
unset "array[1]"
array[42]=Earth
To get the number of elements in an array:
echo "${#array[@]}"
As mentioned above, arrays can be sparse so you shouldn't use the length to get the last element. Here's how you can in Bash 4.2 and later:
echo "${array[-1]}"
in any version of Bash (from somewhere after 2.05b):
echo "${array[@]: -1:1}"
Larger negative offsets select farther from the end of the array. Note the space before the minus sign in the older form. It is required.
You need to use overflow option like below:
.nav{
max-height: 300px;
overflow-y: scroll;
}
Change the height according to amount of items you need to show
I ended up here when trying to figure this out. With the version that's up there right now you can drag and drop a folder into it and it works, even though it doesn't allow you to select a folder when you open the upload dialogue.
Try
g++ hw.cpp
./a.out
g++
is the C++ compiler frontend to GCC.
gcc
is the C compiler frontend to GCC.
Yes, Xcode is definitely an option. It is a GUI IDE that is built on-top of GCC.
Though I prefer a slightly more verbose approach:
#include <iostream>
int main()
{
std::cout << "Hello world!" << std::endl;
}
This seems a bit easier then the above suggestions because it uses the OBJECT_ID() function to locate the table's id. Any column with that id is part of the table.
SELECT *
FROM syscolumns
WHERE id=OBJECT_ID('YOUR_TABLE')
I commonly use a similar query to see if a column I know is part of a newer version is present. It is the same query with the addition of {AND name='YOUR_COLUMN'} to the where clause.
IF EXISTS (
SELECT *
FROM syscolumns
WHERE id=OBJECT_ID('YOUR_TABLE')
AND name='YOUR_COLUMN'
)
BEGIN
PRINT 'Column found'
END
Here is another solution:
>>>list1=["C:\\","D:\\","E:\\","C:\\"]
>>>set1=set(list1)
>>>set1
set(['E:\\', 'D:\\', 'C:\\'])
In this code I have used the set method in order to turn it into a set and then it removed all duplicate values from the list
To solve, you need to import Private Certificate (PFX).
If you don't have PFX, use OpenSSL to generate it:
Open command line and run:
openssl pkcs12 -export -in public_certificate.cer -inkey server.key -out private_certificate.pfx
Than, install private_certificate.pfx (right click -> Install Certificate).
Now, your certificate does not disappear anymore and you can bind Website over SSL.
A great resource: https://blog.lextudio.com/the-whole-story-of-server-certificate-disappears-in-iis-7-7-5-8-8-5-10-0-after-installing-it-why-b66e802baa38
Position your <div>
absolutely at the bottom and don't forget to give div.A
a position: relative
- http://jsfiddle.net/TTaMx/
.A {
position: relative;
margin: 40px 0;
height: 40px;
width: 200px;
background: #eee;
}
.A:after {
content: " ";
display: block;
background: #c00;
height: 29px;
width: 100%;
position: absolute;
bottom: -29px;
}?
Check whether .git/config
contains
[remote "origin"]
url = …
fetch = +refs/heads/master:refs/remotes/origin/master
If so, change it to say
[remote "origin"]
url = …
fetch = +refs/heads/*:refs/remotes/origin/*
Then you should be able to use it:
$ git fetch
remote: Counting objects: …
remote: Compressing objects: ..
Unpacking objects: …
remote: …
From …
* [new branch] branchname -> origin/branchname
$ git checkout branchname
Branch branchname set up to track remote branch branchname from origin.
Switched to a new branch 'branchname'
If you are talking about changing the working directory for a java program that you launch from within eclipse, then there's a space for that in the run configuration. If you go to Run menu and select "Run Configurations..." then select your run configuration, then on the "Arguments" tab for a Java Application there is a place for you to edit the "Working directory". This alters the current directory that will be used for launching the java program.
See related question Default eclipse working directory if this is what you are meaning.
I also had this problem, it is because there is an application LISTENING to 8080 port. To solve this problem I followed the below steps:
Open cmd.exe then type
netstat -aon | find ":8080" | find "LISTENING"
You will see like this result
TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING 1464
Copy PID "1464".
Open Task Manager (Ctrl+Alt+del), go to the details tag, then find the program or service via PID that is listening to the port 8080 then STOP it or End process.
Edit : See jme's answer for the best way with Python3.
Using pathlib, you have the following solution :
Let's say we want to check if son
is a descendant of parent
, and both are Path
objects.
We can get a list of the parts in the path with list(parent.parts)
.
Then, we just check that the begining of the son is equal to the list of segments of the parent.
>>> lparent = list(parent.parts)
>>> lson = list(son.parts)
>>> if lson[:len(lparent)] == lparent:
>>> ... #parent is a parent of son :)
If you want to get the remaining part, you can just do
>>> ''.join(lson[len(lparent):])
It's a string, but you can of course use it as a constructor of an other Path object.