Try this code
$('window').scrollDown(function(){$(#div).hide()});
$('window').scrollUp(function(){ $(#div).show() });
Here is the Swift version (pre iOS9):
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
UIApplication.sharedApplication().setStatusBarHidden(true, withAnimation: UIStatusBarAnimation.None)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
UIApplication.sharedApplication().setStatusBarHidden(false, withAnimation: UIStatusBarAnimation.None)
}
This also works (iOS7+):
override func prefersStatusBarHidden() -> Bool {
return true
}
You also need to call:
setNeedsStatusBarAppearanceUpdate()
in say viewDidLoad()
.
Note that if you use a SplitView controller, or some other container
view controller, you also need to have it return your class when its sent childViewControllerForStatusBarHidden
. One way to do this is have a public weak var for say statusController
, and return it in this overridden method.
<TextView
android:id="@+id/layone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Previous Page"
android:textColor="#000000"
android:textSize="16dp"
android:paddingLeft="10dp"
android:layout_marginTop="10dp"
android:visibility="gone" />
layone is a TextView.
You got your id wrong.
LinearLayout layone= (LinearLayout) view.findViewById(R.id.laytwo);// change id here
layone.setVisibility(View.VISIBLE);
should do the job.
or change like this to show the TextView:
TextView layone= (TextView) view.findViewById(R.id.layone);
layone.setVisibility(View.VISIBLE);
Looking at the jQuery code, this is what happens:
hide: function( speed, easing, callback ) {
if ( speed || speed === 0 ) {
return this.animate( genFx("hide", 3), speed, easing, callback);
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
var display = jQuery.css( this[i], "display" );
if ( display !== "none" ) {
jQuery.data( this[i], "olddisplay", display );
}
}
// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
this[i].style.display = "none";
}
return this;
}
},
It's better if you check visibility like this:
if($('#video-over').is(':visible'))
the answers here are correct and i liked @Jyo the Whiff idea of a show and hide fragment implementation except the way he has it currently would hide the fragment on the first run so i added a slight change in that i added the isAdded check and show the fragment if its not already
public void showHideCardPreview(int id) {
FragmentManager fm = getSupportFragmentManager();
Bundle b = new Bundle();
b.putInt(Constants.CARD, id);
cardPreviewFragment.setArguments(b);
FragmentTransaction ft = fm.beginTransaction()
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
if (!cardPreviewFragment.isAdded()){
ft.add(R.id.full_screen_container, cardPreviewFragment);
ft.show(cardPreviewFragment);
} else {
if (cardPreviewFragment.isHidden()) {
Log.d(TAG,"++++++++++++++++++++ show");
ft.show(cardPreviewFragment);
} else {
Log.d(TAG,"++++++++++++++++++++ hide");
ft.hide(cardPreviewFragment);
}
}
ft.commit();
}
fun Activity.setStatusBarVisibility(isVisible: Boolean) {
//see details https://developer.android.com/training/system-ui/immersive
if (isVisible) {
window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
} else {
window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_FULLSCREEN)
}
}
To switch the display-style between block
and none
you can do something like this:
function toggleDiv(id) {
var div = document.getElementById(id);
div.style.display = div.style.display == "none" ? "block" : "none";
}
working demo: http://jsfiddle.net/BQUyT/2/
Angular-ui comes with dialog directive.Use it and set templateurl to whatever page you want to include.That is the most elegant way and i have used it in my project as well. You can pass several other parameters for dialog as per need.
Try this
$('.yourchkboxes').change(function(){
$('.yourbutton').toggle($('.yourchkboxes:checked').length > 0);
});
So it will check for at least one checkbox is checked or not.
Why not just use $('#msform').hide()
? Behind the scene jQuery's hide
and show
just set display: none
or display: block
.
hide()
will not change the style if already hidden.
based on the comment below, you are removing all style with removeAttr("style")
, in which case call hide()
immediately after that.
e.g.
$("#msform").removeAttr("style").hide();
The reverse of this is of course show()
as in
$("#msform").show();
Or, more interestingly, toggle()
, which effective flips between hide()
and show()
based on the current state.
actually jQuery simply clears the value of the 'display' property, and doesn't set it to 'block' (see internal implementation of jQuery.showHide()) -
function showHide(elements, show) {
var display, elem, hidden,
...
if (show) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if (!values[index] && display === "none") {
elem.style.display = "";
}
...
if (!show || elem.style.display === "none" || elem.style.display === "") {
elem.style.display = show ? values[index] || "" : "none";
}
}
Please note that you can override $.fn.show()/$.fn.hide(); storing original display in element itself when hiding (e.g. as an attribute or in the $.data()); and then applying it back again when showing.
Also, using css important! will probably not work here - since setting a style inline is usually stronger than any other rule
If you're using selinux it might be because of security restrictions. Try setting this as root:
# setsebool -P httpd_can_network_connect on
In Bootstrap 4, there are already separated files in their GitHub. You can find them here
https://github.com/twbs/bootstrap/tree/main/dist/css
var search = "world";
var replacement = "csharp";
string result = Regex.Replace(
stringToLookInto,
Regex.Escape(search),
replacement.Replace("$","$$"),
RegexOptions.IgnoreCase
);
The Regex.Escape is useful if you rely on user input which can contains Regex language elements
Update
Thanks to comments, you actually don't have to escape the replacement string.
Here is a small fiddle that tests the code:
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
var tests = new[] {
new { Input="abcdef", Search="abc", Replacement="xyz", Expected="xyzdef" },
new { Input="ABCdef", Search="abc", Replacement="xyz", Expected="xyzdef" },
new { Input="A*BCdef", Search="a*bc", Replacement="xyz", Expected="xyzdef" },
new { Input="abcdef", Search="abc", Replacement="x*yz", Expected="x*yzdef" },
new { Input="abcdef", Search="abc", Replacement="$", Expected="$def" },
};
foreach(var test in tests){
var result = ReplaceCaseInsensitive(test.Input, test.Search, test.Replacement);
Console.WriteLine(
"Success: {0}, Actual: {1}, {2}",
result == test.Expected,
result,
test
);
}
}
private static string ReplaceCaseInsensitive(string input, string search, string replacement){
string result = Regex.Replace(
input,
Regex.Escape(search),
replacement.Replace("$","$$"),
RegexOptions.IgnoreCase
);
return result;
}
}
Its output is:
Success: True, Actual: xyzdef, { Input = abcdef, Search = abc, Replacement = xyz, Expected = xyzdef }
Success: True, Actual: xyzdef, { Input = ABCdef, Search = abc, Replacement = xyz, Expected = xyzdef }
Success: True, Actual: xyzdef, { Input = A*BCdef, Search = a*bc, Replacement = xyz, Expected = xyzdef }
Success: True, Actual: x*yzdef, { Input = abcdef, Search = abc, Replacement = x*yz, Expected = x*yzdef}
Success: True, Actual: $def, { Input = abcdef, Search = abc, Replacement = $, Expected = $def }
I'm freshly new with Pandas but I wanted to achieve the same thing, automatically avoiding column names with _x or _y and removing duplicate data. I finally did it by using this answer and this one from Stackoverflow
sales.csv
city;state;units Mendocino;CA;1 Denver;CO;4 Austin;TX;2
revenue.csv
branch_id;city;revenue;state_id 10;Austin;100;TX 20;Austin;83;TX 30;Austin;4;TX 47;Austin;200;TX 20;Denver;83;CO 30;Springfield;4;I
merge.py import pandas
def drop_y(df):
# list comprehension of the cols that end with '_y'
to_drop = [x for x in df if x.endswith('_y')]
df.drop(to_drop, axis=1, inplace=True)
sales = pandas.read_csv('data/sales.csv', delimiter=';')
revenue = pandas.read_csv('data/revenue.csv', delimiter=';')
result = pandas.merge(sales, revenue, how='inner', left_on=['state'], right_on=['state_id'], suffixes=('', '_y'))
drop_y(result)
result.to_csv('results/output.csv', index=True, index_label='id', sep=';')
When executing the merge command I replace the _x
suffix with an empty string and them I can remove columns ending with _y
output.csv
id;city;state;units;branch_id;revenue;state_id 0;Denver;CO;4;20;83;CO 1;Austin;TX;2;10;100;TX 2;Austin;TX;2;20;83;TX 3;Austin;TX;2;30;4;TX 4;Austin;TX;2;47;200;TX
I believe you need to .f
file as a parameter, not as a command-single-string. same with the "--domain "+i
, which i would split in two elements of the list.
Assuming that:
FORTRAN
executable, ~/
is indeed the correct way for the FORTRAN
executableI would change this line:
subprocess.Popen(["FORTRAN ~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain "+i])
to
subprocess.Popen(["FORTRAN", "~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain", i])
If that doesn't work, you should do a os.path.exists()
for the .f
file, and check that you can launch the FORTRAN
executable without any path, and set the path or system path variable accordingly
[EDIT 6-Mar-2017]
As the exception, detailed in the original post, is a python exception from subprocess
; it is likely that the WinError 2
is because it cannot find FORTRAN
I highly suggest that you specify full path for your executable:
for i in input:
exe = r'c:\somedir\fortrandir\fortran.exe'
fortran_script = r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f'
subprocess.Popen([exe, fortran_script, "--domain", i])
if you need to convert the forward-slashes to backward-slashes, as suggested in one of the comments, you can do this:
for i in input:
exe = os.path.normcase(r'c:\somedir\fortrandir\fortran.exe')
fortran_script = os.path.normcase(r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
i = os.path.normcase(i)
subprocess.Popen([exe, fortran_script, "--domain", i])
[EDIT 7-Mar-2017]
The following line is incorrect:
exe = os.path.normcase(r'~/C:/Program Files (x86)/Silverfrost/ftn95.exe'
I am not sure why you have ~/
as a prefix for every path, don't do that.
for i in input:
exe = os.path.normcase(r'C:/Program Files (x86)/Silverfrost/ftn95.exe'
fortran_script = os.path.normcase(r'C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
i = os.path.normcase(i)
subprocess.Popen([exe, fortran_script, "--domain", i])
[2nd EDIT 7-Mar-2017]
I do not know this FORTRAN or ftn95.exe, does it need a shell to function properly?, in which case you need to launch as follows:
subprocess.Popen([exe, fortran_script, "--domain", i], shell = True)
You really need to try to launch the command manually from the working directory which your python script is operating from. Once you have the command which is actually working, then build up the subprocess
command.
DECLARE @INPUT VARCHAR(5) = '0.12',@INPUT_1 VARCHAR(5)='0.12x';
select CONVERT(float, @INPUT) YOUR_QUERY ,
case when isnumeric(@INPUT_1)=1 THEN CONVERT(float, @INPUT_1) ELSE 0 END AS YOUR_QUERY_ANSWERED
above will return values
however below query wont work
DECLARE @INPUT VARCHAR(5) = '0.12',@INPUT_1 VARCHAR(5)='0.12x';
select CONVERT(float, @INPUT) YOUR_QUERY ,
case when isnumeric(@INPUT_1)=1 THEN CONVERT(float, @INPUT_1) ELSE **@INPUT_1** END AS YOUR_QUERY_ANSWERED
as @INPUT_1 actually has varchar in it.
So your output column must have a varchar in it.
Just replace the "\n
" with "".
In vi/Vim for every line in the document:
%s/>\n_/>_/g
If you want to confirm every replacement:
%s/>\n_/>_/gc
Just another information... Had that problem today on a Windows 2012 R2 x64 TS system where the application was started from a unc/network path. The issue occured for one application for all terminal server users. Executing the application locally worked without problems. After a reboot it started working again - the SEHException's thrown had been Constructor init and TargetInvocationException
To expand upon dreamlax's example... If you want to send data along with the notification
In posting code:
NSDictionary *userInfo =
[NSDictionary dictionaryWithObject:myObject forKey:@"someKey"];
[[NSNotificationCenter defaultCenter] postNotificationName:
@"TestNotification" object:nil userInfo:userInfo];
In observing code:
- (void) receiveTestNotification:(NSNotification *) notification {
NSDictionary *userInfo = notification.userInfo;
MyObject *myObject = [userInfo objectForKey:@"someKey"];
}
Data view is good Feature of data table . We can filter the data table as per our requirements using data view . Below Functions is After binding data table to list box data source then filter by text box control . ( this condition you can change as per your needs .Contains(txtSearch.Text.Trim()) )
Private Sub BindClients()
okcl = 0
sql = "Select * from Client Order By cname"
Dim dacli As New SqlClient.SqlDataAdapter
Dim cmd As New SqlClient.SqlCommand()
cmd.CommandText = sql
cmd.CommandType = CommandType.Text
dacli.SelectCommand = cmd
dacli.SelectCommand.Connection = Me.sqlcn
Dim dtcli As New DataTable
dacli.Fill(dtcli)
dacli.Fill(dataTableClients)
lstboxc.DataSource = dataTableClients
lstboxc.DisplayMember = "cname"
lstboxc.ValueMember = "ccode"
okcl = 1
If dtcli.Rows.Count > 0 Then
ccode = dtcli.Rows(0)("ccode")
Call ClientDispData1()
End If
End Sub
Private Sub FilterClients()
Dim query As EnumerableRowCollection(Of DataRow) = From dataTableClients In
dataTableClients.AsEnumerable() Where dataTableClients.Field(Of String)
("cname").Contains(txtSearch.Text.Trim()) Order By dataTableClients.Field(Of
String)("cname") Select dataTableClients
Dim dataView As DataView = query.AsDataView()
lstboxc.DataSource = dataView
lstboxc.DisplayMember = "cname"
lstboxc.ValueMember = "ccode"
okcl = 1
If dataTableClients.Rows.Count > 0 Then
ccode = dataTableClients.Rows(0)("ccode")
Call ClientDispData1()
End If
End Sub
I was researching this a while ago because I wanted to create a custom button that would open the file dialog and start the upload immediately. I just noticed something that might make this possible - firefox seems to open the dialog when you click anywhere on the upload. So the following might do it:
This is only theoretical since I already used another method to solve the problem but it just might work.
I branched off from the accepted answer to only run when the click is being HELD down and dragged.
My function was running when I wasn't holding the mouse down. Here's the updated code if you also want this functionality:
var isDragging = false;
var mouseDown = false;
$('.test_area')
.mousedown(function() {
isDragging = false;
mouseDown = true;
})
.mousemove(function(e) {
isDragging = true;
if (isDragging === true && mouseDown === true) {
my_special_function(e);
}
})
.mouseup(function(e) {
var wasDragging = isDragging;
isDragging = false;
mouseDown = false;
if ( ! wasDragging ) {
my_special_function(e);
}
}
);
To find distinct in field_1
in collection but we want some WHERE
condition too than we can do like following :
db.your_collection_name.distinct('field_1', {WHERE condition here and it should return a document})
So, find number distinct names
from a collection where age > 25 will be like :
db.your_collection_name.distinct('names', {'age': {"$gt": 25}})
Hope it helps!
Another workaround is just to set the li
item to flex
or inline-flex
. Depending on the circumstances that may suit you better. In case you have a real icon / image placed in the HTML the default flex position is on the central horizontal line.
If you want to log errors from web-page, you should use WebChromeClient
and override its onConsoleMessage
:
webView.settings.apply {
javaScriptEnabled = true
javaScriptCanOpenWindowsAutomatically = true
domStorageEnabled = true
}
webView.webViewClient = WebViewClient()
webView.webChromeClient = MyWebChromeClient()
private class MyWebChromeClient : WebChromeClient() {
override fun onConsoleMessage(consoleMessage: ConsoleMessage): Boolean {
Timber.d("${consoleMessage.message()}")
Timber.d("${consoleMessage.lineNumber()} ${consoleMessage.sourceId()}")
return super.onConsoleMessage(consoleMessage)
}
}
MSDeploy can migrate all content, config, etc. that is what the IIS team recommends. http://www.iis.net/extensions/WebDeploymentTool
To create a package, run the following command (replace Default Web Site with your web site name):
msdeploy.exe -verb:sync -source:apphostconfig="Default Web Site" -dest:package=c:\dws.zip > DWSpackage7.log
To restore the package, run the following command:
msdeploy.exe -verb:sync -source:package=c:\dws.zip -dest:apphostconfig="Default Web Site" > DWSpackage7.log
Other solutions attach a counter attribute to the function, usually with convoluted logic to handle the initialization. This is inappropriate for new code.
In Python 3, the right way is to use a nonlocal
statement:
counter = 0
def foo():
nonlocal counter
counter += 1
print(f'counter is {counter}')
See PEP 3104 for the specification of the nonlocal
statement.
If the counter is intended to be private to the module, it should be named _counter
instead.
Other solutions are great but they didn't take care of the fact that watermark shouldn't get selected on selection from the mouse. This fiddle takes care or that: https://jsfiddle.net/MiKr13/d1r4o0jg/9/
This will be better option for pdf or static html.
CSS:
#watermark {
opacity: 0.2;
font-size: 52px;
color: 'black';
background: '#ccc';
position: absolute;
cursor: default;
user-select: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
right: 5px;
bottom: 5px;
}
Probably "new f-strings in Python 3.6" is the most efficient way of concatenating strings.
Using %s
>>> timeit.timeit("""name = "Some"
... age = 100
... '%s is %s.' % (name, age)""", number = 10000)
0.0029734770068898797
Using .format
>>> timeit.timeit("""name = "Some"
... age = 100
... '{} is {}.'.format(name, age)""", number = 10000)
0.004015227983472869
Using f
>>> timeit.timeit("""name = "Some"
... age = 100
... f'{name} is {age}.'""", number = 10000)
0.0019175919878762215
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('#abc').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'post.php',
method:'POST',
data: new FormData(this),
contentType: false,
cache:false,
processData:false,
success: function (data) {
alert(data);
location.reload();
}
});
});
});
</script>
</head>
<body>
<form enctype= "multipart/form-data" id="abc">
<input name="fname" ><br>
<input name="lname"><br>
<input type="file" name="file" required=""><br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
You should use isinstance
isinstance(...)
isinstance(object, class-or-type-or-tuple) -> bool
Return whether an object is an instance of a class or of a subclass thereof.
With a type as second argument, return whether that is the object's type.
The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
isinstance(x, A) or isinstance(x, B) or ... (etc.).
You can use CSS3 filters. They are relatively easy to implement, though are only supported on webkit at the minute. Samsung Galaxy 2's browser should support though, as I think that's a webkit browser?
First you need to define a LocationListener
to handle location changes.
private final LocationListener mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(final Location location) {
//your code here
}
};
Then get the LocationManager
and ask for location updates
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME,
LOCATION_REFRESH_DISTANCE, mLocationListener);
}
And finally make sure that you have added the permission on the Manifest,
For using only network based location use this one
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
For GPS based location, this one
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
I got this error when I was trying to access a url using curl:
curl 'https://example.com:80/some/page'
The solution was to change https
to http
curl 'http://example.com:80/some/page'
I think the best way I've seen it done is multiplying by 10 to the power of the number of digits, then doing a Math.round, then finally dividing by 10 to the power of digits. Here is a simple function I use in typescript:
function roundToXDigits(value: number, digits: number) {
value = value * Math.pow(10, digits);
value = Math.round(value);
value = value / Math.pow(10, digits);
return value;
}
Or plain javascript:
function roundToXDigits(value, digits) {
if(!digits){
digits = 2;
}
value = value * Math.pow(10, digits);
value = Math.round(value);
value = value / Math.pow(10, digits);
return value;
}
Staying MVVM, I think using either Behaviors from the Blend SDK (System.Windows.Interactivity) or a custom interaction request from Prism could work really well for this sort of situation.
If going the Behavior route, here's the general idea:
public class CloseWindowBehavior : Behavior<Window>
{
public bool CloseTrigger
{
get { return (bool)GetValue(CloseTriggerProperty); }
set { SetValue(CloseTriggerProperty, value); }
}
public static readonly DependencyProperty CloseTriggerProperty =
DependencyProperty.Register("CloseTrigger", typeof(bool), typeof(CloseWindowBehavior), new PropertyMetadata(false, OnCloseTriggerChanged));
private static void OnCloseTriggerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var behavior = d as CloseWindowBehavior;
if (behavior != null)
{
behavior.OnCloseTriggerChanged();
}
}
private void OnCloseTriggerChanged()
{
// when closetrigger is true, close the window
if (this.CloseTrigger)
{
this.AssociatedObject.Close();
}
}
}
Then in your window, you would just bind the CloseTrigger to a boolean value that would be set when you wanted the window to close.
<Window x:Class="TestApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:local="clr-namespace:TestApp"
Title="MainWindow" Height="350" Width="525">
<i:Interaction.Behaviors>
<local:CloseWindowBehavior CloseTrigger="{Binding CloseTrigger}" />
</i:Interaction.Behaviors>
<Grid>
</Grid>
</Window>
Finally, your DataContext/ViewModel would have a property that you'd set when you wanted the window to close like this:
public class MainWindowViewModel : INotifyPropertyChanged
{
private bool closeTrigger;
/// <summary>
/// Gets or Sets if the main window should be closed
/// </summary>
public bool CloseTrigger
{
get { return this.closeTrigger; }
set
{
this.closeTrigger = value;
RaisePropertyChanged(nameof(CloseTrigger));
}
}
public MainWindowViewModel()
{
// just setting for example, close the window
CloseTrigger = true;
}
protected void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
(set your Window.DataContext = new MainWindowViewModel())
Please keep in mind that only a few elements can be self-closing, most others have to be closed through adding an explicit end tag. In the above case, the first script tag was not closed properly, the end script tag of the second script then closed the script section, causing only the first script to be loaded as external script source and ignoring the second script.
More info about which tags can be self-closed, have a look at the W3C drafts for HTML5 (although the definition was no different in earlier HTML-versions):
http://www.w3.org/TR/html5/syntax.html#end-tags (8.1.2.1, Point 6)
Yes.
It is a good practice since an element can be a part of different groups, and you may want specific elements to be a part of more than one group. The element can hold an infinite number of classes in HTML5, while in HTML4 you are limited by a specific length.
The following example will show you the use of multiple classes.
The first class makes the text color
red.
The second class makes the background-color
blue.
See how the DOM Element with multiple classes will behave, it will wear both CSS statements at the same time.
Result: multiple CSS statements in different classes will stack up.
You can read more about CSS Specificity.
.class1 {
color:red;
}
.class2 {
background-color:blue;
}
<div class="class1">text 1</div>
<div class="class2">text 2</div>
<div class="class1 class2">text 3</div>
Why cant you use the finally block?
Like
try {
} catch (Exception e) {
// THIS WILL EXECUTE IF THERE IS AN EXCEPTION IS THROWN IN THE TRY BLOCK
} finally {
// THIS WILL EXECUTE IRRESPECTIVE OF WHETHER AN EXCEPTION IS THROWN WITHIN THE TRY CATCH OR NOT
}
EDIT after question amended:
You can do:
int? returnFromFunction2 = null;
try {
returnFromFunction2 = function2();
return returnFromFunction2.value;
} catch (Exception e) {
// THIS WILL EXECUTE IF THERE IS AN EXCEPTION IS THROWN IN THE TRY BLOCK
} finally {
if (returnFromFunction2.HasValue) { // do something with value }
// THIS WILL EXECUTE IRRESPECTIVE OF WHETHER AN EXCEPTION IS THROWN WITHIN THE TRY CATCH OR NOT
}
#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define IS_IPHONE_X (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 812.0f)
Your answers inspired me to write some macros myself. My requirements were the following:
only write each value of the enum once, so there are no double lists to maintain
don't keep the enum values in a separate file that is later #included, so I can write it wherever I want
don't replace the enum itself, I still want to have the enum type defined, but in addition to it I want to be able to map every enum name to the corresponding string (to not affect legacy code)
the searching should be fast, so preferably no switch-case, for those huge enums
This code creates a classic enum with some values. In addition it creates as std::map which maps each enum value to it's name (i.e. map[E_SUNDAY] = "E_SUNDAY", etc.)
Ok, here is the code now:
EnumUtilsImpl.h:
map<int, string> & operator , (map<int, string> & dest,
const pair<int, string> & keyValue) {
dest[keyValue.first] = keyValue.second;
return dest;
}
#define ADD_TO_MAP(name, value) pair<int, string>(name, #name)
EnumUtils.h // this is the file you want to include whenever you need to do this stuff, you will use the macros from it:
#include "EnumUtilsImpl.h"
#define ADD_TO_ENUM(name, value) \
name value
#define MAKE_ENUM_MAP_GLOBAL(values, mapName) \
int __makeMap##mapName() {mapName, values(ADD_TO_MAP); return 0;} \
int __makeMapTmp##mapName = __makeMap##mapName();
#define MAKE_ENUM_MAP(values, mapName) \
mapName, values(ADD_TO_MAP);
MyProjectCodeFile.h // this is an example of how to use it to create a custom enum:
#include "EnumUtils.h*
#define MyEnumValues(ADD) \
ADD(val1, ), \
ADD(val2, ), \
ADD(val3, = 100), \
ADD(val4, )
enum MyEnum {
MyEnumValues(ADD_TO_ENUM)
};
map<int, string> MyEnumStrings;
// this is how you initialize it outside any function
MAKE_ENUM_MAP_GLOBAL(MyEnumValues, MyEnumStrings);
void MyInitializationMethod()
{
// or you can initialize it inside one of your functions/methods
MAKE_ENUM_MAP(MyEnumValues, MyEnumStrings);
}
Cheers.
The assertNotNull()
method means "a passed parameter must not be null
": if it is null then the test case fails.
The assertNull()
method means "a passed parameter must be null
": if it is not null then the test case fails.
String str1 = null;
String str2 = "hello";
// Success.
assertNotNull(str2);
// Fail.
assertNotNull(str1);
// Success.
assertNull(str1);
// Fail.
assertNull(str2);
A clustered index alters the way that the rows are stored. When you create a clustered index on a column (or a number of columns), SQL server sorts the table’s rows by that column(s). It is like a dictionary, where all words are sorted in alphabetical order in the entire book.
A non-clustered index, on the other hand, does not alter the way the rows are stored in the table. It creates a completely different object within the table that contains the column(s) selected for indexing and a pointer back to the table’s rows containing the data. It is like an index in the last pages of a book, where keywords are sorted and contain the page number to the material of the book for faster reference.
You can use CustomMultiChildLayout to draw this kind of layouts. Here you can find a tutorial: How to Create Custom Layout Widgets in Flutter.
You can call $setUnion
on a single array, which also filters dupes:
{ $project: {Package: 1, deps: {'$setUnion': '$deps.Package'}}}
On which point does
HTTPURLConnection
try to establish a connection to the given URL?
On the port named in the URL if any, otherwise 80 for HTTP and 443 for HTTPS. I believe this is documented.
On which point can I know that I was able to successfully establish a connection?
When you call getInputStream()
or getOutputStream()
or getResponseCode()
without getting an exception.
Are establishing a connection and sending the actual request done in one step/method call? What method is it?
No and none.
Can you explain the function of
getOutputStream()
andgetInputStream()
in layman's term?
Either of them first connects if necessary, then returns the required stream.
I notice that when the server I'm trying to connect to is down, I get an Exception at
getOutputStream()
. Does it mean thatHTTPURLConnection
will only start to establish a connection when I invokegetOutputStream()
? How about thegetInputStream()
? Since I'm only able to get the response atgetInputStream()
, then does it mean that I didn't send any request atgetOutputStream()
yet but simply establishes a connection? DoHttpURLConnection
go back to the server to request for response when I invokegetInputStream()
?
See above.
Am I correct to say that
openConnection()
simply creates a new connection object but does not establish any connection yet?
Yes.
How can I measure the read overhead and connect overhead?
Connect: take the time getInputStream()
or getOutputStream()
takes to return, whichever you call first. Read: time from starting first read to getting the EOS.
There is a library for this BarCode PHP. You just need to include a few files:
require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');
You can generate many types of barcodes, namely 1D or 2D. Add the required library:
require_once('class/BCGcode39.barcode.php');
Generate the colours:
// The arguments are R, G, and B for color.
$colorFront = new BCGColor(0, 0, 0);
$colorBack = new BCGColor(255, 255, 255);
After you have added all the codes, you will get this way:
Example
Since several have asked for an example here is what I was able to do to get it done
require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');
require_once('class/BCGcode128.barcode.php');
header('Content-Type: image/png');
$color_white = new BCGColor(255, 255, 255);
$code = new BCGcode128();
$code->parse('HELLO');
$drawing = new BCGDrawing('', $color_white);
$drawing->setBarcode($code);
$drawing->draw();
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);
If you want to actually create the image file so you can save it then change
$drawing = new BCGDrawing('', $color_white);
to
$drawing = new BCGDrawing('image.png', $color_white);
To timeout the slowcommand
after 1 second:
timeout 1 slowcommand || echo "I failed, perhaps due to time out"
To determine whether the command timed out or failed for its own reasons, check whether the status code is 124:
# ping for 3 seconds, but timeout after only 1 second
timeout 1 ping 8.8.8.8 -w3
EXIT_STATUS=$?
if [ $EXIT_STATUS -eq 124 ]
then
echo 'Process Timed Out!'
else
echo 'Process did not timeout. Something else went wrong.'
fi
exit $EXIT_STATUS
Note that when the exit status is 124, you don't know whether it timed out due to your timeout
command, or whether the command itself terminated due to some internal timeout logic of its own and then returned 124. You can safely assume in either case, though, that a timeout of some kind happened.
function get_when($date) {
$current = strtotime(date('Y-m-d H:i'));
$date_diff = $date - $current;
$difference = round($date_diff/(60*60*24));
if($difference >= 0) {
return 'Today';
} else if($difference == -1) {
return 'Yesterday';
} else if($difference == -2 || $difference == -3 || $difference == -4 || $difference == -5) {
return date('l', $date);
} else {
return ('on ' . date('jS/m/y', $date));
}
}
get_when(date('Y-m-d H:i', strtotime($your_targeted_date)));
If you use Qt and endl
, you could accidentally end up using an incorrect endl
which gives you very surprising results. See the following code snippet:
#include <iostream>
#include <QtCore/QtCore>
#include <QtGui/QtGui>
// notice that there is no "using namespace std;"
int main(int argc, char** argv)
{
QApplication qapp(argc,argv);
QMainWindow mw;
mw.show();
std::cout << "Finished Execution!" << endl;
// This prints something similar to: "Finished Execution!67006AB4"
return qapp.exec();
}
Note that I wrote endl
instead of std::endl
(which would have been correct) and apparently there is a endl
function defined in qtextstream.h (which is part of QtCore).
Using "\n"
instead of endl
completely sidesteps any potential namespace issues.
This is also a good example why putting symbols into the global namespace (like Qt does by default) is a bad idea.
The following is a sample code to pass values from one page to another using html. Here the data from page1 is passed to page2 and it's retrieved by using javascript.
1) page1.html
<!-- Value passing one page to another
Author: Codemaker
-->
<html>
<head>
<title> Page 1 - Codemaker</title>
</head>
<body>
<form method="get" action="page2.html">
<table>
<tr>
<td>First Name:</td>
<td><input type=text name=firstname size=10></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type=text name=lastname size=10></td>
</tr>
<tr>
<td>Age:</td>
<td><input type=text name=age size=10></td>
</tr>
<tr>
<td colspan=2><input type=submit value="Submit">
</td>
</tr>
</table>
</form>
</body>
</html>
2) page2.html
<!-- Value passing one page to another
Author: Codemaker
-->
<html>
<head>
<title> Page 2 - Codemaker</title>
</head>
<body>
<script>
function getParams(){
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
for (var i=0; i<pairs.length; i++){
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params;
}
params = getParams();
firstname = unescape(params["firstname"]);
lastname = unescape(params["lastname"]);
age = unescape(params["age"]);
document.write("firstname = " + firstname + "<br>");
document.write("lastname = " + lastname + "<br>");
document.write("age = " + age + "<br>");
</script>
</body>
</html>
Try
sudo apt-get update
sudo apt-get install build-essential
(If I recall correctly the package name is without the extra s
at the end).
I used interop to open Excel and to modify the column widths once the data was done. If you use interop to spit the data into a new Excel workbook (if this is what you want), it will be terribly slow. Instead, I generated a .CSV
, then opened the .CSV
in Excel. This has its own problems, but I've found this the quickest method.
First, convert the .CSV
:
// Convert array data into CSV format.
// Modified from http://csharphelper.com/blog/2018/04/write-a-csv-file-from-an-array-in-c/.
private string GetCSV(List<string> Headers, List<List<double>> Data)
{
// Get the bounds.
var rows = Data[0].Count;
var cols = Data.Count;
var row = 0;
// Convert the array into a CSV string.
StringBuilder sb = new StringBuilder();
// Add the first field in this row.
sb.Append(Headers[0]);
// Add the other fields in this row separated by commas.
for (int col = 1; col < cols; col++)
sb.Append("," + Headers[col]);
// Move to the next line.
sb.AppendLine();
for (row = 0; row < rows; row++)
{
// Add the first field in this row.
sb.Append(Data[0][row]);
// Add the other fields in this row separated by commas.
for (int col = 1; col < cols; col++)
sb.Append("," + Data[col][row]);
// Move to the next line.
sb.AppendLine();
}
// Return the CSV format string.
return sb.ToString();
}
Then, export it to Excel:
public void ExportToExcel()
{
// Initialize app and pop Excel on the screen.
var excelApp = new Excel.Application { Visible = true };
// I use unix time to give the files a unique name that's almost somewhat useful.
DateTime dateTime = DateTime.UtcNow;
long unixTime = ((DateTimeOffset)dateTime).ToUnixTimeSeconds();
var path = @"C:\Users\my\path\here + unixTime + ".csv";
var csv = GetCSV();
File.WriteAllText(path, csv);
// Create a new workbook and get its active sheet.
excelApp.Workbooks.Open(path);
var workSheet = (Excel.Worksheet)excelApp.ActiveSheet;
// iterate over each value and throw it in the chart
for (var column = 0; column < Data.Count; column++)
{
((Excel.Range)workSheet.Columns[column + 1]).AutoFit();
}
currentSheet = workSheet;
}
You'll have to install some stuff, too...
Right click on the solution from solution explorer and select "Manage NuGet Packages." - add Microsoft.Office.Interop.Excel
It might actually work right now if you created the project the way interop wants you to. If it still doesn't work, I had to create a new project in a different category. Under New > Project, select Visual C# > Windows Desktop > Console App. Otherwise, the interop tools won't work.
In case I forgot anything, here's my 'using' statements:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
Html Code:
<select id="multiple" multiple="multiple" name="multiple">
<option value=""> -- Select -- </option>
<option value="1">Opt1</option>
<option value="2">Opt2</option>
<option value="3">Opt3</option>
<option value="4">Opt4</option>
<option value="5">Opt5</option>
</select>
JQuery Code:
$('#multiple :selected').each(function(i, sel){
alert( $(sel).val() );
});
Hope it works
My website's correct path was not specified in IIS.
Just for fun, here's what I'd probably do in a real project, where I'm already using all my favourite libraries (in this case Guava, formerly known as Google Collections).
String text = Files.toString(new File("textfile.txt"), Charsets.UTF_8);
List<Integer> list = Lists.newArrayList();
for (String s : text.split("\\s")) {
list.add(Integer.valueOf(s));
}
Benefit: Not much own code to maintain (contrast with e.g. this). Edit: Although it is worth noting that in this case tschaible's Scanner solution doesn't have any more code!
Drawback: you obviously may not want to add new library dependencies just for this. (Then again, you'd be silly not to make use of Guava in your projects. ;-)
As an alternative to curl
, you can use HTTPie, it'a CLI, cURL-like tool for humans.
Installation instructions: https://github.com/jakubroztocil/httpie#installation
Then, run:
http -f POST http://localhost:4040/api/users username=johnsnow photo@images/avatar.jpg
HTTP/1.1 200 OK
Access-Control-Expose-Headers: X-Frontend
Cache-control: no-store
Connection: keep-alive
Content-Encoding: gzip
Content-Length: 89
Content-Type: text/html; charset=windows-1251
Date: Tue, 26 Jun 2018 11:11:55 GMT
Pragma: no-cache
Server: Apache
Vary: Accept-Encoding
X-Frontend: front623311
...
Example 3 in the Ruby's net/http documentation shows how to download a document over HTTP, and to output the file instead of just loading it into memory, substitute puts with a binary write to a file, e.g. as shown in Dejw's answer.
More complex cases are shown further down in the same document.
If by any chance you were using
D3.js
You could do
d3.set(["foo", "bar", "foo", "baz"]).values() ==> ["foo", "bar", "baz"]
You can just use 7zip (or another similar app) to get the dirs inside the core.zip file that's bundled in the installer. Just use 7zip to browse the exe, you'll see a core.zip file which has all the files that usually go inside "jreX" dir (where X is the major version number). As for setting env variables and the such, you can follow the other answers. If all you want is a portable jre (for example, you can run your jars by using java.exe jarfile or javaw.exe jarfile) then this solution will do. This is very similar to copying the jre dir from one place to another
In chrome to set the value you need to do YYYY-MM-DD
i guess because this worked : http://jsfiddle.net/HudMe/6/
So to make it work you need to set the date as 2012-10-01
If your string is null, calls like this should throw a NullReferenceException:
myString.equals(null)
But anyway, I think a method like this is what you want:
public static class StringUtils
{
public static bool isNullOrEmpty(String myString)
{
return myString == null || "".equals(myString);
}
}
Then in your code, you can do things like this:
if (!StringUtils.isNullOrEmpty(myString))
{
doSomething();
}
Well, LDAP is a protocol(way) to access structured info. LDAP uses client-server model so, LDAP client makes request to access required info. LDAP server stores info not in relational way but in attribute and value pair. You can use LDAP to assign same privilege to group of user or same credential to access multiple services. For more details refer following link : http://www.zytrax.com/books/ldap/ch2/
The primary flag seems to only work for vagrant ssh
for me.
In the past I have used the following method to hack around the issue.
# stage box intended for configuration closely matching production if ARGV[1] == 'stage' config.vm.define "stage" do |stage| box_setup stage, \ "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml" end end
If you don't mind picking the same item again at some other time:
$items[rand(0, count($items) - 1)];
There is an easy workaround for this problem
What you need to do, is format your dates as DD/MM/YYYY (or whichever way around you like)
Insert a column next to the time and date columns, put a formula in this column that adds them together. e.g. =A5+B5.
Format this inserted column into DD/MM/YYYY hh:mm:ss which can be found in the custom category on the formatting section
Plot a scatter graph
Badabing badaboom
If you are unhappy with this workaround, learn to use GNUplot :)
Here is a simple function to convert Bytes to KB, MB, GB, TB :
# Size in Bytes
$size = 14903511;
# Call this function to convert bytes to KB/MB/GB/TB
echo convertToReadableSize($size);
# Output => 14.2 MB
function convertToReadableSize($size){
$base = log($size) / log(1024);
$suffix = array("", "KB", "MB", "GB", "TB");
$f_base = floor($base);
return round(pow(1024, $base - floor($base)), 1) . $suffix[$f_base];
}
For me I got NumberFormatException when trying to deal with the negative numbers. I used the following for the negative and positive numbers.
System.out.println(Integer.parseUnsignedInt("11111111111111111111111111110111", 2));
Output : -9
I think that it's better to use simply str_replace, like the manual says:
If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of ereg_replace() or preg_replace().
<?
$badUrl = "http://www.site.com/backend.php?/c=crud&m=index&t=care";
$goodUrl = str_replace('?/', '?', $badUrl);
lines = open(filename).read().splitlines()
This work for me:
Get inside the container and modify the file's ACL
sudo usermod -aG docker $USER
sudo setfacl --modify user:$USER:rw /var/run/docker.sock
It's a better solution than use chmod.
Another Simple way i found in Netbeans right click on your project>libraris click add jar/folder add your comm.jar and you done.
if you dont have comm.jar download it from >>> http://llk.media.mit.edu/projects/picdev/software/javaxcomm.zip
You could also make the ajax call more generic, reusable, so you can call it from different CRUD(create, read, update, delete) tasks for example and treat the success cases from those calls.
makePostCall = function (url, data) { // here the data and url are not hardcoded anymore
var json_data = JSON.stringify(data);
return $.ajax({
type: "POST",
url: url,
data: json_data,
dataType: "json",
contentType: "application/json;charset=utf-8"
});
}
// and here a call example
makePostCall("index.php?action=READUSERS", {'city' : 'Tokio'})
.success(function(data){
// treat the READUSERS data returned
})
.fail(function(sender, message, details){
alert("Sorry, something went wrong!");
});
This is in VB.NET, just translate to C# if you need it:
<Extension()>
Public Function FindControlInRepeaterHeader(Of T As Control)(obj As Repeater, ControlName As String) As T
Dim ctrl As T = TryCast((From item As RepeaterItem In obj.Controls
Where item.ItemType = ListItemType.Header).SingleOrDefault.FindControl(ControlName),T)
Return ctrl
End Function
And use it easy:
Dim txt as string = rptrComentarios.FindControlInRepeaterHeader(Of Label)("lblVerTodosComentarios").Text
Try to make it work with footer, and items controls too =)
I found this one to be very simple!
my $line = "file1.gz file2.gz file3.gz";
my @abc = ($line =~ /(\w+[.]\w+)/g);
print $abc[0],"\n";
print $abc[1],"\n";
print $abc[2],"\n";
output:
file1.gz
file2.gz
file3.gz
Here take a look at this tutorial to find more on Perl regular expression and scroll down to More matching section.
FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.
Some references:
Though you can use any other client that allows automation.
You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).
Combine WinSCP scripting capabilities with Windows Scheduler:
A typical WinSCP script for upload (with SFTP) looks like:
open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close
With FTP, just replace the sftp://
with the ftp://
and remove the -hostkey="..."
switch.
Similarly for download: How to schedule an automatic FTP download on Windows?
WinSCP can even generate a script from an imported FileZilla session.
For details, see the guide to FileZilla automation.
(I'm the author of WinSCP)
Another option, if you are using SFTP, is the psftp.exe
client from PuTTY suite.
I faced the same problem. I had a zip archive which java.util.zip.ZipFile was not able to handle but WinRar unpacked it just fine. I found article on SDN about compressing and decompressing options in Java. I slightly modified one of example codes to produce method which was finally capable of handling the archive. Trick is in using ZipInputStream instead of ZipFile and in sequential reading of zip archive. This method is also capable of handling empty zip archive. I believe you can adjust the method to suit your needs as all zip classes have equivalent subclasses for .jar archives.
public void unzipFileIntoDirectory(File archive, File destinationDir)
throws Exception {
final int BUFFER_SIZE = 1024;
BufferedOutputStream dest = null;
FileInputStream fis = new FileInputStream(archive);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
File destFile;
while ((entry = zis.getNextEntry()) != null) {
destFile = FilesystemUtils.combineFileNames(destinationDir, entry.getName());
if (entry.isDirectory()) {
destFile.mkdirs();
continue;
} else {
int count;
byte data[] = new byte[BUFFER_SIZE];
destFile.getParentFile().mkdirs();
FileOutputStream fos = new FileOutputStream(destFile);
dest = new BufferedOutputStream(fos, BUFFER_SIZE);
while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
fos.close();
}
}
zis.close();
fis.close();
}
//This is The easiest I can Imagine .
// You need to just change the order of Columns and rows , Yours is printing columns X rows and the solution is printing them rows X columns
for(int rows=0;rows<array.length;rows++){
for(int columns=0;columns <array[rows].length;columns++){
System.out.print(array[rows][columns] + "\t" );}
System.out.println();}
Same this problem i am facing my client application is WinForms application C# 4.0
When i read the solution here, i checked Date & Time of client computer, but that was right and current time was showing, but still i was facing these problem.
After some work-around i found that wrong time zone has selected, i am in India and time zone was of Canada, the host server is located in Kuwait.
I found that system converts time to universal time.
When i changed the time zone to India's time zone, the problem was soled.
I tried a certain sequence that seems to work as you can see below:
ThisWorkbook.Saved = True
Application.Quit
Application.ActiveWindow.Close SaveChanges:=False
ActiveWorkbook.Close SaveChanges:=False
Alternatively,
<style type="text/css">
#example {
display: block;
width: 30px;
height: 10px;
background: url(../images/example.png) no-repeat;
text-indent: -9999px;
}
</style>
<a href="http://www.example.com" id="example">See an example!</a>
More wordy, but it may benefit SEO, and it will look like nice simple text with CSS disabled.
CSS
li {
display: inline-block;
}
Works for me also.
We can use infowindow.close(map); to close all info windows if you already initialize the info window using infowindow = new google.maps.InfoWindow();
I had a similar problem, and I went to Control Panel → Programs and repaired the Visual Studio installation. It worked for me.
The above all approaches are correct and may be working . I have created a working demo following the above guide and tested on 2.x to 5.x
You can clone from Github
The important thing to play around is in Main Activity
toolbar = (Toolbar) findViewById(R.id.toolbar);
res = this.getResources();
this.setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ScrimInsetsFrameLayout scrimInsetsFrameLayout = (ScrimInsetsFrameLayout)
findViewById(R.id.linearLayout);
scrimInsetsFrameLayout.setOnInsetsCallback(this);
}
and the call back
@Override
public void onInsetsChanged(Rect insets) {
Toolbar toolbar = this.toolbar;
ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams)
toolbar.getLayoutParams();
lp.topMargin = insets.top;
int top = insets.top;
insets.top += toolbar.getHeight();
toolbar.setLayoutParams(lp);
insets.top = top; // revert
}
Absolutely the Theme for V21 does the magic
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- API 21 theme customizations can go here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/accent_material_light</item>
<item name="windowActionModeOverlay">true</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:windowTranslucentStatus">true</item>
</style>
and the ScrimInsetsFrameLayout
Now this come more easy with new Design Support library
compile 'com.android.support:design:22.2.0'
clone from @Chris Banes https://github.com/chrisbanes/cheesesquare
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<form name="myform">
Enter your name
<input type="text" name="inputbox" id='textBox' value="" />
<input type="button" name="button" class="member" value="Click1" />
<input type="button" name="button" value="Click2" onClick="testResults()" />
</form>
<script>
function testResults(n) {
var answer = $("#textBox").val();
if (answer == 2) {
alert("Good !");
} else if (answer == 3) {
alert("very Good !");
} else if (answer == 4) {
alert("better !");
} else if (answer == 5) {
alert("best !");
} else {
alert('wrong');
}
}
$(document).on('click', '.member', function () {
var answer = $("#textBox").val();
if (answer == 2) {
alert("Good !");
} else if (answer == 3) {
alert("very Good !");
} else if (answer == 4) {
alert("better !");
} else if (answer == 5) {
alert("best !");
} else {
alert('wrong');
}
});
</script>
It really depends on what level you mean. In Python 2.x, there are two integer types, int
(constrained to sys.maxint
) and long
(unlimited precision), for historical reasons. In Python code, this shouldn't make a bit of difference because the interpreter automatically converts to long when a number is too large. If you want to know about the actual data types used in the underlying interpreter, that's implementation dependent. (CPython's are located in Objects/intobject.c and Objects/longobject.c.) To find out about the systems types look at cdleary answer for using the struct module.
Update as an alternative to the excellent answer from 2010:
You can now use the Get-LocalGroupMember, Get-LocalGroup, Get-LocalUser etc. to get and map users and groups
Example:
PS C:\WINDOWS\system32> Get-LocalGroupMember -name users
ObjectClass Name PrincipalSource
----------- ---- ---------------
User DESKTOP-R05QDNL\someUser1 Local
User DESKTOP-R05QDNL\someUser2 MicrosoftAccount
Group NT AUTHORITY\INTERACTIVE Unknown
You could combine that with Get-LocalUser. Alias glu can also be used instead. Aliases exists for the majority of the new cmndlets.
In case some are wondering (I know you didn't ask about this) Adding users could be for example done like so:
$description = "Netshare user"
$userName = "Test User"
$user = "test.user"
$pwd = "pwd123"
New-LocalUser $user -Password (ConvertTo-SecureString $pwd -AsPlainText -Force) -FullName $userName -Description $description
Android Studio Users:
If you want to use grade, go to http://search.maven.org/ and search for your maven repo. Then, click on the "latest version" and in the details page on the bottom left you will see "Gradle" where you can then copy/paste that link into your app's build.gradle.
Quick 'n dirty, regex-free, low-robustness chop-chop technique
string="US/Central - 10:26 PM (CST)"
etime="${string% [AP]M*}"
etime="${etime#* - }"
HTML Component
<input type="text" [formControl]="txtValue">
TS Component
public txtValue = new FormControl('', { validators:[Validators.required] });
We can use this method to save using API. LearnersModules is the module file on our Angular files SaveSampleExams is the service file is one function method.
> this.service.SaveSampleExams(LearnersModules).subscribe(
> (data) => {
> this.dataSaved = true;
> LearnersModules.txtValue = this.txtValue.value;
> });
If you want it to be more generic and independent, you can use cookie. Iframe content can set a cookie. With jquery.cookie and a timer (or in this case javascript timer), you can check if the cookie is set each second or so.
//token should be a unique random value which is also sent to ifame to get set
iframeLoadCheckTimer = window.setInterval(function () {
cookieValue = $.cookie('iframeToken');
if (cookieValue == token)
{
window.clearInterval(iframeLoadCheckTimer );
$.cookie('iframeToken', null, {
expires: 1,
path: '/'
});
}
}, 1000);
In HTML:
<form onsubmit="return false">
</form>
in order to avoid refresh at all "buttons", even with onclick assigned.
If you have installed MySQL using brew the best way to go would be with homebrew
brew services restart mysql
after you run that command, all the problems that the update generated will be resolved
To do this cross browser including IE7+, you will need to expand the plugin with a transformation matrix. Since vendor prefix is done in jQuery from jquery-1.8+ I will leave that out for the transform
property.
$.fn.animateRotate = function(endAngle, options, startAngle)
{
return this.each(function()
{
var elem = $(this), rad, costheta, sintheta, matrixValues, noTransform = !('transform' in this.style || 'webkitTransform' in this.style || 'msTransform' in this.style || 'mozTransform' in this.style || 'oTransform' in this.style),
anims = {}, animsEnd = {};
if(typeof options !== 'object')
{
options = {};
}
else if(typeof options.extra === 'object')
{
anims = options.extra;
animsEnd = options.extra;
}
anims.deg = startAngle;
animsEnd.deg = endAngle;
options.step = function(now, fx)
{
if(fx.prop === 'deg')
{
if(noTransform)
{
rad = now * (Math.PI * 2 / 360);
costheta = Math.cos(rad);
sintheta = Math.sin(rad);
matrixValues = 'M11=' + costheta + ', M12=-'+ sintheta +', M21='+ sintheta +', M22='+ costheta;
$('body').append('Test ' + matrixValues + '<br />');
elem.css({
'filter': 'progid:DXImageTransform.Microsoft.Matrix(sizingMethod=\'auto expand\','+matrixValues+')',
'-ms-filter': 'progid:DXImageTransform.Microsoft.Matrix(sizingMethod=\'auto expand\','+matrixValues+')'
});
}
else
{
elem.css({
//webkitTransform: 'rotate('+now+'deg)',
//mozTransform: 'rotate('+now+'deg)',
//msTransform: 'rotate('+now+'deg)',
//oTransform: 'rotate('+now+'deg)',
transform: 'rotate('+now+'deg)'
});
}
}
};
if(startAngle)
{
$(anims).animate(animsEnd, options);
}
else
{
elem.animate(animsEnd, options);
}
});
};
Note: The parameters options
and startAngle
are optional, if you only need to set startAngle
use {}
or null
for options
.
Example usage:
var obj = $(document.createElement('div'));
obj.on("click", function(){
obj.stop().animateRotate(180, {
duration: 250,
complete: function()
{
obj.animateRotate(0, {
duration: 250
});
}
});
});
obj.text('Click me!');
obj.css({cursor: 'pointer', position: 'absolute'});
$('body').append(obj);
See also this jsfiddle for a demo.
Update: You can now also pass extra: {}
in the options. This will make you able to execute other animations simultaneously. For example:
obj.animateRotate(90, {extra: {marginLeft: '100px', opacity: 0.5}});
This will rotate the element 90 degrees, and move it to the right with 100px and make it semi-transparent all at the same time during the animation.
Try this query. Its very easy to understand:
CREATE TABLE PersonsDetail(FirstName nvarchar(20), LastName nvarchar(20), GenderID int);
GO
INSERT INTO PersonsDetail VALUES(N'Gourav', N'Bhatia', 2),
(N'Ramesh', N'Kumar', 1),
(N'Ram', N'Lal', 2),
(N'Sunil', N'Kumar', 3),
(N'Sunny', N'Sehgal', 1),
(N'Malkeet', N'Shaoul', 3),
(N'Jassy', N'Sohal', 2);
GO
SELECT FirstName, LastName, Gender =
CASE GenderID
WHEN 1 THEN 'Male'
WHEN 2 THEN 'Female'
ELSE 'Unknown'
END
FROM PersonsDetail
Use strtotime(..)
:
$timestamp = strtotime($mysqltime);
echo date("Y-m-d H:i:s", $timestamp);
Also check this out (to do it in MySQL way.)
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_unix-timestamp
I wanted to add this answer because I used the primary answer from this question as my basis for exporting from a datatable to Excel using OpenXML but then transitioned to OpenXMLWriter when I found it to be much faster than the above method.
You can find the full details in my answer in the link below. My code is in VB.NET though, so you'll have to convert it.
If you'd rather copy the properties:
var json1 = { value1: '1', value2: '2' };
var json2 = { value2: '4', value3: '3' };
function jsonConcat(o1, o2) {
for (var key in o2) {
o1[key] = o2[key];
}
return o1;
}
var output = {};
output = jsonConcat(output, json1);
output = jsonConcat(output, json2);
Output of above code is{ value1: '1', value2: '4', value3: '3' }
You are looking to see if a single value is in an array. Use in_array
.
However note that case is important, as are any leading or trailing spaces. Use var_dump
to find out the length of the strings too, and see if they fit.
If you want to pass a JavaScript object/hash (ie. an associative array in PHP) then you would do:
$.post('/url/to/page', {'key1': 'value', 'key2': 'value'});
If you wanna pass an actual array (ie. an indexed array in PHP) then you can do:
$.post('/url/to/page', {'someKeyName': ['value','value']});
If you want to pass a JavaScript array then you can do:
$.post('/url/to/page', {'someKeyName': variableName});
I forgot about the GNOME tech of "apport", but I don't know much about using it. It is used to generate stacktraces and other diagnostics for processing and can automatically file bugs. It's certainly worth checking in to.
In platforms like Java, int
s are primitives while Integer
is an object which holds a integer field. The important distinction is that primitives are always passed around by value and by definition are immutable.
Any operation involving a primitive variable always returns a new value. On the other hand, objects are passed around by reference. One could argue that the point to the object (AKA the reference) is also being passed around by value, but the contents are not.
Mac OSX only
An easier way to get going (assuming you already have homebrew installed, which you should, if not, go do that first and let homebrew make your life better) is to just run the following command:
brew install chromedriver
That should put the chromedriver in your path and you should be all set.
# this is comment
this isn't comment
is the way to do it. You can place it anywhere in the line and anything that comes later will be ignored
Make sure it's within a document ready tagAlternatively, try using .live
$(document).ready(function(){
$('#content').live('click', function(e) {
alert(1);
});
});
Example:
$(document).ready(function() {_x000D_
$('#content').click(function(e) { _x000D_
alert(1);_x000D_
});_x000D_
});
_x000D_
#content {_x000D_
padding: 20px;_x000D_
background: blue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>_x000D_
<div id="content">Hello world</div>
_x000D_
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.
$('#content').on( "click", function() {
alert(1);
});
You are inside a namespace
so you should use \Exception
to specify the global namespace:
try {
$this->buildXMLHeader();
} catch (\Exception $e) {
return $e->getMessage();
}
In your code you've used catch (Exception $e)
so Exception
is being searched in/as:
App\Services\PayUService\Exception
Since there is no Exception
class inside App\Services\PayUService
so it's not being triggered. Alternatively, you can use a use
statement at the top of your class like use Exception;
and then you can use catch (Exception $e)
.
I just had a similar problem. The error said the same the in the question, tried to solve it with the answer of pkozlowski.opensource and Ben G, which both are correct and good answers.
My problem was indeed different with the same error:
in my HTML-Code I had the initialisation like this...
<html ng-app>
A bit further down I tried to do something like this:
<div id="cartView" ng-app="myApp" ng-controller="CartCtrl">
I got rid of the first one... then it worked... obviously you can't initialise ng-app twice or more times. fair enough.
I totaly forgot about the first "ng-app" and got totaly frustrated. Maybe this is gonna help someone oneday...
https://github.com/nigma/django-easy-pdf
Template:
{% extends "easy_pdf/base.html" %}
{% block content %}
<div id="content">
<h1>Hi there!</h1>
</div>
{% endblock %}
View:
from easy_pdf.views import PDFTemplateView
class HelloPDFView(PDFTemplateView):
template_name = "hello.html"
If you want to use django-easy-pdf on Python 3 check the solution suggested here.
Possible Duplicate:
Just Additional Info which took me long time to find.what if you were using the field name and not id for identifying the form field. You do it like this:
For radio button:
var inp= $('input:radio[name=PatientPreviouslyReceivedDrug]:checked').val();
For textbox:
var txt=$('input:text[name=DrugDurationLength]').val();
You should add client option to your mysql-connector allowPublicKeyRetrieval=true
to allow the client to automatically request the public key from the server. Note that AllowPublicKeyRetrieval=True
could allow a malicious proxy to perform a MITM attack to get the plaintext password, so it is False by default and must be explicitly enabled.
https://mysql-net.github.io/MySqlConnector/connection-options/
you could also try adding useSSL=false
when you use it for testing/develop purposes
example:
jdbc:mysql://localhost:3306/db?allowPublicKeyRetrieval=true&useSSL=false
The ModuleNotFoundError
has been introduced in python 3.6 and can be used for this purpose
try:
import eggs
except ModuleNotFoundError:
# Error handling
pass
The error is raised when a module or one of its parents cannot be found. So
try:
import eggs.sub
except ModuleNotFoundError as err:
# Error handling
print(err)
would print a message that looks like No module named 'eggs'
if the eggs
module cannot be found; but would print something like No module named 'eggs.sub'
if only the sub
module couldn't be found but the eggs
package could be found.
See the documentation of the import system for more info on the ModuleNotFoundError
I like:
git format-patch HEAD~<N>
where <N>
is number of last commits to save as patches.
The details how to use the command are in the DOC
UPD
Here you can find how to apply them then.
UPD For those who did not get the idea of format-patch
Add alias:
git config --global alias.make-patch '!bash -c "cd ${GIT_PREFIX};git add .;git commit -m ''uncommited''; git format-patch HEAD~1; git reset HEAD~1"'
Then at any directory of your project repository run:
git make-patch
This command will create 0001-uncommited.patch
at your current directory. Patch will contain all the changes and untracked files that are visible to next command:
git status .
In the first situation, Num2
is extending the class Num
and since you are not redefining the special method named __init__()
in Num2
, it gets inherited from Num
.
When a class defines an
__init__()
method, class instantiation automatically invokes__init__()
for the newly-created class instance.
In the second situation, since you are redefining __init__()
in Num2
you need to explicitly call the one in the super class (Num
) if you want to extend its behavior.
class Num2(Num):
def __init__(self,num):
Num.__init__(self,num)
self.n2 = num*2
The problem is that I missed out 'db' folder for the dbpath in the command:
C:\mongodb\bin> mongod --directoryperdb --dbpath C:\mongodb\data\db --logpath C:\mongodb\log\mongodb.log --logappend -rest --install
You can't do the second, because even if you use the remove()
method on Iterator, you'll get an Exception thrown.
Personally, I would prefer the first for all Collection
instances, despite the additional overheard of creating the new Collection
, I find it less prone to error during edit by other developers. On some Collection implementations, the Iterator remove()
is supported, on other it isn't. You can read more in the docs for Iterator.
The third alternative, is to create a new Collection
, iterate over the original, and add all the members of the first Collection
to the second Collection
that are not up for deletion. Depending on the size of the Collection
and the number of deletes, this could significantly save on memory, when compared to the first approach.
Example:
Let's say table A has two children B and C. Then we can use the following syntax to drop all tables.
DROP TABLE IF EXISTS B,C,A;
This can be placed in the beginning of the script instead of individually dropping each table.
On your form elements use input type="time"
. It will save you all the hassle of trying to use a data picker library.
The stopPropagation
options are bad because they can interfere with other event handlers including other menus that might have attached close handlers to the HTML element.
Here is a simple solution based on user2989143's answer:
$('html').click(function(event) {
if ($(event.target).closest('#menu-container, #menu-activator').length === 0) {
$('#menu-container').hide();
}
});
return true not work
return false working
found = false;
query = "foo";
$('.items').each(function()
{
if($(this).text() == query)
{
found = true;
return false;
}
});
Try using the [StringLength]
attribute:
[Required(ErrorMessage = "Name is required.")]
[StringLength(40, ErrorMessage = "Name cannot be longer than 40 characters.")]
public string Name { get; set; }
That's for validation purposes. If you want to set for example the maxlength attribute on the input you could write a custom data annotations metadata provider as shown in this post and customize the default templates.
Similar to other syntax above but for learning - can you sort by column names?
sort(colnames(test[1:ncol(test)] ))
Here's a function I've been using that I've put together from various threads around the net that removes everything, all tags and leaves you with a perfect phrase. Does anyone know how to modify this script to allow periods (.) ? In other words, leave everything 'as is' but leave the periods alone or other punctuation like and ! or a comma? let me know.
function stripAlpha( $item )
{
$search = array(
'@<script[^>]*?>.*?</script>@si' // Strip out javascript
,'@<style[^>]*?>.*?</style>@siU' // Strip style tags properly
,'@<[\/\!]*?[^<>]*?>@si' // Strip out HTML tags
,'@<![\s\S]*?–[ \t\n\r]*>@' // Strip multi-line comments including CDATA
,'/\s{2,}/'
,'/(\s){2,}/'
);
$pattern = array(
'#[^a-zA-Z ]#' // Non alpha characters
,'/\s+/' // More than one whitespace
);
$replace = array(
''
,' '
);
$item = preg_replace( $search, '', html_entity_decode( $item ) );
$item = trim( preg_replace( $pattern, $replace, strip_tags( $item ) ) );
return $item;
}
There is no unsigned byte in Java, but if you want to display a byte, you can do,
int myInt = 144;
byte myByte = (byte) myInt;
char myChar = (char) (myByte & 0xFF);
System.out.println("myChar :" + Integer.toHexString(myChar));
Output:
myChar : 90
For more information, please check, How to display a hex/byte value in Java.
Is there maybe a way to grab the rendered page from the internet explorer rendering engine and send it to a PDF-Printer tool automatically?
This is how ActivePDF works, which is good means that you know what you'll get, and it actually has reasonable styling support.
It is also one of the few packages I found (when looking a few years back) that actually supports the various page-break CSS commands.
Unfortunately, the ActivePDF software is very frustrating - since it has to launch the IE browser in the background for conversions it can be quite slow, and it is not particularly stable either.
There is a new version currently in Beta which is supposed to be much better, but I've not actually had a chance to try it out, so don't know how much of an improvement it is.
I think the problem is with the datatype of the data you are passing Caused by: java.sql.SQLException: Invalid column type: 1111
check the datatypes you pass with the actual column datatypes may be there can be some mismatch or some constraint violation with null
long millisecond = beginupd.getTime();
Date.getTime()
JavaDoc states:
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
You want:
if (document.getElementById('customx').value === ""){
//do something
}
The value
property will give you a string value and you need to compare that against an empty string.
On Windows 7, go to C:\Users\%User_Name%\AppData\Roaming\Subversion and remove the auth directory. Just be aware if you are connected to more than 1 SVN server that this will remove the authentication for all of the SVN servers you have configured. If you want to reset just a single server:
Inside the auth directory you should see a folder called svn.simple. Open each of those files with a text editor to determine which one to remove and then remove just that single file.
Using interface
as message constant is generally a bad idea. It will leak into client program permanently as part of exported API. Who knows, that later client programmers might parse that error messages(public) as part of their program.
You will be locked forever to support this, as changes in string format will/may break client program.
One way is to: (Assumes index column begins at A1)
MsgBox Range("A1").End(xlDown).Row
Which is looking for the 1st unoccupied cell downwards from A1 and showing you its ordinal row number.
You can select the next empty cell with:
Range("A1").End(xlDown).Offset(1, 0).Select
If you need the end of a dataset (including blanks), try: Range("A:A").SpecialCells(xlLastCell).Row
Have you tried this?
ALTER TABLE <table_name> MODIFY <col_name> VARCHAR(65353);
This will change the col_name's type to VARCHAR(65353)
This method helped me when trying to retrieve data from Text File and store it in Array then Assign it to a string avariable.
string[] lines = File.ReadAllLines(Environment.CurrentDirectory + "\\Notes.txt");
string marRes = string.Join(Environment.NewLine, lines.ToArray());
Hopefully may help Someone!!!!
Try either
sudo apt-get install php-zip
orsudo apt-get install php5.6-zip
Then, you might have to restart your web server.
sudo service apache2 restart
orsudo service nginx restart
If you are installing on centos or fedora OS then use yum in place of apt-get. example:-
sudo yum install php-zip
or
sudo yum install php5.6-zip
and
sudo service httpd restart
Apparently it is implemented now DATAJPA-231
Use
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class test {
public static void main(String[] args){
try {
File fileDir = new File("PATH_TO_FILE");
BufferedReader in = new BufferedReader(
new InputStreamReader(new FileInputStream(fileDir), "UTF-8"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
}
catch (UnsupportedEncodingException e)
{
System.out.println(e.getMessage());
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
You need to put UTF-8 in quotes
Try this:
HTML:
<table width="200" border="1" class="table">
<tr>
<td><a href="#"> </a></td>
<td> </td>
<td> </td>
</tr>
</table>
CSS:
.table a
{
display:block;
text-decoration:none;
}
I hope it will work fine.
Perhaps use plt.annotate:
import numpy as np
import matplotlib.pyplot as plt
N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]
plt.subplots_adjust(bottom = 0.1)
plt.scatter(
data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
cmap=plt.get_cmap('Spectral'))
for label, x, y in zip(labels, data[:, 0], data[:, 1]):
plt.annotate(
label,
xy=(x, y), xytext=(-20, 20),
textcoords='offset points', ha='right', va='bottom',
bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))
plt.show()
You should make x
and y
numpy arrays, not lists:
x = np.array([0.46,0.59,0.68,0.99,0.39,0.31,1.09,
0.77,0.72,0.49,0.55,0.62,0.58,0.88,0.78])
y = np.array([0.315,0.383,0.452,0.650,0.279,0.215,0.727,0.512,
0.478,0.335,0.365,0.424,0.390,0.585,0.511])
With this change, it produces the expect plot. If they are lists, m * x
will not produce the result you expect, but an empty list. Note that m
is anumpy.float64
scalar, not a standard Python float
.
I actually consider this a bit dubious behavior of Numpy. In normal Python, multiplying a list with an integer just repeats the list:
In [42]: 2 * [1, 2, 3]
Out[42]: [1, 2, 3, 1, 2, 3]
while multiplying a list with a float gives an error (as I think it should):
In [43]: 1.5 * [1, 2, 3]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-43-d710bb467cdd> in <module>()
----> 1 1.5 * [1, 2, 3]
TypeError: can't multiply sequence by non-int of type 'float'
The weird thing is that multiplying a Python list with a Numpy scalar apparently works:
In [45]: np.float64(0.5) * [1, 2, 3]
Out[45]: []
In [46]: np.float64(1.5) * [1, 2, 3]
Out[46]: [1, 2, 3]
In [47]: np.float64(2.5) * [1, 2, 3]
Out[47]: [1, 2, 3, 1, 2, 3]
So it seems that the float gets truncated to an int, after which you get the standard Python behavior of repeating the list, which is quite unexpected behavior. The best thing would have been to raise an error (so that you would have spotted the problem yourself instead of having to ask your question on Stackoverflow) or to just show the expected element-wise multiplication (in which your code would have just worked). Interestingly, addition between a list and a Numpy scalar does work:
In [69]: np.float64(0.123) + [1, 2, 3]
Out[69]: array([ 1.123, 2.123, 3.123])
The primary goal of a hashmap is to store a data set and provide near constant time lookups on it using a unique key. There are two common styles of hashmap implementation:
Separate chaining is preferable if the hashmap may have a poor hash function, it is not desirable to pre-allocate storage for potentially unused slots, or entries may have variable size. This type of hashmap may continue to function relatively efficiently even when the load factor exceeds 1.0. Obviously, there is extra memory required in each entry to store linked list pointers.
Hashmaps using open addressing have potential performance advantages when the load factor is kept below a certain threshold (generally about 0.7) and a reasonably good hash function is used. This is because they avoid potential cache misses and many small memory allocations associated with a linked list, and perform all operations in a contiguous, pre-allocated array. Iteration through all elements is also cheaper. The catch is hashmaps using open addressing must be reallocated to a larger size and rehashed to maintain an ideal load factor, or they face a significant performance penalty. It is impossible for their load factor to exceed 1.0.
Some key performance metrics to evaluate when creating a hashmap would include:
Here is a flexible hashmap implementation I made. I used open addressing and linear probing for collision resolution.
I was facing the similar problem, but instead of one all of my pods were not ready and displaying Ready status 0/1 Something like
I tried a lot of things but at last i found that the context was not correctly set. Please use following command and ensure you are in correct context
kubectl config get-contexts
I often use git reset --mixed to revert a base version before multiple commits which you want to merge, then I make a new commit, that way could let your commit newest, assure your version is HEAD after you push to server.
commit ac72a4308ba70cc42aace47509a5e
Author: <[email protected]>
Date: Tue Jun 11 10:23:07 2013 +0500
Added algorithms for Cosine-similarity
commit 77df2a40e53136c7a2d58fd847372
Author: <[email protected]>
Date: Tue Jun 11 13:02:14 2013 -0700
Set stage for similar objects
commit 249cf9392da197573a17c8426c282
Author: Ralph <[email protected]>
Date: Thu Jun 13 16:44:12 2013 -0700
Fixed a bug in space world automation
If I want to merge head two commits into one, first I use :
git reset --mixed 249cf9392da197573a17c8426c282
"249cf9392da197573a17c8426c282" was third version, also is your base version before you merge, after that, I make a new commit :
git add .
git commit -m 'some commit message'
It's all, hope is another way for everybody.
FYI, from git reset --help
:
--mixed
Resets the index but not the working tree (i.e., the changed files are
preserved but not marked for commit) and reports what has not been
updated. This is the default action.
This may be coming in Late but I think I figured out a better way to load external configurations especially when you run your spring-boot app using java jar myapp.war
instead of @PropertySource("classpath:some.properties")
The configuration would be loaded form the root of the project or from the location the war/jar file is being run from
public class Application implements EnvironmentAware {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
@Override
public void setEnvironment(Environment environment) {
//Set up Relative path of Configuration directory/folder, should be at the root of the project or the same folder where the jar/war is placed or being run from
String configFolder = "config";
//All static property file names here
List<String> propertyFiles = Arrays.asList("application.properties","server.properties");
//This is also useful for appending the profile names
Arrays.asList(environment.getActiveProfiles()).stream().forEach(environmentName -> propertyFiles.add(String.format("application-%s.properties", environmentName)));
for (String configFileName : propertyFiles) {
File configFile = new File(configFolder, configFileName);
LOGGER.info("\n\n\n\n");
LOGGER.info(String.format("looking for configuration %s from %s", configFileName, configFolder));
FileSystemResource springResource = new FileSystemResource(configFile);
LOGGER.log(Level.INFO, "Config file : {0}", (configFile.exists() ? "FOund" : "Not Found"));
if (configFile.exists()) {
try {
LOGGER.info(String.format("Loading configuration file %s", configFileName));
PropertiesFactoryBean pfb = new PropertiesFactoryBean();
pfb.setFileEncoding("UTF-8");
pfb.setLocation(springResource);
pfb.afterPropertiesSet();
Properties properties = pfb.getObject();
PropertiesPropertySource externalConfig = new PropertiesPropertySource("externalConfig", properties);
((ConfigurableEnvironment) environment).getPropertySources().addFirst(externalConfig);
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
} else {
LOGGER.info(String.format("Cannot find Configuration file %s... \n\n\n\n", configFileName));
}
}
}
}
Hope it helps.
I just gave this a whirl in both Chrome and Firefox and IE10.
As mentioned above - make sure that you have marked up with type = "button", "reset", "submit" etc to ensure that it correctly cascades and chooses the correct button.
Perhaps also setting all of them to have the same form (ie all as that worked for me)
this work for me on galaxy note its show contacts, file managers installed on device, gallery, music player
private void openFile(Int CODE) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("*/*");
startActivityForResult(intent, CODE);
}
here get path in onActivityResult
of activity.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
String Fpath = data.getDataString();
// do somthing...
super.onActivityResult(requestCode, resultCode, data);
}
Technically what you are looking for is the unset value in combination with the shorthand property all:
The unset CSS keyword resets a property to its inherited value if it inherits from its parent, and to its initial value if not. In other words, it behaves like the inherit keyword in the first case, and like the initial keyword in the second case. It can be applied to any CSS property, including the CSS shorthand all.
.customClass {
/* specific attribute */
color: unset;
}
.otherClass{
/* unset all attributes */
all: unset;
/* then set own attributes */
color: red;
}
You can use the initial value as well, this will default to the initial browser value.
.otherClass{
/* unset all attributes */
all: initial;
/* then set own attributes */
color: red;
}
As an alternative:
If possible it is probably good practice to encapsulate the class or id in a kind of namespace:
.namespace .customClass{
color: red;
}
<div class="namespace">
<div class="customClass"></div>
</div>
because of the specificity of the selector this will only influence your own classes
It is easier to accomplish this in "preprocessor scripting languages" like SASS with nesting capabilities:
.namespace{
.customClass{
color: red
}
}
I am running on FreeBSD 11.1, the freebsd jail virtualization concept makes the operating system optimal. The current version of Git I am using is 2.15.1, I also prefer to run everything on shell scripts. With that in mind I modified the suggestions above as followed:
git push: .git/hooks/pre-commit
#! /bin/sh -
#
# A hook script called by "git commit" with no arguments. The hook should
# exit with non-zero status after issuing an appropriate message if it wants
# to stop the commit.
SELF_DIR=$(git rev-parse --show-toplevel);
DATABASE=$SELF_DIR/.permissions;
# Clear the permissions database file
> $DATABASE;
printf "Backing-up file permissions...\n";
OLDIFS=$IFS;
IFS=$'\n';
for FILE in $(git ls-files);
do
# Save the permissions of all the files in the index
printf "%s;%s\n" $FILE $(stat -f "%Lp;%u;%g" $FILE) >> $DATABASE;
done
IFS=$OLDIFS;
# Add the permissions database file to the index
git add $DATABASE;
printf "OK\n";
git pull: .git/hooks/post-merge
#! /bin/sh -
SELF_DIR=$(git rev-parse --show-toplevel);
DATABASE=$SELF_DIR/.permissions;
printf "Restoring file permissions...\n";
OLDIFS=$IFS;
IFS=$'\n';
while read -r LINE || [ -n "$LINE" ];
do
FILE=$(printf "%s" $LINE | cut -d ";" -f 1);
PERMISSIONS=$(printf "%s" $LINE | cut -d ";" -f 2);
USER=$(printf "%s" $LINE | cut -d ";" -f 3);
GROUP=$(printf "%s" $LINE | cut -d ";" -f 4);
# Set the file permissions
chmod $PERMISSIONS $FILE;
# Set the file owner and groups
chown $USER:$GROUP $FILE;
done < $DATABASE
IFS=$OLDIFS
pritnf "OK\n";
exit 0;
If for some reason you need to recreate the script the .permissions file output should have the following format:
.gitignore;644;0;0
For a .gitignore file with 644 permissions given to root:wheel
Notice I had to make a few changes to the stat options.
Enjoy,
You can do this with git log
:
git log origin..
Assuming that origin
is the name of your upstream, leaving off any revision name after ..
implies HEAD
, which lists the new commits that haven't been pushed.
Have a look in the syslogins or sysusers tables in the master schema. Not sure if this still still around in more recent MSSQL versions though. In MSSQL 2005 there are views called sys.syslogins and sys.sysusers.
raw_input
can correctly handle the EOF, so we can write a loop, read till we have received an EOF (Ctrl-D) from user:
print("Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it.")
contents = []
while True:
try:
line = input()
except EOFError:
break
contents.append(line)
print "Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it."
contents = []
while True:
try:
line = raw_input("")
except EOFError:
break
contents.append(line)
Open Task Manager and find service adb.exe after saw those service just end it, and run again
Oh ye of little faith:
SELECT *, IDENTITY( int ) AS idcol
INTO #newtable
FROM oldtable
http://msdn.microsoft.com/en-us/library/aa933208(SQL.80).aspx
To use IN, you must have a set, use this syntax instead:
SELECT * FROM Table1 WHERE Table1.principal NOT IN (SELECT principal FROM table2)
The following code, provides a precision way to pause resume a timer.
How it works:
When the timer is resumed after a pause, it generates a correction cycle using a single timeout
, that will consider the pause offset (exact time when the timer was paused between cycles). After the correction cycle finishes, it schedules the following cycles with a regular setInteval
, and continues normally the cycle execution.
This allows to pause/resume the timer, without losing the sync.
Code :
function Timer(_fn_callback_ , _timer_freq_){_x000D_
let RESUME_CORRECTION_RATE = 2;_x000D_
_x000D_
let _timer_statusCode_;_x000D_
let _timer_clockRef_;_x000D_
_x000D_
let _time_ellapsed_; // will store the total time ellapsed_x000D_
let _time_pause_; // stores the time when timer is paused_x000D_
let _time_lastCycle_; // stores the time of the last cycle_x000D_
_x000D_
let _isCorrectionCycle_;_x000D_
_x000D_
/**_x000D_
* execute in each clock cycle_x000D_
*/_x000D_
const nextCycle = function(){_x000D_
// calculate deltaTime_x000D_
let _time_delta_ = new Date() - _time_lastCycle_;_x000D_
_time_lastCycle_ = new Date();_x000D_
_time_ellapsed_ += _time_delta_;_x000D_
_x000D_
// if its a correction cicle (caused by a pause,_x000D_
// destroy the temporary timeout and generate a definitive interval_x000D_
if( _isCorrectionCycle_ ){_x000D_
clearTimeout( _timer_clockRef_ );_x000D_
clearInterval( _timer_clockRef_ );_x000D_
_timer_clockRef_ = setInterval( nextCycle , _timer_freq_ );_x000D_
_isCorrectionCycle_ = false;_x000D_
}_x000D_
// execute callback_x000D_
_fn_callback_.apply( timer, [ timer ] );_x000D_
};_x000D_
_x000D_
// initialize timer_x000D_
_time_ellapsed_ = 0;_x000D_
_time_lastCycle_ = new Date();_x000D_
_timer_statusCode_ = 1;_x000D_
_timer_clockRef_ = setInterval( nextCycle , _timer_freq_ );_x000D_
_x000D_
_x000D_
// timer public API_x000D_
const timer = {_x000D_
get statusCode(){ return _timer_statusCode_ },_x000D_
get timestamp(){_x000D_
let abstime;_x000D_
if( _timer_statusCode_=== 1 ) abstime = _time_ellapsed_ + ( new Date() - _time_lastCycle_ );_x000D_
else if( _timer_statusCode_=== 2 ) abstime = _time_ellapsed_ + ( _time_pause_ - _time_lastCycle_ );_x000D_
return abstime || 0;_x000D_
},_x000D_
_x000D_
pause : function(){_x000D_
if( _timer_statusCode_ !== 1 ) return this;_x000D_
// stop timers_x000D_
clearTimeout( _timer_clockRef_ );_x000D_
clearInterval( _timer_clockRef_ );_x000D_
// set new status and store current time, it will be used on_x000D_
// resume to calculate how much time is left for next cycle_x000D_
// to be triggered_x000D_
_timer_statusCode_ = 2;_x000D_
_time_pause_ = new Date();_x000D_
return this;_x000D_
},_x000D_
_x000D_
resume: function(){_x000D_
if( _timer_statusCode_ !== 2 ) return this;_x000D_
_timer_statusCode_ = 1;_x000D_
_isCorrectionCycle_ = true;_x000D_
const delayEllapsedTime = _time_pause_ - _time_lastCycle_;_x000D_
_time_lastCycle_ = new Date( new Date() - (_time_pause_ - _time_lastCycle_) );_x000D_
_x000D_
_timer_clockRef_ = setTimeout( nextCycle , _timer_freq_ - delayEllapsedTime - RESUME_CORRECTION_RATE);_x000D_
_x000D_
return this;_x000D_
} _x000D_
};_x000D_
return timer;_x000D_
};_x000D_
_x000D_
_x000D_
let myTimer = Timer( x=> console.log(x.timestamp), 1000);
_x000D_
<input type="button" onclick="myTimer.pause()" value="pause">_x000D_
<input type="button" onclick="myTimer.resume()" value="resume">
_x000D_
Code source :
This Timer is a modified and simplified version of advanced-timer
, a js library created by myself, with many more functionalities.
The full library and documentation is available in NPM and GITHUB
Mhh.. I think @Damian asks for remove undefined field (property) from an JS object
.
Then, I would simply do :
for (const i in myObj)
if (typeof myObj[i] === 'undefined')
delete myObj[i];
Short and efficient solution, in (vanilla) JS ! Example :
const myObj = {_x000D_
a: 1,_x000D_
b: undefined,_x000D_
c: null, _x000D_
d: 'hello world'_x000D_
};_x000D_
_x000D_
for (const i in myObj) _x000D_
if (typeof myObj[i] === 'undefined') _x000D_
delete myObj[i]; _x000D_
_x000D_
console.log(myObj);
_x000D_
The Effectively final variable is a local variable that is:
final
While a final variable is a variable that is:
final
keyword.You may have enough correct answers for your question but in case your IDE gives you the warning
Promise returned from navigate is ignored
you may either ignore that warning or use this.router.navigate(['/your-path']).then()
.
$("input[type=checkbox]").on("change", function() {
if (this.checked) {
//do your stuff
}
});
addedMonth <- seq(as.Date('2004-01-01'), length=2, by='1 month')[2]
addedQuarter <- seq(as.Date('2004-01-01'), length=2, by='1 quarter')[2]
From the document
This runs an arbitrary command specified in the package's "start" property of its "scripts" object. If no "start" property is specified on the "scripts" object, it will run node server.js.
which means it will call the start scripts inside the package.json
"scripts": {
"start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite --baseDir ./app --port 8001\" ",
"lite": "lite-server",
...
}
Provided by angular/angular-cli to start angular2 apps which created by angular-cli. when you install angular-cli, it will create ng.cmd under C:\Users\name\AppData\Roaming\npm
(for windows) and execute "%~dp0\node.exe" "%~dp0\node_modules\angular-cli\bin\ng" %*
So using npm start
you can make your own execution where is ng serve
is only for angular-cli
See Also : What happens when you run ng serve?
For a multi-threaded problem, we needed a complex object to be built up for each thread. The object represented the data being processed, and could change depending on the user input.
Could we use a factory instead? Yes
Why didn't we? Builder makes more sense I guess.
Factories are used for creating different types of objects that are the same basic type (implement the same interface or base class).
Builders build the same type of object over and over, but the construction is dynamic so it can be changed at runtime.
Date.parse
recognizes only specific formats, and you don't have the option of telling it what your input format is. In this case it thinks that the input is in the format mm/dd/yyyy
, so the result is wrong.
To fix this, you need either to parse the input yourself (e.g. with String.split
) and then manually construct a Date
object, or use a more full-featured library such as datejs.
Example for manual parsing:
var input = $('#' + controlName).val();
var parts = str.split("/");
var d1 = new Date(Number(parts[2]), Number(parts[1]) - 1, Number(parts[0]));
Example using date.js:
var input = $('#' + controlName).val();
var d1 = Date.parseExact(input, "d/M/yyyy");
try this. There are in general three ways to use mysqldump—
in order to dump a set of one or more tables,
shell> mysqldump [options] db_name [tbl_name ...]
a set of one or more complete databases
shell> mysqldump [options] --databases db_name ...
or an entire MySQL server—as shown here:
shell> mysqldump [options] --all-databases
You Can simply Use One Jsp Page To accomplish the task.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String username=request.getParameter("user_name");
String password=request.getParameter("password");
String role=request.getParameter("role");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
Statement st=con.createStatement();
String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
ResultSet rs=st.executeQuery(query);
while(rs.next())
{
session.setAttribute( "user_name",rs.getString(2));
session.setMaxInactiveInterval(3000);
response.sendRedirect("homepage.jsp");
}
%>
<%}
catch(Exception e)
{
out.println(e);
}
%>
</body>
I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.
To install a debug (test) apk, use -t
:
Run Build-Make Project
Look for the last generated apk in the app folder.
Example:
adb install -t C:\code\BackupRestore\app\build\outputs\apk\debug\app-debug.apk
Or shorter:
$("form#data").submit(function() {
var formData = new FormData(this);
$.post($(this).attr("action"), formData, function() {
// success
});
return false;
});
If you could use something other than 'awk' , then try this instead
echo '1540 "A B"' | cut -d' ' -f2-
-d is a delimiter, -f is the field to cut and with -f2- we intend to cut the 2nd field until end.
I use strace all the time to debug permission issues. The technique goes like this:
$ strace -e trace=open,stat,read,write gnome-calculator
Where gnome-calculator
is the command that you want to run.
Download the server response as an array buffer. Store it as a Blob using the content type from the server (which should be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
):
var httpPromise = this.$http.post(server, postData, { responseType: 'arraybuffer' });
httpPromise.then(response => this.save(new Blob([response.data],
{ type: response.headers('Content-Type') }), fileName));
Save the blob to the user's device:
save(blob, fileName) {
if (window.navigator.msSaveOrOpenBlob) { // For IE:
navigator.msSaveBlob(blob, fileName);
} else { // For other browsers:
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
window.URL.revokeObjectURL(link.href);
}
}
First of all, I don't really see why you would want an object having only ID and Version, and all other props to be nulls. However, here is some code which will do that for you (which doesn't use JPA Em, but normal Hibernate. I assume you can find the equivalence in JPA or simply obtain the Hibernate Session obj from the em delegate Accessing Hibernate Session from EJB using EntityManager ):
List<T> results = session.createCriteria(entityClazz)
.setProjection( Projections.projectionList()
.add( Property.forName("ID") )
.add( Property.forName("VERSION") )
)
.setResultTransformer(Transformers.aliasToBean(entityClazz);
.list();
This will return a list of Objects having their ID and Version set and all other props to null, as the aliasToBean transformer won't be able to find them. Again, I am uncertain I can think of a situation where I would want to do that.
One time when an FK might cause you a problem is when you have historical data that references the key (in a lookup table) even though you no longer want the key available.
Obviously the solution is to design things better up front, but I am thinking of real world situations here where you don't always have control of the full solution.
For example: perhaps you have a look up table customer_type
that lists different types of customers - lets say you need to remove a certain customer type, but (due to business restraints) aren't able to update the client software, and nobody invisaged this situation when developing the software, the fact that it is a foreign key in some other table may prevent you from removing the row even though you know the historical data that references it is irrelevant.
After being burnt with this a few times you probably lean away from db enforcement of relationships.
(I'm not saying this is good - just giving a reason why you may decide to avoid FKs and db contraints in general)
use:
std::vector <Acard> playerHand;
everywhere qualify it by std::
or do:
using std::vector;
in your cpp file.
You have to do this because vector
is defined in the std
namespace and you do not tell your program to find it in std
namespace, you need to tell that.
If you are generating a heap of commands to be run, then call that script from a terminal, you can try the following.
sftp login@host < /path/to/command/list
You will then be asked to enter your password (as per normal) however all the commands in the script run after that.
This is clearly not a completely automated option that can be used in a cron
job, but it can be used from a terminal.
Further to @T.J. Crowder 's answer, I've added a recursive outer loop that allows one to iterate through all the scripts in an array and then execute a function once all the scripts are loaded:
loadList([array of scripts], 0, function(){// do your post-scriptload stuff})
function loadList(list, i, callback)
{
{
loadScript(list[i], function()
{
if(i < list.length-1)
{
loadList(list, i+1, callback);
}
else
{
callback();
}
})
}
}
Of course you can make a wrapper to get rid of the '0' if you like:
function prettyLoadList(list, callback)
{
loadList(list, 0, callback);
}
Nice work @T.J. Crowder - I was cringing at the 'just add a couple seconds delay before running the callback' I saw in other threads.
Just git branch
without options.
From the manpage:
With no arguments, existing branches are listed and the current branch will be highlighted with an asterisk.
Solomon's answer about bootstrap inspired me to add the CSS the bootstrap solution uses, which works really well for me.
.iframe-embed {
position: absolute;
top: 0;
left: 0;
bottom: 0;
height: 100%;
width: 100%;
border: 0;
}
.iframe-embed-wrapper {
position: relative;
display: block;
height: 0;
padding: 0;
overflow: hidden;
}
.iframe-embed-responsive-16by9 {
padding-bottom: 56.25%;
}
<div class="iframe-embed-wrapper iframe-embed-responsive-16by9">
<iframe class="iframe-embed" src="vid.mp4"></iframe>
</div>
If you can use a tool like "dapper", this can be simply:
int[] ages = { 20, 21, 22 }; // could be any common list-like type
var rows = connection.Query<YourType>("SELECT * from TableA WHERE Age IN @ages",
new { ages }).ToList();
Dapper will handle unwrapping this to individual parameters for you.
After much research and testing, I have developed a solution for an app I'm currently converting from Android/iOS to Flutter.
With Android and iOS I used a 'Scaling Factor' applied to base font sizes, rendering text sizes that were relative to the screen size.
This article was very helpful: https://medium.com/flutter-community/flutter-effectively-scale-ui-according-to-different-screen-sizes-2cb7c115ea0a
I created a StatelessWidget to get the font sizes of the Material Design typographical styles. Getting device dimensions using MediaQuery, calculating a scaling factor, then resetting the Material Design text sizes. The Widget can be used to define a custom Material Design Theme.
Emulators used:
set_app_theme.dart (SetAppTheme Widget)
import 'package:flutter/material.dart';
import 'dart:math';
class SetAppTheme extends StatelessWidget {
final Widget child;
SetAppTheme({this.child});
@override
Widget build(BuildContext context) {
final _divisor = 400.0;
final MediaQueryData _mediaQueryData = MediaQuery.of(context);
final _screenWidth = _mediaQueryData.size.width;
final _factorHorizontal = _screenWidth / _divisor;
final _screenHeight = _mediaQueryData.size.height;
final _factorVertical = _screenHeight / _divisor;
final _textScalingFactor = min(_factorVertical, _factorHorizontal);
final _safeAreaHorizontal = _mediaQueryData.padding.left + _mediaQueryData.padding.right;
final _safeFactorHorizontal = (_screenWidth - _safeAreaHorizontal) / _divisor;
final _safeAreaVertical = _mediaQueryData.padding.top + _mediaQueryData.padding.bottom;
final _safeFactorVertical = (_screenHeight - _safeAreaVertical) / _divisor;
final _safeAreaTextScalingFactor = min(_safeFactorHorizontal, _safeFactorHorizontal);
print('Screen Scaling Values:' + '_screenWidth: $_screenWidth');
print('Screen Scaling Values:' + '_factorHorizontal: $_factorHorizontal ');
print('Screen Scaling Values:' + '_screenHeight: $_screenHeight');
print('Screen Scaling Values:' + '_factorVertical: $_factorVertical ');
print('_textScalingFactor: $_textScalingFactor ');
print('Screen Scaling Values:' + '_safeAreaHorizontal: $_safeAreaHorizontal ');
print('Screen Scaling Values:' + '_safeFactorHorizontal: $_safeFactorHorizontal ');
print('Screen Scaling Values:' + '_safeAreaVertical: $_safeAreaVertical ');
print('Screen Scaling Values:' + '_safeFactorVertical: $_safeFactorVertical ');
print('_safeAreaTextScalingFactor: $_safeAreaTextScalingFactor ');
print('Default Material Design Text Themes');
print('display4: ${Theme.of(context).textTheme.display4}');
print('display3: ${Theme.of(context).textTheme.display3}');
print('display2: ${Theme.of(context).textTheme.display2}');
print('display1: ${Theme.of(context).textTheme.display1}');
print('headline: ${Theme.of(context).textTheme.headline}');
print('title: ${Theme.of(context).textTheme.title}');
print('subtitle: ${Theme.of(context).textTheme.subtitle}');
print('body2: ${Theme.of(context).textTheme.body2}');
print('body1: ${Theme.of(context).textTheme.body1}');
print('caption: ${Theme.of(context).textTheme.caption}');
print('button: ${Theme.of(context).textTheme.button}');
TextScalingFactors _textScalingFactors = TextScalingFactors(
display4ScaledSize: (Theme.of(context).textTheme.display4.fontSize * _safeAreaTextScalingFactor),
display3ScaledSize: (Theme.of(context).textTheme.display3.fontSize * _safeAreaTextScalingFactor),
display2ScaledSize: (Theme.of(context).textTheme.display2.fontSize * _safeAreaTextScalingFactor),
display1ScaledSize: (Theme.of(context).textTheme.display1.fontSize * _safeAreaTextScalingFactor),
headlineScaledSize: (Theme.of(context).textTheme.headline.fontSize * _safeAreaTextScalingFactor),
titleScaledSize: (Theme.of(context).textTheme.title.fontSize * _safeAreaTextScalingFactor),
subtitleScaledSize: (Theme.of(context).textTheme.subtitle.fontSize * _safeAreaTextScalingFactor),
body2ScaledSize: (Theme.of(context).textTheme.body2.fontSize * _safeAreaTextScalingFactor),
body1ScaledSize: (Theme.of(context).textTheme.body1.fontSize * _safeAreaTextScalingFactor),
captionScaledSize: (Theme.of(context).textTheme.caption.fontSize * _safeAreaTextScalingFactor),
buttonScaledSize: (Theme.of(context).textTheme.button.fontSize * _safeAreaTextScalingFactor));
return Theme(
child: child,
data: _buildAppTheme(_textScalingFactors),
);
}
}
final ThemeData customTheme = ThemeData(
primarySwatch: appColorSwatch,
// fontFamily: x,
);
final MaterialColor appColorSwatch = MaterialColor(0xFF3787AD, appSwatchColors);
Map<int, Color> appSwatchColors =
{
50 : Color(0xFFE3F5F8),
100 : Color(0xFFB8E4ED),
200 : Color(0xFF8DD3E3),
300 : Color(0xFF6BC1D8),
400 : Color(0xFF56B4D2),
500 : Color(0xFF48A8CD),
600 : Color(0xFF419ABF),
700 : Color(0xFF3787AD),
800 : Color(0xFF337799),
900 : Color(0xFF285877),
};
_buildAppTheme (TextScalingFactors textScalingFactors) {
return customTheme.copyWith(
accentColor: appColorSwatch[300],
buttonTheme: customTheme.buttonTheme.copyWith(buttonColor: Colors.grey[500],),
cardColor: Colors.white,
errorColor: Colors.red,
inputDecorationTheme: InputDecorationTheme(border: OutlineInputBorder(),),
primaryColor: appColorSwatch[700],
primaryIconTheme: customTheme.iconTheme.copyWith(color: appColorSwatch),
scaffoldBackgroundColor: Colors.grey[100],
textSelectionColor: appColorSwatch[300],
textTheme: _buildAppTextTheme(customTheme.textTheme, textScalingFactors),
appBarTheme: customTheme.appBarTheme.copyWith(
textTheme: _buildAppTextTheme(customTheme.textTheme, textScalingFactors)),
// accentColorBrightness: ,
// accentIconTheme: ,
// accentTextTheme: ,
// appBarTheme: ,
// applyElevationOverlayColor: ,
// backgroundColor: ,
// bannerTheme: ,
// bottomAppBarColor: ,
// bottomAppBarTheme: ,
// bottomSheetTheme: ,
// brightness: ,
// buttonBarTheme: ,
// buttonColor: ,
// canvasColor: ,
// cardTheme: ,
// chipTheme: ,
// colorScheme: ,
// cupertinoOverrideTheme: ,
// cursorColor: ,
// dialogBackgroundColor: ,
// dialogTheme: ,
// disabledColor: ,
// dividerColor: ,
// dividerTheme: ,
// floatingActionButtonTheme: ,
// focusColor: ,
// highlightColor: ,
// hintColor: ,
// hoverColor: ,
// iconTheme: ,
// indicatorColor: ,
// materialTapTargetSize: ,
// pageTransitionsTheme: ,
// platform: ,
// popupMenuTheme: ,
// primaryColorBrightness: ,
// primaryColorDark: ,
// primaryColorLight: ,
// primaryTextTheme: ,
// secondaryHeaderColor: ,
// selectedRowColor: ,
// sliderTheme: ,
// snackBarTheme: ,
// splashColor: ,
// splashFactory: ,
// tabBarTheme: ,
// textSelectionHandleColor: ,
// toggleableActiveColor: ,
// toggleButtonsTheme: ,
// tooltipTheme: ,
// typography: ,
// unselectedWidgetColor: ,
);
}
class TextScalingFactors {
final double display4ScaledSize;
final double display3ScaledSize;
final double display2ScaledSize;
final double display1ScaledSize;
final double headlineScaledSize;
final double titleScaledSize;
final double subtitleScaledSize;
final double body2ScaledSize;
final double body1ScaledSize;
final double captionScaledSize;
final double buttonScaledSize;
TextScalingFactors({
@required this.display4ScaledSize,
@required this.display3ScaledSize,
@required this.display2ScaledSize,
@required this.display1ScaledSize,
@required this.headlineScaledSize,
@required this.titleScaledSize,
@required this.subtitleScaledSize,
@required this.body2ScaledSize,
@required this.body1ScaledSize,
@required this.captionScaledSize,
@required this.buttonScaledSize
});
}
TextTheme _buildAppTextTheme(
TextTheme _customTextTheme,
TextScalingFactors _scaledText) {
return _customTextTheme.copyWith(
display4: _customTextTheme.display4.copyWith(fontSize: _scaledText.display4ScaledSize),
display3: _customTextTheme.display3.copyWith(fontSize: _scaledText.display3ScaledSize),
display2: _customTextTheme.display2.copyWith(fontSize: _scaledText.display2ScaledSize),
display1: _customTextTheme.display1.copyWith(fontSize: _scaledText.display1ScaledSize),
headline: _customTextTheme.headline.copyWith(fontSize: _scaledText.headlineScaledSize),
title: _customTextTheme.title.copyWith(fontSize: _scaledText.titleScaledSize),
subtitle: _customTextTheme.subtitle.copyWith(fontSize: _scaledText.subtitleScaledSize),
body2: _customTextTheme.body2.copyWith(fontSize: _scaledText.body2ScaledSize),
body1: _customTextTheme.body1.copyWith(fontSize: _scaledText.body1ScaledSize),
caption: _customTextTheme.caption.copyWith(fontSize: _scaledText.captionScaledSize),
button: _customTextTheme.button.copyWith(fontSize: _scaledText.buttonScaledSize),
).apply(bodyColor: Colors.black);
}
main.dart (Demo App)
import 'package:flutter/material.dart';
import 'package:scaling/set_app_theme.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: SetAppTheme(child: HomePage()),
);
}
}
class HomePage extends StatelessWidget {
final demoText = '0123456789';
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text('Text Scaling with SetAppTheme',
style: TextStyle(color: Colors.white),),
),
body: SingleChildScrollView(
child: Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: <Widget>[
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.display4.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.display3.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.display2.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.display1.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.headline.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.title.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.subtitle.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.body2.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.body1.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.caption.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.button.fontSize,
),
),
],
),
),
),
),
),
);
}
}
Either create an auto-increment id or a UNIQUE id and add it to the natural key you are talking about with the 4 fields. this will make every row in the table unique...
It has already been answered, the best way work-around is to convert the Stored Procedure into an SQL Function or a View.
The short answer, just as mentioned above, is that you cannot directly JOIN a Stored Procedure in SQL, not unless you create another stored procedure or function using the stored procedure's output into a temporary table and JOINing the temporary table, as explained above.
I will answer this by converting your Stored Procedure into an SQL function and show you how to use it inside a query of your choice.
CREATE FUNCTION fnMyFunc()
RETURNS TABLE AS
RETURN
(
SELECT tenant.ID AS TenantID,
SUM(ISNULL(trans.Amount,0)) AS TenantBalance
FROM tblTenant tenant
LEFT JOIN tblTransaction trans ON tenant.ID = trans.TenantID
GROUP BY tenant.ID
)
Now to use that function, in your SQL...
SELECT t.TenantName,
t.CarPlateNumber,
t.CarColor,
t.Sex,
t.SSNO,
t.Phone,
t.Memo,
u.UnitNumber,
p.PropertyName
FROM tblTenant t
LEFT JOIN tblRentalUnit u ON t.UnitID = u.ID
LEFT JOIN tblProperty p ON u.PropertyID = p.ID
LEFT JOIN dbo.fnMyFunc() AS a
ON a.TenantID = t.TenantID
ORDER BY p.PropertyName, t.CarPlateNumber
If you wish to pass parameters into your function from within the above SQL, then I recommend you use CROSS APPLY
or CROSS OUTER APPLY
.
Read up on that here.
Cheers
Another option is:
filter1 = df.index.get_level_values('A') == 1
filter2 = df.index.get_level_values('B') == 4
df.iloc[filter1 & filter2]
Out[11]:
0
A B
1 4 1
I had exactly the same problem. Just one more working modification of the solution given by Denis (the type must be specified):
SELECT ARRAY(
SELECT column_name::text
FROM information_schema.columns
WHERE table_name='aean'
)
Using docker compose you can mount a volume with postgresql.auto.conf
.
Example:
version: '2'
services:
db:
image: postgres:10.9-alpine
volumes:
- postgres:/var/lib/postgresql/data:z
- ./docker/postgres/postgresql.auto.conf:/var/lib/postgresql/data/postgresql.auto.conf
ports:
- 5432:5432
I'm surprised that this question has been around as long as it has, and nobody has provided the pre-mapfile built-in approach yet.
IFS= read -r first_line <file
...puts the first line of the file in the variable expanded by "$first_line"
, easy as that.
Moreover, because read
is built into bash and this usage requires no subshell, it's significantly more efficient than approaches involving subprocesses such as head
or awk
.
You can do that with
find . -mtime 0
From man find
:
[The] time since each file was last modified is divided by 24 hours and any remainder is discarded. That means that to match -mtime 0, a file will have to have a modification in the past which is less than 24 hours ago.
My solution is to add this code to the app.php
define('WEB_DIRECTORY', __DIR__);
The problem is that in command line code that uses the constant will break. You can also add the constant to app/console file and the other environment front controllers
Another solution may be add an static method at AppKernel that returns DIR.'/../web/' So you can access everywhere
You want a .jardesc
file. They do not kick off automatically, but it's within 2 clicks.
Export > Java > JAR file
Next
.jardesc
fileNow, all you have to do is right click on your .jardesc
file and choose Create JAR
and it will export it in the same spot.
This is an issue with the jdbc Driver version. I had this issue when I was using mysql-connector-java-commercial-5.0.3-bin.jar but when I changed to a later driver version mysql-connector-java-5.1.22.jar, the issue was fixed.
You can try the new for of loop:
const apple = {
color: 'red',
size: 'medium',
weight: 12,
sugar: 10
}
for (const prop of apple.entries()){
console.log(prop);
}
Here's a few examples:
The reason for the using
statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens.
As in Understanding the 'using' statement in C# (codeproject) and Using objects that implement IDisposable (microsoft), the C# compiler converts
using (MyResource myRes = new MyResource())
{
myRes.DoSomething();
}
to
{ // Limits scope of myRes
MyResource myRes= new MyResource();
try
{
myRes.DoSomething();
}
finally
{
// Check for a null resource.
if (myRes != null)
// Call the object's Dispose method.
((IDisposable)myRes).Dispose();
}
}
C# 8 introduces a new syntax, named "using declarations":
A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.
So the equivalent code of above would be:
using var myRes = new MyResource();
myRes.DoSomething();
And when control leaves the containing scope (usually a method, but it can also be a code block), myRes
will be disposed.
In my case the problem was that https was unable to start correctly because Listen 443 was in "IfDefine SSL" derective, but my apache didnt start with -DSSL option. The fix was to change my apachectl script in:
$HTTPD -k $ARGV
to:
$HTTPD -k $ARGV -DSSL
Hope that helps somebody.
No curly braces required you can directly write
@if($user->status =='waiting')
<td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{{ $user->travel_id }}" data-toggle="modal" data-target="#myModal">Approve/Reject<a></td>
@else
<td>{{ $user->status }}</td>
@endif
For Jpa based application: base package scan
@EnableJpaRepositories(basePackages = "repository")
You can try it once!!!
Project Structure
com
+- stack
+- app
| +- Application.java
+- controller
| +- EmployeeController.java
+- service
| +- EmployeeService.java
+- repository
| +- EmployeeRepository.java
+- model
| +- Employee.java
-pom.xml
dependencies:
mysql, lombok, data-jpa
application.properties
#Data source :
spring.datasource.url=jdbc:mysql://localhost:3306/employee?useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.generate-ddl=true
spring.datasource.driverClassName=com.mysql.jdbc.Driver
#Jpa/Hibernate :
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto = update
Employee.java
@Entity
@Table (name = "employee")
@Getter
@Setter
public class Employee {
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
private Long id;
@Column (name = "first_name")
private String firstName;
@Column (name = "last_name")
private String lastName;
@Column (name = "email")
private String email;
@Column (name = "phone_number")
private String phoneNumber;
@Column (name = "emp_desg")
private String desgination;
}
EmployeeRepository.java
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
EmployeeController.java
@RestController
public class EmployeeController {
@Autowired
private EmployeeService empService;
@GetMapping (value = "/employees")
public List<Employee> getAllEmployee(){
return empService.getAllEmployees();
}
@PostMapping (value = "/employee")
public ResponseEntity<Employee> addEmp(@RequestBody Employee emp, HttpServletRequest
request) throws URISyntaxException {
HttpHeaders headers = new HttpHeaders();
headers.setLocation(new URI(request.getRequestURI() + "/" + emp.getId()));
empService.saveEmployee(emp);
return new ResponseEntity<Employee>(emp, headers, HttpStatus.CREATED);
}
EmployeeService.java
public interface EmployeeService {
public List<Employee> getAllEmployees();
public Employee saveEmployee(Employee emp);
}
EmployeeServiceImpl.java
@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeRepository empRepository;
@Override
public List<Employee> getAllEmployees() {
return empRepository.findAll();
}
@Override
public Employee saveEmployee(Employee emp) {
return empRepository.save(emp);
}
}
EmployeeApplication.java
@SpringBootApplication
@EnableJpaRepositories(basePackages = "repository")
public class EmployeeApplication {
public static void main(String[] args) {
SpringApplication.run(EmployeeApplication.class, args);
}
}
Although the top answers are correct, I personally like to work with attached properties to enable the solution to be applied to any UIElement
, especially when the Window
is not aware of the element that should be focused. In my experience I often see a composition of several view models and user controls, where the window is often nothing more that the root container.
public sealed class AttachedProperties
{
// Define the key gesture type converter
[System.ComponentModel.TypeConverter(typeof(System.Windows.Input.KeyGestureConverter))]
public static KeyGesture GetFocusShortcut(DependencyObject dependencyObject)
{
return (KeyGesture)dependencyObject?.GetValue(FocusShortcutProperty);
}
public static void SetFocusShortcut(DependencyObject dependencyObject, KeyGesture value)
{
dependencyObject?.SetValue(FocusShortcutProperty, value);
}
/// <summary>
/// Enables window-wide focus shortcut for an <see cref="UIElement"/>.
/// </summary>
// Using a DependencyProperty as the backing store for FocusShortcut. This enables animation, styling, binding, etc...
public static readonly DependencyProperty FocusShortcutProperty =
DependencyProperty.RegisterAttached("FocusShortcut", typeof(KeyGesture), typeof(AttachedProperties), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.None, new PropertyChangedCallback(OnFocusShortcutChanged)));
private static void OnFocusShortcutChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is UIElement element) || e.NewValue == e.OldValue)
return;
var window = FindParentWindow(d);
if (window == null)
return;
var gesture = GetFocusShortcut(d);
if (gesture == null)
{
// Remove previous added input binding.
for (int i = 0; i < window.InputBindings.Count; i++)
{
if (window.InputBindings[i].Gesture == e.OldValue && window.InputBindings[i].Command is FocusElementCommand)
window.InputBindings.RemoveAt(i--);
}
}
else
{
// Add new input binding with the dedicated FocusElementCommand.
// see: https://gist.github.com/shuebner20/349d044ed5236a7f2568cb17f3ed713d
var command = new FocusElementCommand(element);
window.InputBindings.Add(new InputBinding(command, gesture));
}
}
}
With this attached property you can define a focus shortcut for any UIElement. It will automatically register the input binding at the window containing the element.
<TextBox x:Name="SearchTextBox"
Text={Binding Path=SearchText}
local:AttachedProperties.FocusShortcutKey="Ctrl+Q"/>
The full sample including the FocusElementCommand implementation is available as gist: https://gist.github.com/shuebner20/c6a5191be23da549d5004ee56bcc352d
Disclaimer: You may use this code everywhere and free of charge. Please keep in mind, that this is a sample that is not suitable for heavy usage. For example, there is no garbage collection of removed elements because the Command will hold a strong reference to the element.
A very simple, non-technical rule-of-thumb would be that clustered indexes are usually used for your primary key (or, at least, a unique column) and that non-clustered are used for other situations (maybe a foreign key). Indeed, SQL Server will by default create a clustered index on your primary key column(s). As you will have learnt, the clustered index relates to the way data is physically sorted on disk, which means it's a good all-round choice for most situations.
It seems you have changed some permissions of the directory. I did the following steps to restore it.
$ git diff > backup-diff.txt ### in case you have some other code changes
$ git checkout .
IMHO, the 'cleanest' way to select the First, visible, enabled text field on the page, is to use jQuery and do something like this:
$(document).ready(function() {
$('input:text[value=""]:visible:enabled:first').focus();
});
Hope that helps...
Thanks...
I find this type of approach works for me:
Product ProductDetail Country ========= ================== ========= ProductId ProductDetailId CountryId - etc - ProductId CountryName CountryId Language ProductName - etc - ProductDescription - etc -
The ProductDetail table holds all the translations (for product name, description etc..) in the languages you want to support. Depending on your app's requirements, you may wish to break the Country table down to use regional languages too.
Uncheck the "copy projects into workspace" checkbox, and then click "refresh" button, you will be able to import the project
Really, the best practice is to step back and ask whether you really need to do this. Why do you want to modify the value of a variable that you're passing in to the function?
If you need to do it for a quick hack, the quickest way is to pass a list
holding the integer, and stick a [0]
around every use of it, as mgilson's answer demonstrates.
If you need to do it for something more significant, write a class
that has an int
as an attribute, so you can just set it. Of course this forces you to come up with a good name for the class, and for the attribute—if you can't think of anything, go back and read the sentence again a few times, and then use the list
.
More generally, if you're trying to port some Java idiom directly to Python, you're doing it wrong. Even when there is something directly corresponding (as with static
/@staticmethod
), you still don't want to use it in most Python programs just because you'd use it in Java.
Here are the steps
See following code:
public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString Replace2(SqlString inputtext, SqlString filter,SqlString replacewith)
{
string str = inputtext.ToString();
try
{
string pattern = (string)filter;
string replacement = (string)replacewith;
Regex rgx = new Regex(pattern);
string result = rgx.Replace(str, replacement);
return (SqlString)result;
}
catch (Exception s)
{
return (SqlString)s.Message;
}
}
}
Deploy your CLR function
Now Test it
See following code:
create table dbo.test(dummydata varchar(255))
Go
INSERT INTO dbo.test values('P@ssw1rd'),('This 12is @test')
Go
Update dbo.test
set dummydata=dbo.Replace2(dummydata,'[0-9@]','')
select * from dbo.test
dummydata, Psswrd, This is test booom!!!!!!!!!!!!!
I normally use the fontawesome font(http://fontawesome.io/icon/check/), you can use it in html files:
<i class="fa fa-check"></i>
or in css:
content: "\f00c";
font-family: FontAwesome;
Depending on the type of your variable, one of abs(int)
, labs(long)
, llabs(long long)
, imaxabs(intmax_t)
, fabsf(float)
, fabs(double)
, or fabsl(long double)
.
Those functions are all part of the C standard library, and so are present both in Objective-C and plain C (and are generally available in C++ programs too.)
(Alas, there is no habs(short)
function. Or scabs(signed char)
for that matter...)
Apple's and GNU's Objective-C headers also include an ABS()
macro which is type-agnostic. I don't recommend using ABS()
however as it is not guaranteed to be side-effect-safe. For instance, ABS(a++)
will have an undefined result.
If you're using C++ or Objective-C++, you can bring in the <cmath>
header and use std::abs()
, which is templated for all the standard integer and floating-point types.
By default the underlying type of each element in the enum is integer.
enum Values
{
A,
B,
C
}
You can also specify custom value for each item:
enum Values
{
A = 10,
B = 11,
C = 12
}
int x = (int)Values.A; // x will be 10;
Note: By default, the first enumerator has the value 0.
I'm surprised that no one mentioned Cutter (http://cutter.sourceforge.net/) You can test C and C++, it seamlessly integrates with autotools and has a really nice tutorial available.
If you have Pillow
installed with scipy
and it is still giving you error then check your scipy
version because it has been removed from scipy since 1.3.0rc1
.
rather install scipy 1.1.0
by :
pip install scipy==1.1.0
check https://github.com/scipy/scipy/issues/6212
The method imread
in scipy.misc
requires the forked package of PIL
named Pillow
. If you are having problem installing the right version of PIL try using imread
in other packages:
from matplotlib.pyplot import imread
im = imread(image.png)
To read jpg
images without PIL
use:
import cv2 as cv
im = cv.imread(image.jpg)
You can try
from scipy.misc.pilutil import imread
instead of from scipy.misc import imread
Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.