In my case, the Hibernate was looking for columns in a snake case, like create_date
, while the columns in the DB were in the camel case, e.g., createDate
.
Adding
spring:
jpa:
hibernate:
naming: # must tell spring/jpa/hibernate to use the column names as specified, not snake case
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
to the application.yml
helped fix the problem.
select u_name as user_name from users where u_name = "john";
Think of it like this, your where clause evaluates first, to determine which rows (or joined rows) need to be returned. Once the where clause is executed, the select clause runs for it.
To put it a better way, imagine this:
select distinct(u_name) as user_name from users where u_name = "john";
You can't reference the first half without the second. Where always gets evaluated first, then the select clause.
You can use HAVING clause for filter calculated in SELECT fields and aliases
I had this error aswell.
I am working in mysql workbench. When giving the values they have to be inside "". That solved it for me.
(I have too low reputation to comment, but this is comment on JoshCaba's entry, using the Ace-engine instead of Jet for Excel 2007)
If you don't have Ace installed/registered on your machine, you can get it at: https://www.microsoft.com/en-US/download/details.aspx?id=13255
It applies for Excel 2010 as well.
Recommended, without jQuery:
Give your <input>
an ID and refer to that. Also, remove the checked=""
part of the <input>
tag if you want the checkbox to start out unticked. Then it's:
document.getElementById("my-checkbox").checked = true;
Pure JavaScript, with no Element ID (#1):
var inputs = document.getElementsByTagName('input');
for(var i = 0; i<inputs.length; i++){
if(typeof inputs[i].getAttribute === 'function' && inputs[i].getAttribute('name') === 'copyNewAddrToBilling'){
inputs[i].checked = true;
break;
}
}
Pure Javascript, with no Element ID (#2):
document.querySelectorAll('.text input[name="copyNewAddrToBilling"]')[0].checked = true;
document.querySelector('.text input[name="copyNewAddrToBilling"]').checked = true;
Note that the querySelectorAll
and querySelector
methods are supported in these browsers: IE8+, Chrome 4+, Safari 3.1+, Firefox 3.5+ and all mobile browsers.
If the element may be missing, you should test for its existence, e.g.:
var input = document.querySelector('.text input[name="copyNewAddrToBilling"]');
if (!input) { return; }
With jQuery:
$('.text input[name="copyNewAddrToBilling"]').prop('checked', true);
Yowsup provide best solution with example.you can download api from https://github.com/tgalal/yowsup let me know if you have any issue.
In python you can use json.Dump(str) before send result to html template. with this command string convert to correct json format and send to html template. After send this result to JSON.parse(result) , this is correct response and you can use this.
The List<>
class does guarantee ordering - things will be retained in the list in the order you add them, including duplicates, unless you explicitly sort the list.
According to MSDN:
...List "Represents a strongly typed list of objects that can be accessed by index."
The index values must remain reliable for this to be accurate. Therefore the order is guaranteed.
You might be getting odd results from your code if you're moving the item later in the list, as your Remove()
will move all of the other items down one place before the call to Insert()
.
Can you boil your code down to something small enough to post?
Here's another one in case you don't want to use Collectors.toMap()
Map<String, Choice> result =
choices.stream().collect(HashMap<String, Choice>::new,
(m, c) -> m.put(c.getName(), c),
(m, u) -> {});
try something like
public static Document loadXML(String xml) throws Exception
{
DocumentBuilderFactory fctr = DocumentBuilderFactory.newInstance();
DocumentBuilder bldr = fctr.newDocumentBuilder();
InputSource insrc = new InputSource(new StringReader(xml));
return bldr.parse(insrc);
}
You should look at RAND_MAX
for your particular compiler/environment.
I think you would see these results if rand()
is producing a random 16-bit number. (you seem to be assuming it will be a 32-bit number).
I can't promise this is the answer, but please post your value of RAND_MAX
, and a little more detail on your environment.
In my case, there were two slightly different dependences (version 2.1 vs 2.0) in two maven sub-modules. After I switched to a single version the error has gone in IDEA 14. (Refresh and .m2 swipe didn't help.)
One simple way to validate a date string is to convert to a date object and test that, e.g.
// Expect input as d/m/y_x000D_
function isValidDate(s) {_x000D_
var bits = s.split('/');_x000D_
var d = new Date(bits[2], bits[1] - 1, bits[0]);_x000D_
return d && (d.getMonth() + 1) == bits[1];_x000D_
}_x000D_
_x000D_
['0/10/2017','29/2/2016','01/02'].forEach(function(s) {_x000D_
console.log(s + ' : ' + isValidDate(s))_x000D_
})
_x000D_
When testing a Date this way, only the month needs to be tested since if the date is out of range, the month will change. Same if the month is out of range. Any year is valid.
You can also test the bits of the date string:
function isValidDate2(s) {_x000D_
var bits = s.split('/');_x000D_
var y = bits[2],_x000D_
m = bits[1],_x000D_
d = bits[0];_x000D_
// Assume not leap year by default (note zero index for Jan)_x000D_
var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];_x000D_
_x000D_
// If evenly divisible by 4 and not evenly divisible by 100,_x000D_
// or is evenly divisible by 400, then a leap year_x000D_
if ((!(y % 4) && y % 100) || !(y % 400)) {_x000D_
daysInMonth[1] = 29;_x000D_
}_x000D_
return !(/\D/.test(String(d))) && d > 0 && d <= daysInMonth[--m]_x000D_
}_x000D_
_x000D_
['0/10/2017','29/2/2016','01/02'].forEach(function(s) {_x000D_
console.log(s + ' : ' + isValidDate2(s))_x000D_
})
_x000D_
You probably need to wrap the UNION
in a sub-SELECT
and apply the WHERE
clause afterward:
SELECT * FROM (
SELECT * FROM Table1 WHERE Field1 = Value1
UNION
SELECT * FROM Table2 WHERE Field1 = Value2
) AS t WHERE Field2 = Value3
Basically, the UNION
is looking for two complete SELECT
statements to combine, and the WHERE
clause is part of the SELECT
statement.
It may make more sense to apply the outer WHERE
clause to both of the inner queries. You'll probably want to benchmark the performance of both approaches and see which works better for you.
I can't see any native .NET way to do it but if you want to get your hands dirty with the underlying Win32 controls...
You should be able to send it the CB_GETCOMBOBOXINFO
message with a COMBOBOXINFO
structure which will contain the internal edit control's handle.
You can then send the edit control the EM_SETCUEBANNER
message with a pointer to the string.
(Note that this requires at least XP and visual styles to be enabled.
Reply to MVC4 DataType.Date EditorFor won't display date value in Chrome, fine in IE
In the Model you need to have following type of declaration:
[DataType(DataType.Date)]
public DateTime? DateXYZ { get; set; }
OR
[DataType(DataType.Date)]
public Nullable<System.DateTime> DateXYZ { get; set; }
You don't need to use following attribute:
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
At the Date.cshtml use this template:
@model Nullable<DateTime>
@using System.Globalization;
@{
DateTime dt = DateTime.Now;
if (Model != null)
{
dt = (System.DateTime)Model;
}
if (Request.Browser.Type.ToUpper().Contains("IE") || Request.Browser.Type.Contains("InternetExplorer"))
{
@Html.TextBox("", String.Format("{0:d}", dt.ToShortDateString()), new { @class = "datefield", type = "date" })
}
else
{
//Tested in chrome
DateTimeFormatInfo dtfi = CultureInfo.CreateSpecificCulture("en-US").DateTimeFormat;
dtfi.DateSeparator = "-";
dtfi.ShortDatePattern = @"yyyy/MM/dd";
@Html.TextBox("", String.Format("{0:d}", dt.ToString("d", dtfi)), new { @class = "datefield", type = "date" })
}
}
Have fun! Regards, Blerton
Just for posterity, here's the text from several external sources regarding the Excel file formats. Some of these have been mentioned in other answers to this question but without reproducing the essential content.
1. From Doug Mahugh, August 22, 2006:
...the new XLSB binary format. Like Open XML, it’s a full-fidelity file format that can store anything you can create in Excel, but the XLSB format is optimized for performance in ways that aren’t possible with a pure XML format.
The XLSB format (also sometimes referred to as BIFF12, as in “binary file format for Office 12”) uses the same Open Packaging Convention used by the Open XML formats and XPS. So it’s basically a ZIP container, and you can open it with any ZIP tool to see what’s inside. But instead of .XML parts within the package, you’ll find .BIN parts...
This article also refers to documentation about the BIN format, too lengthy to reproduce here.
2. From MSDN Archive, August 29, 2006 which in turn cites an already-missing blog post regarding the XLSB format:
Even though we’ve done a lot of work to make sure that our XML formats open quickly and efficiently, this binary format is still more efficient for Excel to open and save, and can lead to some performance improvements for workbooks that contain a lot of data, or that would require a lot of XML parsing during the Open process. (In fact, we’ve found that the new binary format is faster than the old XLS format in many cases.) Also, there is no macro-free version of this file format – all XLSB files can contain macros (VBA and XLM). In all other respects, it is functionally equivalent to the XML file format above:
File size – file size of both formats is approximately the same, since both formats are saved to disk using zip compression Architecture – both formats use the same packaging structure, and both have the same part-level structures. Feature support – both formats support exactly the same feature set Runtime performance – once loaded into memory, the file format has no effect on application/calculation speed Converters – both formats will have identical converter support
If you want to show time on textview then better use Chronometer or TextClock
Using Chronometer:This was added in API 1. It has lot of option to customize it.
Your xml
<Chronometer
android:id="@+id/chronometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp" />
Your activity
Chronometer mChronometer=(Chronometer) findViewById(R.id.chronometer);
mChronometer.setBase(SystemClock.elapsedRealtime());
mChronometer.start();
Using TextClock: This widget is introduced in API level 17. I personally like Chronometer.
Your xml
<TextClock
android:id="@+id/textClock"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:format12Hour="hh:mm:ss a"
android:gravity="center_horizontal"
android:textColor="#d41709"
android:textSize="44sp"
android:textStyle="bold" />
Thats it, you are done.
You can use any of these two widgets. This will make your life easy.
We have similar situation right now and as of this answer, I am using laravel 5.6 release.
I will not use your example in the question but mine, because it's related though.
I have route like this:
Route::name('your.name.here')->get('/your/uri', 'YourController@someMethod');
Then in your controller method, make sure you include
use Illuminate\Http\Request;
and this should be above your controller, most likely a default, if generated using php artisan
, now to get variable from the url it should look like this:
public function someMethod(Request $request)
{
$foo = $request->input("start");
$bar = $request->input("limit");
// some codes here
}
Regardless of the HTTP verb, the input() method may be used to retrieve user input.
https://laravel.com/docs/5.6/requests#retrieving-input
Hope this help.
If you're not sure whether the object has been disposed or not, you should call the Dispose
method itself rather than methods such as Close
. While the framework doesn't guarantee that the Dispose method must run without exceptions even if the object had previously been disposed, it's a common pattern and to my knowledge implemented on all disposable objects in the framework.
The typical pattern for Dispose
, as per Microsoft:
public void Dispose()
{
Dispose(true);
// Use SupressFinalize in case a subclass
// of this type implements a finalizer.
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
// If you need thread safety, use a lock around these
// operations, as well as in your methods that use the resource.
if (!_disposed)
{
if (disposing) {
if (_resource != null)
_resource.Dispose();
Console.WriteLine("Object disposed.");
}
// Indicate that the instance has been disposed.
_resource = null;
_disposed = true;
}
}
Notice the check on _disposed
. If you were to call a Dispose
method implementing this pattern, you could call Dispose as many times as you wanted without hitting exceptions.
contentType
option to false
is used for multipart/form-data
forms that pass files.
When one sets the contentType
option to false
, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multipart/form-data, one must leave the processData
flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.
Use jQuery's .serialize()
method which creates a text string in standard URL-encoded notation.
You need to pass un-encoded data when using contentType: false
.
Try using new FormData
instead of .serialize():
var formData = new FormData($(this)[0]);
See for yourself the difference of how your formData is passed to your php page by using console.log()
.
var formData = new FormData($(this)[0]);
console.log(formData);
var formDataSerialized = $(this).serialize();
console.log(formDataSerialized);
I use UUID() to create a unique value.
example:
insert into Companies (CompanyID, CompanyName) Values(UUID(), "TestUUID");
_cmbTemplates.SelectedText = "test1"
or maybe
_cmbTemplates.SelectedItem= _cmbTemplates.Items.Equals("test1");
Add the docker group if it doesn't already exist.
$ sudo groupadd docker
Add the connected user "${USER}" to the docker group.
Change the user name to match your preferred user.
You may have to logout and log back in again for this to take effect.
$ sudo gpasswd -a ${USER} docker
Restart the Docker daemon.
$ sudo service docker restart
Either !=
or ne
will work, but you need to get the accessor syntax and nested quotes sorted out.
<c:if test="${content.contentType.name ne 'MCE'}">
<%-- snip --%>
</c:if>
Simply get all improtanat information with this below SQL in Mysql
SELECT t.TABLE_NAME , t.ENGINE , t.TABLE_ROWS ,t.AVG_ROW_LENGTH,
t.INDEX_LENGTH FROM
INFORMATION_SCHEMA.TABLES as t where t.TABLE_SCHEMA = 'YOURTABLENAMEHERE'
order by t.TABLE_NAME ASC limit 10000;
[Note: edited to modernize ggplot syntax]
Your example is not reproducible since there is no ex1221new
(there is an ex1221
in Sleuth2
, so I guess that is what you meant). Also, you don't need (and shouldn't) pull columns out to send to ggplot
. One advantage is that ggplot
works with data.frame
s directly.
You can set the labels with xlab()
and ylab()
, or make it part of the scale_*.*
call.
library("Sleuth2")
library("ggplot2")
ggplot(ex1221, aes(Discharge, Area)) +
geom_point(aes(size=NO3)) +
scale_size_area() +
xlab("My x label") +
ylab("My y label") +
ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")
ggplot(ex1221, aes(Discharge, Area)) +
geom_point(aes(size=NO3)) +
scale_size_area("Nitrogen") +
scale_x_continuous("My x label") +
scale_y_continuous("My y label") +
ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")
An alternate way to specify just labels (handy if you are not changing any other aspects of the scales) is using the labs
function
ggplot(ex1221, aes(Discharge, Area)) +
geom_point(aes(size=NO3)) +
scale_size_area() +
labs(size= "Nitrogen",
x = "My x label",
y = "My y label",
title = "Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")
which gives an identical figure to the one above.
If you're playing around in Blazor and get the error, you need to add the package Microsoft.AspNetCore.Blazor.HttpClient
.
WAMP = Windows + Apache + MySQL/MariaDB + PHP/Python/Perl
You can't use MongoDB in wamp.You need to install MongoDB separately
Deleting the file \AppData\Local\Microsoft\VisualStudio\14.0\1033\SpecificFold??erCache.xml solved the issue for me.
These solutions are working in case when target database is blank. In case when both databases already have some data you need something more complicated http://byalexblog.net/merge-sql-databases
What I did was creating my own Window and Style. Because I like to have control over everything and I didn't want some external libraries just to use a Window from it. I looked at already mentioned MahApps.Metro on GitHub
and also very nice Modern UI on GitHub. (.NET4.5 only)
There is one more it's Elysium but I really didn't try this one.
The style I did was really easy when I looked how it's done in these. Now I have my own Window and I can do whatever I want with xaml... for me it's the main reason why I did my own. And I made one more for you too :) I should probably say that I wouldn't be able to do it without exploring Modern UI it was great help. I tried to make it look like VS2012 Window. It looks like this.
Here is code (please note that it's targeting .NET4.5)
public class MyWindow : Window
{
public MyWindow()
{
this.CommandBindings.Add(new CommandBinding(SystemCommands.CloseWindowCommand, this.OnCloseWindow));
this.CommandBindings.Add(new CommandBinding(SystemCommands.MaximizeWindowCommand, this.OnMaximizeWindow, this.OnCanResizeWindow));
this.CommandBindings.Add(new CommandBinding(SystemCommands.MinimizeWindowCommand, this.OnMinimizeWindow, this.OnCanMinimizeWindow));
this.CommandBindings.Add(new CommandBinding(SystemCommands.RestoreWindowCommand, this.OnRestoreWindow, this.OnCanResizeWindow));
}
private void OnCanResizeWindow(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = this.ResizeMode == ResizeMode.CanResize || this.ResizeMode == ResizeMode.CanResizeWithGrip;
}
private void OnCanMinimizeWindow(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = this.ResizeMode != ResizeMode.NoResize;
}
private void OnCloseWindow(object target, ExecutedRoutedEventArgs e)
{
SystemCommands.CloseWindow(this);
}
private void OnMaximizeWindow(object target, ExecutedRoutedEventArgs e)
{
SystemCommands.MaximizeWindow(this);
}
private void OnMinimizeWindow(object target, ExecutedRoutedEventArgs e)
{
SystemCommands.MinimizeWindow(this);
}
private void OnRestoreWindow(object target, ExecutedRoutedEventArgs e)
{
SystemCommands.RestoreWindow(this);
}
}
And here resources:
<BooleanToVisibilityConverter x:Key="bool2VisibilityConverter" />
<Color x:Key="WindowBackgroundColor">#FF2D2D30</Color>
<Color x:Key="HighlightColor">#FF3F3F41</Color>
<Color x:Key="BlueColor">#FF007ACC</Color>
<Color x:Key="ForegroundColor">#FFF4F4F5</Color>
<SolidColorBrush x:Key="WindowBackgroundColorBrush" Color="{StaticResource WindowBackgroundColor}"/>
<SolidColorBrush x:Key="HighlightColorBrush" Color="{StaticResource HighlightColor}"/>
<SolidColorBrush x:Key="BlueColorBrush" Color="{StaticResource BlueColor}"/>
<SolidColorBrush x:Key="ForegroundColorBrush" Color="{StaticResource ForegroundColor}"/>
<Style x:Key="WindowButtonStyle" TargetType="{x:Type Button}">
<Setter Property="Foreground" Value="{DynamicResource ForegroundColorBrush}" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="Padding" Value="1" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid Background="{TemplateBinding Background}">
<ContentPresenter x:Name="contentPresenter"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
Margin="{TemplateBinding Padding}"
RecognizesAccessKey="True" />
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="{StaticResource HighlightColorBrush}" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" Value="{DynamicResource BlueColorBrush}" />
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter TargetName="contentPresenter" Property="Opacity" Value=".5" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="MyWindowStyle" TargetType="local:MyWindow">
<Setter Property="Foreground" Value="{DynamicResource ForegroundColorBrush}" />
<Setter Property="Background" Value="{DynamicResource WindowBackgroundBrush}"/>
<Setter Property="ResizeMode" Value="CanResizeWithGrip" />
<Setter Property="UseLayoutRounding" Value="True" />
<Setter Property="TextOptions.TextFormattingMode" Value="Display" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:MyWindow">
<Border x:Name="WindowBorder" Margin="{Binding Source={x:Static SystemParameters.WindowNonClientFrameThickness}}" Background="{StaticResource WindowBackgroundColorBrush}">
<Grid>
<Border BorderThickness="1">
<AdornerDecorator>
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="25" />
<RowDefinition Height="*" />
<RowDefinition Height="15" />
</Grid.RowDefinitions>
<ContentPresenter Grid.Row="1" Grid.RowSpan="2" Margin="7"/>
<Rectangle x:Name="HeaderBackground" Height="25" Fill="{DynamicResource WindowBackgroundColorBrush}" VerticalAlignment="Top" Grid.Row="0"/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Top" WindowChrome.IsHitTestVisibleInChrome="True" Grid.Row="0">
<Button Command="{Binding Source={x:Static SystemCommands.MinimizeWindowCommand}}" ToolTip="minimize" Style="{StaticResource WindowButtonStyle}">
<Button.Content>
<Grid Width="30" Height="25" RenderTransform="1,0,0,1,0,1">
<Path Data="M0,6 L8,6 Z" Width="8" Height="7" VerticalAlignment="Center" HorizontalAlignment="Center"
Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="2" />
</Grid>
</Button.Content>
</Button>
<Grid Margin="1,0,1,0">
<Button x:Name="Restore" Command="{Binding Source={x:Static SystemCommands.RestoreWindowCommand}}" ToolTip="restore" Visibility="Collapsed" Style="{StaticResource WindowButtonStyle}">
<Button.Content>
<Grid Width="30" Height="25" UseLayoutRounding="True" RenderTransform="1,0,0,1,.5,.5">
<Path Data="M2,0 L8,0 L8,6 M0,3 L6,3 M0,2 L6,2 L6,8 L0,8 Z" Width="8" Height="8" VerticalAlignment="Center" HorizontalAlignment="Center"
Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="1" />
</Grid>
</Button.Content>
</Button>
<Button x:Name="Maximize" Command="{Binding Source={x:Static SystemCommands.MaximizeWindowCommand}}" ToolTip="maximize" Style="{StaticResource WindowButtonStyle}">
<Button.Content>
<Grid Width="31" Height="25">
<Path Data="M0,1 L9,1 L9,8 L0,8 Z" Width="9" Height="8" VerticalAlignment="Center" HorizontalAlignment="Center"
Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="2" />
</Grid>
</Button.Content>
</Button>
</Grid>
<Button Command="{Binding Source={x:Static SystemCommands.CloseWindowCommand}}" ToolTip="close" Style="{StaticResource WindowButtonStyle}">
<Button.Content>
<Grid Width="30" Height="25" RenderTransform="1,0,0,1,0,1">
<Path Data="M0,0 L8,7 M8,0 L0,7 Z" Width="8" Height="7" VerticalAlignment="Center" HorizontalAlignment="Center"
Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="1.5" />
</Grid>
</Button.Content>
</Button>
</StackPanel>
<TextBlock x:Name="WindowTitleTextBlock" Grid.Row="0" Text="{TemplateBinding Title}" HorizontalAlignment="Left" TextTrimming="CharacterEllipsis" VerticalAlignment="Center" Margin="8 -1 0 0" FontSize="16" Foreground="{TemplateBinding Foreground}"/>
<Grid Grid.Row="2">
<Path x:Name="ResizeGrip" Visibility="Collapsed" Width="12" Height="12" Margin="1" HorizontalAlignment="Right"
Stroke="{StaticResource BlueColorBrush}" StrokeThickness="1" Stretch="None" Data="F1 M1,10 L3,10 M5,10 L7,10 M9,10 L11,10 M2,9 L2,11 M6,9 L6,11 M10,9 L10,11 M5,6 L7,6 M9,6 L11,6 M6,5 L6,7 M10,5 L10,7 M9,2 L11,2 M10,1 L10,3" />
</Grid>
</Grid>
</AdornerDecorator>
</Border>
<Border BorderBrush="{StaticResource BlueColorBrush}" BorderThickness="1" Visibility="{Binding IsActive, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Converter={StaticResource bool2VisibilityConverter}}" />
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="WindowState" Value="Maximized">
<Setter TargetName="Maximize" Property="Visibility" Value="Collapsed" />
<Setter TargetName="Restore" Property="Visibility" Value="Visible" />
<Setter TargetName="LayoutRoot" Property="Margin" Value="7" />
</Trigger>
<Trigger Property="WindowState" Value="Normal">
<Setter TargetName="Maximize" Property="Visibility" Value="Visible" />
<Setter TargetName="Restore" Property="Visibility" Value="Collapsed" />
</Trigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="ResizeMode" Value="CanResizeWithGrip" />
<Condition Property="WindowState" Value="Normal" />
</MultiTrigger.Conditions>
<Setter TargetName="ResizeGrip" Property="Visibility" Value="Visible" />
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="WindowChrome.WindowChrome">
<Setter.Value>
<WindowChrome CornerRadius="0" GlassFrameThickness="1" UseAeroCaptionButtons="False" />
</Setter.Value>
</Setter>
</Style>
Look at the r.status_code
attribute:
if r.status_code == 404:
# A 404 was issued.
Demo:
>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404
If you want requests
to raise an exception for error codes (4xx or 5xx), call r.raise_for_status()
:
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "requests/models.py", line 664, in raise_for_status
raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.
You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:
if r:
# successful response
If you want to be more explicit, use if r.ok:
.
select * from test;
a1 a2 a3
1 1 2
1 2 2
2 1 2
select t1.a3 from test t1, test t2 where t1.a1 = t2.a1 and t2.a2 = t1.a2 and t1.a1 = t2.a2
a3
1
You can try same thing using Joins too..
I use the following line to add for staging all the modified and newly created files, excluding the ones listed in .gitignore:
git add $(git ls-files -mo --exclude-standard)
(the syntax $() is for the bash shell). I guess that the command line option -mod should add also the deleted files... Or, if you have file names with embedded blanks, the following one-liner should do the trick:
git ls-files -z --deleted --modified --others --exclude-standard | xargs -0 git add
and with --outdated as an extra argument, you will get the Current and Latest versions of the packages you are using :
$ pip list --outdated
distribute (Current: 0.6.34 Latest: 0.7.3)
django-bootstrap3 (Current: 1.1.0 Latest: 4.3.0)
Django (Current: 1.5.4 Latest: 1.6.4)
Jinja2 (Current: 2.6 Latest: 2.8)
So combining with AdamKG 's answer :
$ pip list --outdated | grep Jinja2
Jinja2 (Current: 2.6 Latest: 2.8)
Check pip-tools too : https://github.com/nvie/pip-tools
String.prototype.startsWith
is a standard method in the most recent version of JavaScript, ES6.
Looking at the compatibility table below, we can see that it is supported on all current major platforms, except versions of Internet Explorer.
+-------------------------------------------------------------------------------+
¦ Feature ¦ Chrome ¦ Firefox ¦ Edge ¦ Internet Explorer ¦ Opera ¦ Safari ¦
¦---------------+--------+---------+-------+-------------------+-------+--------¦
¦ Basic Support ¦ 41+ ¦ 17+ ¦ (Yes) ¦ No Support ¦ 28 ¦ 9 ¦
+-------------------------------------------------------------------------------+
You'll need to implement .startsWith
yourself. Here is the polyfill:
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchString, position) {
position = position || 0;
return this.indexOf(searchString, position) === position;
};
}
I believe you could create you own branch (using your own credential) from the same trunk as your workmate's branch, merge from your workmate's branch to your working copy and then merge from your branch. All future commit should be marked as coming from you.
Check the project properties. It's configurable there if you are using another .net windows application for example
Manifest.MF contains information about the files contained in the JAR file.
Whenever a JAR file is created a default manifest.mf file is created inside META-INF folder and it contains the default entries like this:
Manifest-Version: 1.0
Created-By: 1.7.0_06 (Oracle Corporation)
These are entries as “header:value” pairs. The first one specifies the manifest version and second one specifies the JDK version with which the JAR file is created.
Main-Class header: When a JAR file is used to bundle an application in a package, we need to specify the class serving an entry point of the application. We provide this information using ‘Main-Class’ header of the manifest file,
Main-Class: {fully qualified classname}
The ‘Main-Class’ value here is the class having main method. After specifying this entry we can execute the JAR file to run the application.
Class-Path header: Most of the times we need to access the other JAR files from the classes packaged inside application’s JAR file. This can be done by providing their fully qualified paths in the manifest file using ‘Class-Path’ header,
Class-Path: {jar1-name jar2-name directory-name/jar3-name}
This header can be used to specify the external JAR files on the same local network and not inside the current JAR.
Package version related headers: When the JAR file is used for package versioning the following headers are used as specified by the Java language specification:
Headers in a manifest
Header | Definition
-------------------------------------------------------------------
Name | The name of the specification.
Specification-Title | The title of the specification.
Specification-Version | The version of the specification.
Specification-Vendor | The vendor of the specification.
Implementation-Title | The title of the implementation.
Implementation-Version | The build number of the implementation.
Implementation-Vendor | The vendor of the implementation.
Package sealing related headers:
We can also specify if any particular packages inside a JAR file should be sealed meaning all the classes defined in that package must be archived in the same JAR file. This can be specified with the help of ‘Sealed’ header,
Name: {package/some-package/} Sealed:true
Here, the package name must end with ‘/’.
Enhancing security with manifest files:
We can use manifest files entries to ensure the security of the web application or applet it packages with the different attributes as ‘Permissions’, ‘Codebae’, ‘Application-Name’, ‘Trusted-Only’ and many more.
META-INF folder:
This folder is where the manifest file resides. Also, it can contain more files containing meta data about the application. For example, in an EJB module JAR file, this folder contains the EJB deployment descriptor for the EJB module along with the manifest file for the JAR. Also, it contains the xml file containing mapping of an abstract EJB references to concrete container resources of the application server on which it will be run.
Reference:
https://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html
If you are using Visual S2019, Create a new local branch as shown in following, and then push the changes to the repo.
Most of the solutions given here to create the prepared query are more complex that they need to be. Using PHP's built in functions you can easily creare the SQL statement without significant overhead.
Given $records
, an array of records where each record is itself an indexed array (in the form of field => value
), the following function will insert the records into the given table $table
, on a PDO connection $connection
, using only a single prepared statement. Note that this is a PHP 5.6+ solution because of the use of argument unpacking in the call to array_push
:
private function import(PDO $connection, $table, array $records)
{
$fields = array_keys($records[0]);
$placeHolders = substr(str_repeat(',?', count($fields)), 1);
$values = [];
foreach ($records as $record) {
array_push($values, ...array_values($record));
}
$query = 'INSERT INTO ' . $table . ' (';
$query .= implode(',', $fields);
$query .= ') VALUES (';
$query .= implode('),(', array_fill(0, count($records), $placeHolders));
$query .= ')';
$statement = $connection->prepare($query);
$statement->execute($values);
}
I guess you hate to write more selectors and divide them by a comma?
.registration_form_right input:not([type="radio"]),
.registration_form_right input:not([type="checkbox"])
{
}
and BTW this
not([type="radio" && type="checkbox"])
looks to me more like "input which does not have both these types" :)
No it doesn't wait and the way you are doing it in that sample is not good practice.
dispatch_async
is always asynchronous. It's just that you are enqueueing all the UI blocks to the same queue so the different blocks will run in sequence but parallel with your data processing code.
If you want the update to wait you can use dispatch_sync
instead.
// This will wait to finish
dispatch_sync(dispatch_get_main_queue(), ^{
// Update the UI on the main thread.
});
Another approach would be to nest enqueueing the block. I wouldn't recommend it for multiple levels though.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Background work
dispatch_async(dispatch_get_main_queue(), ^{
// Update UI
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Background work
dispatch_async(dispatch_get_main_queue(), ^{
// Update UI
});
});
});
});
If you need the UI updated to wait then you should use the synchronous versions. It's quite okay to have a background thread wait for the main thread. UI updates should be very quick.
how about just recasting inside a method that should invoke basically a automatic copy constructor
T t = new T();
T t2 = (T)t; //eh something like that
List<myclass> cloneum;
public void SomeFuncB(ref List<myclass> _mylist)
{
cloneum = new List<myclass>();
cloneum = (List < myclass >) _mylist;
cloneum.Add(new myclass(3));
_mylist = new List<myclass>();
}
seems to work to me
Nowadays, Alpine images will boot directly into /bin/sh
by default, without having to specify a shell to execute:
$ sudo docker run -it --rm alpine
/ # echo $0
/bin/sh
This is since the alpine
image Dockerfiles now contain a CMD
command, that specifies the shell to execute when the container starts: CMD ["/bin/sh"]
.
In older Alpine image versions (pre-2017), the CMD command was not used, since Docker used to create an additional layer for CMD which caused the image size to increase. This is something that the Alpine image developers wanted to avoid. In recent Docker versions (1.10+), CMD no longer occupies a layer, and so it was added to alpine
images. Therefore, as long as CMD is not overridden, recent Alpine images will boot into /bin/sh
.
For reference, see the following commit to the official Alpine Dockerfiles by Glider Labs:
https://github.com/gliderlabs/docker-alpine/commit/ddc19dd95ceb3584ced58be0b8d7e9169d04c7a3#diff-db3dfdee92c17cf53a96578d4900cb5b
You do it exactly as you showed with this line:
get.setHeader("Content-Type", "application/x-zip");
So your header is fine and the problem is some other input to the web service. You'll want to debug that on the server side.
I think if the HTML and other UI stuff needs the data returned then there is not going to be a way to async it.
I believe the only way to do this in PHP would be to log a request in a database and have a cron check every minute, or use something like Gearman queue processing, or maybe exec() a command line process
In the meantime you php page would have to generate some html or js that makes it reload every few seconds to check on progress, not ideal.
To sidestep the issue, how many different requests are you expecting? Could you download them all automatically every hour or so and save to a database?
Sample Code: To set Footer text programatically
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
Label lbl = (Label)e.Row.FindControl("lblTotal");
lbl.Text = grdTotal.ToString("c");
}
}
UPDATED CODE:
decimal sumFooterValue = 0;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string sponsorBonus = ((Label)e.Row.FindControl("Label2")).Text;
string pairingBonus = ((Label)e.Row.FindControl("Label3")).Text;
string staticBonus = ((Label)e.Row.FindControl("Label4")).Text;
string leftBonus = ((Label)e.Row.FindControl("Label5")).Text;
string rightBonus = ((Label)e.Row.FindControl("Label6")).Text;
decimal totalvalue = Convert.ToDecimal(sponsorBonus) + Convert.ToDecimal(pairingBonus) + Convert.ToDecimal(staticBonus) + Convert.ToDecimal(leftBonus) + Convert.ToDecimal(rightBonus);
e.Row.Cells[6].Text = totalvalue.ToString();
sumFooterValue += totalvalue;
}
if (e.Row.RowType == DataControlRowType.Footer)
{
Label lbl = (Label)e.Row.FindControl("lblTotal");
lbl.Text = sumFooterValue.ToString();
}
}
In .aspx Page
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1"
AutoGenerateColumns="False" DataKeyNames="ID" CellPadding="4"
ForeColor="#333333" GridLines="None" ShowFooter="True"
onrowdatabound="GridView1_RowDataBound">
<RowStyle BackColor="#EFF3FB" />
<Columns>
<asp:TemplateField HeaderText="Report Date" SortExpression="reportDate">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("reportDate") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server"
Text='<%# Bind("reportDate", "{0:dd MMMM yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sponsor Bonus" SortExpression="sponsorBonus">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("sponsorBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server"
Text='<%# Bind("sponsorBonus", "{0:0.00}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Pairing Bonus" SortExpression="pairingBonus">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("pairingBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server"
Text='<%# Bind("pairingBonus", "{0:c}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Static Bonus" SortExpression="staticBonus">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("staticBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("staticBonus") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Left Bonus" SortExpression="leftBonus">
<EditItemTemplate>
<asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("leftBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("leftBonus") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Right Bonus" SortExpression="rightBonus">
<EditItemTemplate>
<asp:TextBox ID="TextBox6" runat="server" Text='<%# Bind("rightBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label6" runat="server" Text='<%# Bind("rightBonus") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total" SortExpression="total">
<EditItemTemplate>
<asp:TextBox ID="TextBox7" runat="server"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:Label ID="lbltotal" runat="server" Text="Label"></asp:Label>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label7" runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle Width="100px" />
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
My Blog - Asp.net Gridview Article
Given that the accepted answer is outdated and I see nothing in the other answers regarding this I am creating a new one. In .Net 2, and earlier, you had to manually close the stream before closing the connection. That bug is fixed in all later versions of TcpClient
in C# and as stated in the doc of the Close method a call to the method Close
closes both the connection and the stream
EDIT according to Microsoft Docs
The Close method marks the instance as disposed and requests that the associated Socket close the TCP connection. Based on the LingerState property, the TCP connection may stay open for some time after the Close method is called when data remains to be sent. There is no notification provided when the underlying connection has completed closing.
Calling this method will eventually result in the close of the associated Socket and will also close the associated NetworkStream that is used to send and receive data if one was created.
Forms in C# are classes that inherit the Form
base class.
You can show a popup by creating an instance of the class and calling ShowDialog()
.
This should work, at least according to the Search Filter Syntax article on MSDN network.
The "hang-up" you have noticed is probably just a delay. Try running the same query with narrower scope (for example the specific OU where the test object is located), as it may take very long time for processing if you run it against all AD objects.
You may also try separating the filter into two parts:
(|(displayName=*searchstring)(displayName=searchstring*))
You can get the latest version of Boost by using Homebrew.
brew install boost
.
If it is related to the SSIS Package check may be possible that your source db contains few null rows. After removing them this issue will not appear any more.
Here's a C# function that prepends a text line to an existing text blob, delimited by CRLFs, and returns a T-SQL expression suitable for INSERT
or UPDATE
operations. It's got some of our proprietary error handling in it, but once you rip that out, it may be helpful -- I hope so.
/// <summary>
/// Generate a SQL string value expression suitable for INSERT/UPDATE operations that prepends
/// the specified line to an existing block of text, assumed to have \r\n delimiters, and
/// truncate at a maximum length.
/// </summary>
/// <param name="sNewLine">Single text line to be prepended to existing text</param>
/// <param name="sOrigLines">Current text value; assumed to be CRLF-delimited</param>
/// <param name="iMaxLen">Integer field length</param>
/// <returns>String: SQL string expression suitable for INSERT/UPDATE operations. Empty on error.</returns>
private string PrependCommentLine(string sNewLine, String sOrigLines, int iMaxLen)
{
String fn = MethodBase.GetCurrentMethod().Name;
try
{
String [] line_array = sOrigLines.Split("\r\n".ToCharArray());
List<string> orig_lines = new List<string>();
foreach(String orig_line in line_array)
{
if (!String.IsNullOrEmpty(orig_line))
{
orig_lines.Add(orig_line);
}
} // end foreach(original line)
String final_comments = "'" + sNewLine + "' + CHAR(13) + CHAR(10) ";
int cum_length = sNewLine.Length + 2;
foreach(String orig_line in orig_lines)
{
String curline = orig_line;
if (cum_length >= iMaxLen) break; // stop appending if we're already over
if ((cum_length+orig_line.Length+2)>=iMaxLen) // If this one will push us over, truncate and warn:
{
Util.HandleAppErr(this, fn, "Truncating comments: " + orig_line);
curline = orig_line.Substring(0, iMaxLen - (cum_length + 3));
}
final_comments += " + '" + curline + "' + CHAR(13) + CHAR(10) \r\n";
cum_length += orig_line.Length + 2;
} // end foreach(second pass on original lines)
return(final_comments);
} // end main try()
catch(Exception exc)
{
Util.HandleExc(this,fn,exc);
return("");
}
}
I'm using ZSH so I had to modify ~/.zshrc
with the lines concerning NVM in that order:
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm
source ~/.nvm/nvm.sh
The ModelAttribute annotation is used as part of a Spring MVC Web application and can be used in two scenarios.
First of all, it can be used to inject data into a pre-JSP load model. This is especially useful in ensuring that a JSP is required to display all the data itself. An injection is obtained by connecting one method to the model.
Second, it can be used to read data from an existing model and assign it to the parameters of the coach's method.
refrence https://dzone.com/articles/using-spring-mvc%E2%80%99s
You can implement a SoapExtension that logs the full request and response to a log file. You can then enable the SoapExtension in the web.config, which makes it easy to turn on/off for debugging purposes. Here is an example that I have found and modified for my own use, in my case the logging was done by log4net but you can replace the log methods with your own.
public class SoapLoggerExtension : SoapExtension
{
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Stream oldStream;
private Stream newStream;
public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
{
return null;
}
public override object GetInitializer(Type serviceType)
{
return null;
}
public override void Initialize(object initializer)
{
}
public override System.IO.Stream ChainStream(System.IO.Stream stream)
{
oldStream = stream;
newStream = new MemoryStream();
return newStream;
}
public override void ProcessMessage(SoapMessage message)
{
switch (message.Stage)
{
case SoapMessageStage.BeforeSerialize:
break;
case SoapMessageStage.AfterSerialize:
Log(message, "AfterSerialize");
CopyStream(newStream, oldStream);
newStream.Position = 0;
break;
case SoapMessageStage.BeforeDeserialize:
CopyStream(oldStream, newStream);
Log(message, "BeforeDeserialize");
break;
case SoapMessageStage.AfterDeserialize:
break;
}
}
public void Log(SoapMessage message, string stage)
{
newStream.Position = 0;
string contents = (message is SoapServerMessage) ? "SoapRequest " : "SoapResponse ";
contents += stage + ";";
StreamReader reader = new StreamReader(newStream);
contents += reader.ReadToEnd();
newStream.Position = 0;
log.Debug(contents);
}
void ReturnStream()
{
CopyAndReverse(newStream, oldStream);
}
void ReceiveStream()
{
CopyAndReverse(newStream, oldStream);
}
public void ReverseIncomingStream()
{
ReverseStream(newStream);
}
public void ReverseOutgoingStream()
{
ReverseStream(newStream);
}
public void ReverseStream(Stream stream)
{
TextReader tr = new StreamReader(stream);
string str = tr.ReadToEnd();
char[] data = str.ToCharArray();
Array.Reverse(data);
string strReversed = new string(data);
TextWriter tw = new StreamWriter(stream);
stream.Position = 0;
tw.Write(strReversed);
tw.Flush();
}
void CopyAndReverse(Stream from, Stream to)
{
TextReader tr = new StreamReader(from);
TextWriter tw = new StreamWriter(to);
string str = tr.ReadToEnd();
char[] data = str.ToCharArray();
Array.Reverse(data);
string strReversed = new string(data);
tw.Write(strReversed);
tw.Flush();
}
private void CopyStream(Stream fromStream, Stream toStream)
{
try
{
StreamReader sr = new StreamReader(fromStream);
StreamWriter sw = new StreamWriter(toStream);
sw.WriteLine(sr.ReadToEnd());
sw.Flush();
}
catch (Exception ex)
{
string message = String.Format("CopyStream failed because: {0}", ex.Message);
log.Error(message, ex);
}
}
}
[AttributeUsage(AttributeTargets.Method)]
public class SoapLoggerExtensionAttribute : SoapExtensionAttribute
{
private int priority = 1;
public override int Priority
{
get { return priority; }
set { priority = value; }
}
public override System.Type ExtensionType
{
get { return typeof (SoapLoggerExtension); }
}
}
You then add the following section to your web.config where YourNamespace and YourAssembly point to the class and assembly of your SoapExtension:
<webServices>
<soapExtensionTypes>
<add type="YourNamespace.SoapLoggerExtension, YourAssembly"
priority="1" group="0" />
</soapExtensionTypes>
</webServices>
Specifically, document.all
was introduced for IE4 BEFORE document.getElementById
had been introduced.
So, the presence of document.all
means that the code is intended to support IE4, or is trying to identify the browser as IE4 (though it could have been Opera), or the person who wrote (or copied and pasted) the code wasn't up on the latest.
In the highly unlikely event that you need to support IE4, then, you do need document.all
(or a library that handles these ancient IE specs).
Only people from Microsoft can really answer that question. However, I'd like to offer some fun facts about it ;)
First, this is what it says in MSDN about the Boolean.ToString() method:
Return Value
Type: System.String
TrueString if the value of this instance is true, or FalseString if the value of this instance is false.
Remarks
This method returns the constants "True" or "False". Note that XML is case-sensitive, and that the XML specification recognizes "true" and "false" as the valid set of Boolean values. If the String object returned by the ToString() method is to be written to an XML file, its String.ToLower method should be called first to convert it to lowercase.
Here comes the fun fact #1: it doesn't return TrueString or FalseString at all. It uses hardcoded literals "True" and "False". Wouldn't do you any good if it used the fields, because they're marked as readonly, so there's no changing them.
The alternative method, Boolean.ToString(IFormatProvider) is even funnier:
Remarks
The provider parameter is reserved. It does not participate in the execution of this method. This means that the Boolean.ToString(IFormatProvider) method, unlike most methods with a provider parameter, does not reflect culture-specific settings.
What's the solution? Depends on what exactly you're trying to do. Whatever it is, I bet it will require a hack ;)
Correct me if wrong...I think request does persist between consecutive pages..
Think you traverse from page 1--> page 2-->page 3.
You have some value set in the request object using setAttribute from page 1, which you retrieve in page 2 using getAttribute,then if you try setting something again in same request object to retrieve it in page 3 then it fails giving you null value as "the request that created the JSP, and the request that gets generated when the JSP is submitted are completely different requests and any attributes placed on the first one will not be available on the second".
I mean something like this in page 2 fails:
Where as the same thing has worked in case of page 1 like:
So I think I would need to proceed with either of the two options suggested by Phill.
You could load the external page with jquery:
<script>$("#testLoad").load("http://www.somesite.com/somepage.html");</script> <div id="testLoad"></div> //would this help
The main difference between each of these is the precision.
float
is a 32-bit
number, double
is a 64-bit
number and decimal
is a 128-bit
number.
NGINX itself may not be the root cause.
IF "minimum ports per VM instance" set on the NAT Gateway -- which stand between your NGINX instance & the proxy_pass
destination -- is too small for the number of concurrent requests, it has to be increased.
Solution: Increase the available number of ports per VM on NAT Gateway.
Context In my case, on Google Cloud, a reverse proxy NGINX was placed inside a subnet, with a NAT Gateway. The NGINX instance was redirecting requests to a domain associated with our backend API (upstream) through the NAT Gateway.
This documentation from GCP will help you understand how NAT is relevant to the NGINX 504 timeout.
Here the converter for XStream including unmarshall
public class MapEntryConverter implements Converter{
public boolean canConvert(Class clazz) {
return AbstractMap.class.isAssignableFrom(clazz);
}
public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
AbstractMap<String,String> map = (AbstractMap<String,String>) value;
for (Entry<String,String> entry : map.entrySet()) {
writer.startNode(entry.getKey().toString());
writer.setValue(entry.getValue().toString());
writer.endNode();
}
}
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
Map<String, String> map = new HashMap<String, String>();
while(reader.hasMoreChildren()) {
reader.moveDown();
map.put(reader.getNodeName(), reader.getValue());
reader.moveUp();
}
return map;
}
This is possible to do without an iframe
specifically. jQuery is utilised since it's mentioned in the title.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Load remote content into object element</title>
</head>
<body>
<div id="siteloader"></div>?
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
$("#siteloader").html('<object data="http://tired.com/">');
</script>
</body>
</html>
If your are in Visual Studio 2012 or later this has an additional setting 'SDL checks' Under Property Pages -> C/C++ -> General
Additional Security Development Lifecycle (SDL) recommended checks; includes enabling additional secure code generation features and extra security-relevant warnings as errors.
It defaults to YES - For a reason, I.E you should use the secure version of the strncpy. If you change this to NO you will not get a error when using the insecure version.
let arr = [11,22,11,22];
let hasDuplicate = arr.some((val, i) => arr.indexOf(val) !== i);
// hasDuplicate = true
True -> array has duplicates
False -> uniqe array
Check Nullable<T>.HasValue
if(!SomeProperty.HasValue ||SomeProperty.Value == Guid.Empty)
{
//not valid GUID
}
else
{
//Valid GUID
}
Before truncating the tables you have to remove all foreign keys. Use this script to generate final scripts to drop and recreate all foreign keys in database. Please set the @action variable to 'CREATE' or 'DROP'.
You can use $(window).resize() to detect if the viewport is resized.
jQuery does not have any function to consistently detect the correctly width and height of the viewport[1] when there is a scroll bar present.
I found a solution that uses the Modernizr library and specifically the mq function which opens media queries for javascript.
Here is my solution:
// A function for detecting the viewport minimum width.
// You could use a similar function for minimum height if you wish.
var min_width;
if (Modernizr.mq('(min-width: 0px)')) {
// Browsers that support media queries
min_width = function (width) {
return Modernizr.mq('(min-width: ' + width + ')');
};
}
else {
// Fallback for browsers that does not support media queries
min_width = function (width) {
return $(window).width() >= width;
};
}
var resize = function() {
if (min_width('768px')) {
// Do some magic
}
};
$(window).resize(resize);
resize();
My answer will probably not help resizing a iframe to 100% viewport width with a margin on each side, but I hope it will provide solace for webdevelopers frustrated with browser incoherence of javascript viewport width and height calculation.
Maybe this could help with regards to the iframe:
$('iframe').css('width', '100%').wrap('<div style="margin:2em"></div>');
[1] You can use $(window).width() and $(window).height() to get a number which will be correct in some browsers, but incorrect in others. In those browsers you can try to use window.innerWidth and window.innerHeight to get the correct width and height, but i would advice against this method because it would rely on user agent sniffing.
Usually the different browsers are inconsistent about whether or not they include the scrollbar as part of the window width and height.
Note: Both $(window).width() and window.innerWidth vary between operating systems using the same browser. See: https://github.com/eddiemachado/bones/issues/468#issuecomment-23626238
Since Ubuntu 18.04 installing Intellij IDEA is easy! You just need to search "IDEA" in Software Center. Also you're able to choose a branch to install (I use EAP).
For earlier versions:
According to this (snap) and this (umake) articles the most comfortable ways are:
to use snap-packages (since versions IDEA 2017.3 & Ubuntu 14.04):
install snapd system. Since Ubuntu 16.04 you already have it.
to use ubuntu-make
(for Ubuntu versions earlier than 16.04 use apt-get
command instead apt
):
Add PPA ubuntu-desktop/ubuntu-make (if you install ubuntu-make from standard repo you'll see only a few IDE's):
$ sudo add-apt-repository ppa:ubuntu-desktop/ubuntu-make
Install ubuntu-make:
$ sudo apt update
$ sudo apt install ubuntu-make
install preffered ide (IDEA, for this question):
$ umake ide idea
or even ultimate version if you need:
$ umake ide idea-ultimate
I upgrade Intellij IDEA via reinstalling it:
$ umake -r ide idea-ultimate
$ umake ide idea-ultimate
LCASE or UCASE respectively.
Example:
SELECT UCASE(MyColumn) AS Upper, LCASE(MyColumn) AS Lower
FROM MyTable
Ran into this today and switching to another branch didn't help. It turned out that somehow my worktree information had gotten corrupted and there was a worktree with the same folder path as my working directory with a HEAD
pointing at the branch (git worktree list
). I deleted the .git/worktree/
folder that was referencing it and git branch -d
worked.
Other answers have explained what 'detached HEAD' means. I try to answer why I want to do that. There are some cases I prefer checkout a commit than checkout a temporary branch.
To compile/build at some specific commit (maybe for your daily build or just to release some specific version to test team), I used to checkout a tmp branch for that, but then I need to remember to delete the tmp branch after build. So I found checkout a commit is more convenient, after the build I just checkout to the original branch.
To check what codes look like at that commit, maybe to debug an issue. The case is not much different from my case #1, I can also checkout a tmp branch for that but then I need to remember delete it. So I choose to checkout a commit more often.
This is probably just me being paranoid, so I prepare to merge another branch but I already suspect I would get some merge conflict and I want to see them first before merge. So I checkout the head commit then do the merge, see the merge result. Then I git checkout -f
to switch back to my branch, using -f
to discard any merge conflict. Again I found it more convenient than checkout a tmp branch.
Simple js
if ($(document).height() <= $(window).height()) {
$("footer").addClass("navbar-fixed-bottom");
}
Update #1
$(window).on('resize', function() {
$('footer').toggleClass("navbar-fixed-bottom", $(document).height() <= $(window).height());
});
I received this error while attempting to open an SSDT 2010/SSIS 2012 project in VS with SSDT 2013. When it opened the project, it asked to migrate all the packages. When I allowed it to proceed, every package failed with this error and others. I found that bypassing the conversion and just opening each package individually, the package is upgraded upon opening, and it converted fine and successfully ran.
You should add next permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And then here is usages in code:
val externalFilesDir = context.getExternalFilesDir(DIRECTORY_DOWNLOADS)
The bundle identifier is an ID for your application used by the system as a domain for which it can store settings and reference your application uniquely.
It is represented in reverse DNS notation and it is recommended that you use your company name and application name to create it.
An example bundle ID for an App called The Best App by a company called Awesome Apps would look like:
com.awesomeapps.thebestapp
In this case the suffix is thebestapp
.
It is as simple as string[:2]
. A function can be easily written to do it, if you need.
Even this, is as simple as
def first2(s):
return s[:2]
Why don't you do:
String number = String.valueOf(input);
char[] digits = number.toCharArray();
You can use css for simulate a vertical line, and use the class on the div
.vhLine {
border-left: thick solid #000000;
}
Using moment.js
, you can use keepOffset
parameter of toISOString
:
toISOString(keepOffset?: boolean): string;
moment().toISOString(true)
Here is how to do it with SourceTree (v2.3.1):
1. Click Fetch
2. Check "Prune tracking branches ..."
3. Press OK
4.
all
is one option:
> A <- c("A", "B", "C", "D")
> B <- A
> C <- c("A", "C", "C", "E")
> all(A==B)
[1] TRUE
> all(A==C)
[1] FALSE
But you may have to watch out for recycling:
> D <- c("A","B","A","B")
> E <- c("A","B")
> all(D==E)
[1] TRUE
> all(length(D)==length(E)) && all(D==E)
[1] FALSE
The documentation for length
says it currently only outputs an integer of length 1, but that it may change in the future, so that's why I wrapped the length test in all
.
Wget currently only supports x-www-form-urlencoded data. --post-file
is not for transmitting files as form attachments, it expects data with the form: key=value&otherkey=example
.
--post-data
and --post-file
work the same way: the only difference is that --post-data
allows you to specify the data in the command line, while --post-file
allows you to specify the path of the file that contain the data to send.
Here's the documentation:
--post-data=string
--post-file=file
Use POST as the method for all HTTP requests and send the specified data
in the request body. --post-data sends string as data, whereas
--post-file sends the contents of file. Other than that, they work in
exactly the same way. In particular, they both expect content of the
form "key1=value1&key2=value2", with percent-encoding for special
characters; the only difference is that one expects its content as a
command-line parameter and the other accepts its content from a file. In
particular, --post-file is not for transmitting files as form
attachments: those must appear as "key=value" data (with appropriate
percent-coding) just like everything else. Wget does not currently
support "multipart/form-data" for transmitting POST data; only
"application/x-www-form-urlencoded". Only one of --post-data and
--post-file should be specified.
Regarding your authentication token, it should either be provided in the header, in the path of the url, or in the data itself. This must be indicated somewhere in the documentation of the service you use. In a POST request, as in a GET request, you must specify the data using keys and values. This way the server will be able to receive multiple information with specific names. It's similar with variables.
Hence, you can't just send a magic token to the server, you also need to specify the name of the key. If the key is "token", then it should be token=YOUR_TOKEN
.
wget --post-data 'user=foo&password=bar' http://example.com/auth.php
Also, you should consider using curl if you can because it is easier to send files using it. There are many examples on the Internet for that.
You have $headers .= '...';
followed by $headers = '...';
; the second line is overwriting the first.
Just put the $headers .= "Bcc: $emailList\r\n";
say after the Content-type
line and it should be fine.
On a side note, the To
is generally required; mail servers might mark your message as spam otherwise.
$headers = "From: [email protected]\r\n" .
"X-Mailer: php\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "Bcc: $emailList\r\n";
use it in css external file.
.td-table
{
word-wrap: break-word;
word-break: break-all;
white-space: normal !important;
text-align: justify;
}
This css allowed chrome and firefox to render all other elements on my page normally and remove the margin above my h1 tag. Also, as a page is resized em can work better than px.
h1 {
margin-top: -.3em;
margin-bottom: 0em;
}
Complete code with error handling and added file stream closes. Add it to your class that you want to be able to serialize and deserialize. In my case the class name is CreateResumeForm
. You should change it to your own class name. Android
interface Serializable
is not sufficient to save your objects to the file, it only creates streams.
// Constant with a file name
public static String fileName = "createResumeForm.ser";
// Serializes an object and saves it to a file
public void saveToFile(Context context) {
try {
FileOutputStream fileOutputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(this);
objectOutputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// Creates an object by reading it from a file
public static CreateResumeForm readFromFile(Context context) {
CreateResumeForm createResumeForm = null;
try {
FileInputStream fileInputStream = context.openFileInput(fileName);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
createResumeForm = (CreateResumeForm) objectInputStream.readObject();
objectInputStream.close();
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
return createResumeForm;
}
Use it like this in your Activity
:
form = CreateResumeForm.readFromFile(this);
You are mixing the 1.5.6 version of the jcl bridge with the 1.6.0 version of the slf4j-api; this won't work because of a few changes in 1.6.0. Use the same versions for both, i.e. 1.6.1 (the latest). I use the jcl-over-slf4j bridge all the time and it works fine.
Instead of if
, ternary operator might come handy when you want to get a value based on whether something is nil:
func f(x: String?) -> String {
return x == nil ? "empty" : "non-empty"
}
A small function I made that can grab the string between, and can (optionally) skip a number of matched words to grab a specific index.
Also, setting start
to false
will use the beginning of the string, and setting end
to false
will use the end of the string.
set pos1
to the position of the start
text you want to use, 1
will use the first occurrence of start
pos2
does the same thing as pos1
, but for end
, and 1
will use the first occurrence of end
only after start
, occurrences of end
before start
are ignored.
function getStringBetween(str, start=false, end=false, pos1=1, pos2=1){
var newPos1 = 0;
var newPos2 = str.length;
if(start){
var loops = pos1;
var i = 0;
while(loops > 0){
if(i > str.length){
break;
}else if(str[i] == start[0]){
var found = 0;
for(var p = 0; p < start.length; p++){
if(str[i+p] == start[p]){
found++;
}
}
if(found >= start.length){
newPos1 = i + start.length;
loops--;
}
}
i++;
}
}
if(end){
var loops = pos2;
var i = newPos1;
while(loops > 0){
if(i > str.length){
break;
}else if(str[i] == end[0]){
var found = 0;
for(var p = 0; p < end.length; p++){
if(str[i+p] == end[p]){
found++;
}
}
if(found >= end.length){
newPos2 = i;
loops--;
}
}
i++;
}
}
var result = '';
for(var i = newPos1; i < newPos2; i++){
result += str[i];
}
return result;
}
On Windows: if you use %>% inside a %dopar% loop, you have to add a reference to load package dplyr
(or magrittr
, which dplyr
loads).
Example:
plots <- foreach(myInput=iterators::iter(plotCount), .packages=c("RODBC", "dplyr")) %dopar%
{
return(getPlot(myInput))
}
If you omit the .packages
command, and use %do%
instead to make it all run in a single process, then works fine. The reason is that it all runs in one process, so it doesn't need to specifically load new packages.
import java.text.SimpleDateFormat;
import java.util.Scanner;
class DayFromDate {
public static void main(String args[]) {
System.out.println("Enter the date(dd/mm/yyyy):");
Scanner scan = new Scanner(System.in);
String Date = scan.nextLine();
try {
boolean dateValid = dateValidate(Date);
if(dateValid == true) {
SimpleDateFormat df = new SimpleDateFormat( "dd/MM/yy" );
java.util.Date date = df.parse( Date );
df.applyPattern( "EEE" );
String day= df.format( date );
if(day.compareTo("Sat") == 0 || day.compareTo("Sun") == 0) {
System.out.println(day + ": Weekend");
} else {
System.out.println(day + ": Weekday");
}
} else {
System.out.println("Invalid Date!!!");
}
} catch(Exception e) {
System.out.println("Invalid Date Formats!!!");
}
}
static public boolean dateValidate(String d) {
String dateArray[] = d.split("/");
int day = Integer.parseInt(dateArray[0]);
int month = Integer.parseInt(dateArray[1]);
int year = Integer.parseInt(dateArray[2]);
System.out.print(day + "\n" + month + "\n" + year + "\n");
boolean leapYear = false;
if((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)) {
leapYear = true;
}
if(year > 2099 || year < 1900)
return false;
if(month < 13) {
if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
if(day > 31)
return false;
} else if(month == 4 || month == 6 || month == 9 || month == 11) {
if(day > 30)
return false;
} else if(leapYear == true && month == 2) {
if(day > 29)
return false;
} else if(leapYear == false && month == 2) {
if(day > 28)
return false;
}
return true;
} else return false;
}
}
Your mistake is looking for range
, which gives you the range
of a vector, for example:
range(c(10, -5, 100))
gives
-5 100
Instead, look at the :
operator to give sequences (with a step size of one):
1:100
or you can use the seq
function to have a bit more control. For example,
##Step size of 2
seq(1, 100, by=2)
or
##length.out: desired length of the sequence
seq(1, 100, length.out=5)
Try,
public class Sent
{
public int MsgID;
public string Content;
public int Status;
}
public class Messages
{
public int MsgID;
public string Content;
}
List<Sent> SentList = new List<Sent>() { new Sent() { MsgID = 1, Content = "aaa", Status = 0 }, new Sent() { MsgID = 3, Content = "ccc", Status = 0 } };
List<Messages> MsgList = new List<Messages>() { new Messages() { MsgID = 1, Content = "aaa" }, new Messages() { MsgID = 2, Content = "bbb" }, new Messages() { MsgID = 3, Content = "ccc" }, new Messages() { MsgID = 4, Content = "ddd" }, new Messages() { MsgID = 5, Content = "eee" }};
int [] sentMsgIDs = SentList.Select(v => v.MsgID).ToArray();
List<Messages> result1 = MsgList.Where(o => !sentMsgIDs.Contains(o.MsgID)).ToList<Messages>();
Hope it should help.
You cannot sanely depend on client side JavaScript to determine if user credentials are correct. The browser (and all code that executes that) is under the control of the user, not you, so it is not trustworthy.
The username and password need to be entered using a form. The OK button will be a submit button. The action attribute must point to a URL which will be handled by a program that checks the credentials.
This program could be written in JavaScript, but how you go about that would depend on which server side JavaScript engine you were using. Note that SSJS is not a mainstream technology so if you really want to use it, you would have to use specialised hosting or admin your own server.
(Half a decade later and SSJS is much more common thanks to Node.js, it is still fairly specialised though).
If you want to redirect afterwards, then the program needs to emit an HTTP Location header.
Note that you need to check the credentials are OK (usually by storing a token, which isn't the actual password, in a cookie) before outputting any private page. Otherwise anyone could get to the private pages by knowing the URL (and thus bypassing the login system).
^[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$
Write this code in Terminal.
export GOPATH=path/to/your/gopath/directory
Note: This will reset on every new Terminal window or system restart.
To be persistent, paste the code below in your .zshrc
or .bashrc
file according to your shell. Those files in your Home Directory. It will be like below.
export PATH=path/to/some/other/place/composer/for/example
export GOPATH=path/to/your/gopath/directory
export PATH=$PATH:$GOPATH/bin
I have just compile it and it compiles fine without the implicit import, probably you're seeing a stale cache or something of your IDE.
Have you tried compiling from the command line?
I have the exact same version:
Probably you're thinking the warning is an error.
UPDATE
It looks like you have a Arrays.class
file in the directory where you're trying to compile ( probably created before ). That's why the explicit import solves the problem. Try copying your source code to a clean new directory and try again. You'll see there is no error this time. Or, clean up your working directory and remove the Arrays.class
This solution worked for me:
tabBarOptions: {
showIcon: true,
showLabel: false,
style: {
backgroundColor: '#000',
borderTopLeftRadius: 40,
borderTopRightRadius: 40,
position: 'relative',
zIndex: 2,
marginTop: -48
}
}
This should do
import pylab as plot
params = {'legend.fontsize': 20,
'legend.handlelength': 2}
plot.rcParams.update(params)
Then do the plot afterwards.
There are a ton of other rcParams, they can also be set in the matplotlibrc file.
Also presumably you can change it passing a matplotlib.font_manager.FontProperties
instance but this I don't know how to do. --> see Yann's answer.
You're putting Integers in so Python is giving you an integer back:
>>> 10 / 90
0
If if you cast this to a float afterwards the rounding will have already been done, in other words, 0 integer will always become 0 float.
If you use floats on either side of the division then Python will give you the answer you expect.
>>> 10 / 90.0
0.1111111111111111
So in your case:
>>> float(20-10) / (100-10)
0.1111111111111111
>>> (20-10) / float(100-10)
0.1111111111111111
transparent is the default for background-color
This message displays when Internet Explorer reaches the maximum number of synchronous instructions for a piece of JavaScript. The default maximum is 5,000,000 instructions, you can increase this number on a single machine by editing the registry.
Internet Explorer now tracks the total number of executed script statements and resets the value each time that a new script execution is started, such as from a timeout or from an event handler, for the current page with the script engine. Internet Explorer displays a "long-running script" dialog box when that value is over a threshold amount.
The only way to solve the problem for all users that might be viewing your page is to break up the number of iterations your loop performs using timers, or refactor your code so that it doesn't need to process as many instructions.
Breaking up a loop with timers is relatively straightforward:
var i=0;
(function () {
for (; i < 6000000; i++) {
/*
Normal processing here
*/
// Every 100,000 iterations, take a break
if ( i > 0 && i % 100000 == 0) {
// Manually increment `i` because we break
i++;
// Set a timer for the next iteration
window.setTimeout(arguments.callee);
break;
}
}
})();
Declarative Programming is programming with declarations, i.e. declarative sentences. Declarative sentences have a number of properties that distinguish them from imperative sentences. In particular, declarations are:
A relevant point is that these are all structural properties and are orthogonal to subject matter. Declarative is not about "What vs. How". We can declare (represent and constrain) a "how" just as easily as we declare a "what". Declarative is about structure, not content. Declarative programming has a significant impact on how we abstract and refactor our code, and how we modularize it into subprograms, but not so much on the domain model.
Often, we can convert from imperative to declarative by adding context. E.g. from "Turn left. (... wait for it ...) Turn Right." to "Bob will turn left at intersection of Foo and Bar at 11:01. Bob will turn right at the intersection of Bar and Baz at 11:06." Note that in the latter case the sentences are idempotent and commutative, whereas in the former case rearranging or repeating the sentences would severely change the meaning of the program.
Regarding monotonic, declarations can add constraints which subtract possibilities. But constraints still add information (more precisely, constraints are information). If we need time-varying declarations, it is typical to model this with explicit temporal semantics - e.g. from "the ball is flat" to "the ball is flat at time T". If we have two contradictory declarations, we have an inconsistent declarative system, though this might be resolved by introducing soft constraints (priorities, probabilities, etc.) or leveraging a paraconsistent logic.
Please use the Pandas to_numpy()
method. Below is an example--
>>> import pandas as pd
>>> df = pd.DataFrame({"A":[1, 2], "B":[3, 4], "C":[5, 6]})
>>> df
A B C
0 1 3 5
1 2 4 6
>>> s_array = df[["A", "B", "C"]].to_numpy()
>>> s_array
array([[1, 3, 5],
[2, 4, 6]])
>>> t_array = df[["B", "C"]].to_numpy()
>>> print (t_array)
[[3 5]
[4 6]]
Hope this helps. You can select any number of columns using
columns = ['col1', 'col2', 'col3']
df1 = df[columns]
Then apply to_numpy()
method.
What balanced means depends a bit on the structure at hand. For instance, A B-Tree cannot have nodes more than a certain depth from the root, or less for that matter, all data lives at a fixed depth from the root, but it can be out of balance if the distribution of leaves to leaves-but-one nodes is uneven. Skip-lists Have no notion at all of balance, relying instead on probability to achieve decent performance. Fibonacci trees purposefully fall out of balance, postponing the rebalance to achieve superior asymptotic performance in exchange for occasionally longer updates. AVL and Red-Black trees attach metadata to each node to attain a depth-balance invariant.
All of these structures and more are present in the standard libraries of most common programming systems (except python, RAGE!). Implementing one or two is good programming practice, but its probably not a good use of time to roll your own for production, unless your problem has some peculiar performance need not satisfied by any off-the-shelf collections.
From my experience, there is at least one clear advantage when using event.preventDefault() over using return false. Suppose you are capturing the click event on an anchor tag, otherwise which it would be a big problem if the user were to be navigated away from the current page. If your click handler uses return false to prevent browser navigation, it opens the possibility that the interpreter will not reach the return statement and the browser will proceed to execute the anchor tag's default behavior.
$('a').click(function (e) {
// custom handling here
// oops...runtime error...where oh where will the href take me?
return false;
});
The benefit to using event.preventDefault() is that you can add this as the first line in the handler, thereby guaranteeing that the anchor's default behavior will not fire, regardless if the last line of the function is not reached (eg. runtime error).
$('a').click(function (e) {
e.preventDefault();
// custom handling here
// oops...runtime error, but at least the user isn't navigated away.
});
For TFS 2013:
Start in VisualStudio-Team Explorer, in the PendingChanges Dialog undo the Changes whith the state [add], which should be ignored.
Visual Studio will detect the Add(s) again. Click On "Detected: x add(s)"-in Excluded Changes
In the opened "Promote Cadidate Changes"-Dialog You can easy exclude Files and Folders with the Contextmenu. Options are:
Don't forget to Check In the changed .tfignore-File.
For VS 2015/2017:
The same procedure: In the "Excluded Changes Tab" in TeamExplorer\Pending Changes click on Detected: xxx add(s)
The "Promote Candidate Changes" Dialog opens, and on the entries you can Right-Click for the Contextmenu. Typo is fixed now :-)
Based on above solutions, here comes a extension class which you can use to serialize and deserialize any object. Any other XML attributions are up to you.
Just use it like this:
string s = new MyObject().Serialize(); // to serialize into a string
MyObject b = s.Deserialize<MyObject>();// deserialize from a string
internal static class Extensions
{
public static T Deserialize<T>(this string value)
{
var xmlSerializer = new XmlSerializer(typeof(T));
return (T)xmlSerializer.Deserialize(new StringReader(value));
}
public static string Serialize<T>(this T value)
{
if (value == null)
return string.Empty;
var xmlSerializer = new XmlSerializer(typeof(T));
using (var stringWriter = new StringWriter())
{
using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings { Indent = true }))
{
xmlSerializer.Serialize(xmlWriter, value);
return stringWriter.ToString();
}
}
}
}
I had a similar issue myself, I think all you need to do is git reset --hard
and you will not lose your changes or any untracked changes.
If you read the docs in git stash --help
it states that apply is "Like pop, but do not remove the state from the stash list" so the state still resides there, you can get it back.
Alternatively, if you have no conflicts, you can just git stash
again after testing your changes.
If you do have conflicts, don't worry, git reset --hard
won't lose them, as
"Applying the state can fail with conflicts; in this case, it is not removed from the stash list. You need to resolve the conflicts by hand and call git stash drop manually afterwards."
You can use the script from http://technet.microsoft.com/en-us/library/ee692772.aspx#EBAA to access the registry and list applications using WMI.
import datetime
datetime.datetime.now().strftime ("%Y%m%d")
20151015
For the time
from time import gmtime, strftime
showtime = strftime("%Y-%m-%d %H:%M:%S", gmtime())
print showtime
2015-10-15 07:49:18
I think it's important to note here that onBlur() fires regardless.
This is a helpful thread but the only thing it doesn't clarify is that onBlur() will fire every single time.
onChange() will only fire when the value is changed.
put r
before your string, it converts normal string to raw string
I think that you are after this:
SELECT image_id
FROM list
WHERE (style_id, style_value) IN ((24,'red'),(25,'big'),(27,'round'))
GROUP BY image_id
HAVING count(distinct style_id, style_value)=3
You can't use AND, because values can't be 24 red
and 25 big
and 27 round
at the same time in the same row, but you need to check the presence of style_id, style_value
in multiple rows, under the same image_id
.
In this query I'm using IN (that, in this particular example, is equivalent to an OR), and I am counting the distinct rows that match. If 3 distinct rows match, it means that all 3 attributes are present for that image_id
, and my query will return it.
I would suggest the use of fping with the mask option, since you are not restricting yourself in ping.
fping -g 192.168.1.0/24
The response will be easy to parse in a script:
192.168.1.1 is alive
192.168.1.2 is alive
192.168.1.3 is alive
192.168.1.5 is alive
...
192.168.1.4 is unreachable
192.168.1.6 is unreachable
192.168.1.7 is unreachable
...
Note: Using the argument -a
will restrict the output to reachable ip addresses, you may want to use it otherwise fping will also print unreachable addresses:
fping -a -g 192.168.1.0/24
From man:
fping differs from ping in that you can specify any number of targets on the command line, or specify a file containing the lists of targets to ping. Instead of sending to one target until it times out or replies, fping will send out a ping packet and move on to the next target in a round-robin fashion.
More info: http://fping.org/
There is a lot of error in your program.
Calculation of index. I think it should be Math.random()%deck.length
In the display of card. According to me, you should make a class of card which has rank suit and make the array of that class type
If you want I can give you the Complete structure of that but it is better if u make it by yourself
I have ran into this when doing ajax forms where I include multiple field sets. Taking for example an employment application. I start out with one professional reference set and I have a button that says "Add More". This does an ajax call with a $count parameter to include the input set again (name, contact, phone.. etc) This works fine on first page call as I do something like:
<?php
include('references.php');`
?>
User presses a button that makes an ajax call
Then inside the references.php file I have something like:ajax('references.php?count=1');
<?php
$count = isset($_GET['count']) ? $_GET['count'] : 0;
?>
I also have other dynamic includes like this throughout the site that pass parameters. The problem happens when the user presses submit and there is a form error. So now to not duplicate code to include those extra field sets that where dynamically included, i created a function that will setup the include with the appropriate GET params.
<?php
function include_get_params($file) {
$parts = explode('?', $file);
if (isset($parts[1])) {
parse_str($parts[1], $output);
foreach ($output as $key => $value) {
$_GET[$key] = $value;
}
}
include($parts[0]);
}
?>
The function checks for query params, and automatically adds them to the $_GET variable. This has worked pretty good for my use cases.
Here is an example on the form page when called:
<?php
// We check for a total of 12
for ($i=0; $i<12; $i++) {
if (isset($_POST['references_name_'.$i]) && !empty($_POST['references_name_'.$i])) {
include_get_params(DIR .'references.php?count='. $i);
} else {
break;
}
}
?>
Just another example of including GET params dynamically to accommodate certain use cases. Hope this helps. Please note this code isn't in its complete state but this should be enough to get anyone started pretty good for their use case.
In my case the following was necessary:
sudo chgrp vboxsf /media/sf_sharedFolder
you can use the special package "checkinstall" for all packages which are not even in debian/ubuntu yet.
You can use "uupdate" (apt-get install devscripts
) to build a package from source with existing debian sources:
Example for libdrm2:
apt-get build-dep libdrm2
apt-get source libdrm2
cd libdrm-2.3.1
uupdate ~/Downloads/libdrm-2.4.1.tar.gz
cd ../libdrm-2.4.1
dpkg-buildpackage -us -uc -nc
git config --global alias.count 'rev-list --all --count'
If you add this to your config, you can just reference the command;
git count
// loading bytes from a file is very easy in C#. The built in System.IO.File.ReadAll* methods take care of making sure every byte is read properly.
// note that for Linux, you will not need the c: part
// just swap out the example folder here with your actual full file path
string pdfFilePath = "c:/pdfdocuments/myfile.pdf";
byte[] bytes = System.IO.File.ReadAllBytes(pdfFilePath);
// munge bytes with whatever pdf software you want, i.e. http://sourceforge.net/projects/itextsharp/
// bytes = MungePdfBytes(bytes); // MungePdfBytes is your custom method to change the PDF data
// ...
// make sure to cleanup after yourself
// and save back - System.IO.File.WriteAll* makes sure all bytes are written properly - this will overwrite the file, if you don't want that, change the path here to something else
System.IO.File.WriteAllBytes(pdfFilePath, bytes);
Here is a good way to do it.
from django.utils.datastructures import MultiValueDictKeyError
try:
message = 'You submitted: %r' % request.GET['q']
except MultiValueDictKeyError:
message = 'You submitted nothing!'
You don't need to check again if q is in GET request. The call in the QueryDict.get already does that to you.
Use str(ex) to print execption
try:
#your code
except ex:
print(str(ex))
in support to @jean.timex solution, use below code if you want to open one section at any time. create a variable like: var expandedSection = -1;
func toggleSection(_ header: CollapsibleTableViewHeader, section: Int) {
let collapsed = !sections[section].collapsed
// Toggle collapse
sections[section].collapsed = collapsed
header.setCollapsed(collapsed)
tableView.reloadSections(NSIndexSet(index: section) as IndexSet, with: .automatic)
if (expandedSection >= 0 && expandedSection != section){
sections[expandedSection].collapsed = true
tableView.reloadSections(NSIndexSet(index: expandedSection) as IndexSet, with: .automatic)
}
expandedSection = section;
}
The concept for all these providers is much simpler than it initially appears. If you dissect a provider you and pull out the different parts it becomes very clear.
To put it simply each one of these providers is a specialized version of the other, in this order: provider
> factory
> value
/ constant
/ service
.
So long the provider does what you can you can use the provider further down the chain which would result in writing less code. If it doesn't accomplish what you want you can go up the chain and you'll just have to write more code.
This image illustrates what I mean, in this image you will see the code for a provider, with the portions highlighted showing you which portions of the provider could be used to create a factory, value, etc instead.
(source: simplygoodcode.com)
For more details and examples from the blog post where I got the image from go to: http://www.simplygoodcode.com/2015/11/the-difference-between-service-provider-and-factory-in-angularjs/
I installed GitHubDesktop
on Windows 10 and git.exe
is located there:
C:\Users\john\AppData\Local\GitHubDesktop\app-0.7.2\resources\app\git\cmd\git.exe
At current, Android doesn't support Java 7, only Java 6. New features in Java 7 such as the diamond syntax are therefore not currently supported. Finding sources to support this isn't easy, but I could find that the Dalvic engine is built upon a subset of Apache Harmony which only ever supported Java up to version 6. And if you check the system requirements for developing Android apps it also states that at least JDK 6 is needed (though this of course isn't real proof, just an indication). And this says pretty much the same as I have. If I find anything more substancial, I'll add it.
Edit: It seems Java 7 support has been added since I originally wrote this answer; check the answer by Sergii Pechenizkyi.
Prefixing with 'r'
works very well, but it needs to be in the correct syntax. For example:
passwordFile = open(r'''C:\Users\Bob\SecretPasswordFile.txt''')
No need for \\
here - maintains readability and works well.
Ah I think a understand now. Have a look if this really is what you want:
$(".start").keyup(function(){
$(this).closest('tr').find("input").each(function() {
alert(this.value)
});
});
This will give you all input values of a row.
Update:
To get the value of not all elements you can use :not()
:
$(this).closest('tr').find("input:not([name^=desc][name^=phone])").each(function() {
alert(this.value)
});
Actually I am not 100% sure whether it works this way, maybe you have to use two not
s instead of this one combining both conditions.
#include <iostream>
#include <sstream>
std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;
while(std::getline(ss, token, ',')) {
std::cout << token << '\n';
}
abc
def
ghi
To answer the question about mappings: your provided __iter__
should iterate over the keys of the mapping. The following is a simple example that creates a mapping x -> x * x
and works on Python3 extending the ABC mapping.
import collections.abc
class MyMap(collections.abc.Mapping):
def __init__(self, n):
self.n = n
def __getitem__(self, key): # given a key, return it's value
if 0 <= key < self.n:
return key * key
else:
raise KeyError('Invalid key')
def __iter__(self): # iterate over all keys
for x in range(self.n):
yield x
def __len__(self):
return self.n
m = MyMap(5)
for k, v in m.items():
print(k, '->', v)
# 0 -> 0
# 1 -> 1
# 2 -> 4
# 3 -> 9
# 4 -> 16
If just wanted to show math in the browser for yourself, you could try the Chrome extension GitHub with MathJax. It's quite convenient.
Deleting .idea
and re-importing the SBT project solved this issue for me.
In Python3, To find the cumulative sum of a list where the i
th element
is the sum of the first i+1 elements from the original list, you may do:
a = [4 , 6 , 12]
b = []
for i in range(0,len(a)):
b.append(sum(a[:i+1]))
print(b)
OR you may use list comprehension:
b = [sum(a[:x+1]) for x in range(0,len(a))]
Output
[4,10,22]
Using replace and assigning a new df:
import pandas as pd
df = pd.DataFrame(['-',3,2,5,1,-5,-1,'-',9])
dfnew = df.replace('-', 0)
print(dfnew)
(venv) D:\assets>py teste2.py
0
0 0
1 3
2 2
3 5
4 1
5 -5
Just discovered GenMyModel, an awesome UML modeler to design class diagram online
Definitely Docker for the win!
As you may know Vagrant is for virtual machine management whereas Docker is for software containers management. If you are not aware of the difference, here is: A software container can share the same machine and kernel with other software containers. Using containers you save money because you don't waste resources on multiple operating systems (kernels), you can pack more software per server keeping a good degree of isolation.
Of course is a new discipline to care with its own pitfals and challenges.
Go for Docker Swarm if your requirements cross the single machine resources limit.
Like this:
document.getElementById('myTextarea').value = '';
or like this in jQuery:
$('#myTextarea').val('');
Where you have
<textarea id="myTextarea" name="something">This text gets removed</textarea>
For all the downvoters and non-believers:
value Property: Retrieves or sets the text in the entry field of the textArea element.
value DOMString The raw value contained in the control.
jww is right — you're referencing the wrong intermediate certificate.
As you have been issued with a SHA256 certificate, you will need the SHA256 intermediate. You can grab it from here: http://secure2.alphassl.com/cacert/gsalphasha2g2r1.crt
Read these answered questions to understand the difference between Cygwin and MinGW.
Question #1: I want to create an application that I write source code once, compile it once and run it in any platforms (e.g. Windows, Linux and Mac OS X…).
Answer #1: Write your source code in JAVA. Compile the source code once and run it anywhere.
Question #2: I want to create an application that I write source code once but there is no problem that I compile the source code for any platforms separately (e.g. Windows, Linux and Mac OS X …).
Answer #2: Write your source code in C or C++. Use standard header files only. Use a suitable compiler for any platform (e.g. Visual Studio for Windows, GCC for Linux and XCode for Mac). Note that you should not use any advanced programming features to compile your source code in all platforms successfully. If you use none C or C++ standard classes or functions, your source code does not compile in other platforms.
Question #3: In answer of question #2, it is difficult using different compiler for each platform, is there any cross platform compiler?
Answer #3: Yes, Use GCC compiler. It is a cross platform compiler. To compile your source code in Windows use MinGW that provides GCC compiler for Windows and compiles your source code to native Windows program. Do not use any advanced programming features (like Windows API) to compile your source code in all platforms successfully. If you use Windows API functions, your source code does not compile in other platforms.
Question #4: C or C++ standard header files do not provide any advanced programming features like multi-threading. What can I do?
Answer #4: You should use POSIX (Portable Operating System Interface [for UNIX]) standard. It provides many advanced programming features and tools. Many operating systems fully or partly POSIX compatible (like Mac OS X, Solaris, BSD/OS and ...). Some operating systems while not officially certified as POSIX compatible, conform in large part (like Linux, FreeBSD, OpenSolaris and ...). Cygwin provides a largely POSIX-compliant development and run-time environment for Microsoft Windows.
Thus:
The characters will get send just like that to the underlying output device (in your case probably a terminal emulator).
It is up to the terminal's implementation then how those characters get actually displayed. For example, a bell (\a
) could trigger a beep sound on some terminals, a flash of the screen on others, or it will be completely ignored. It all depends on how the terminal is configured.
You are not seeding the number.
Use This:
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand(static_cast<unsigned int>(time(0)));
cout << (rand() % 100) << endl;
return 0;
}
You only need to seed it once though. Basically don't seed it every random number.
I would suggest you to test it firstly:
copy this train.csv
to the same directory as this jupyter script in and then change the path to train.csv
to test whether this can be loaded successfully.
If yes, that means the previous path input is a problem
If not, that means the file it self denied your access to it, or its real filename can be something else like: train.csv.<hidden extension>
apparently, the GET and/or the POST variable(s) do(es) not exist. simply test if "isset". (pseudocode):
if(isset($_GET['action'];)) {$action = $_GET['action'];} else { RECOVER FROM ERROR CODE }
Your convention seems to be reasonable. If I were searching for your framework in the Maven repo, I would look for awesome-inhouse-framework-x.y.jar
in com.mycompany.awesomeinhouseframework
group directory. And I would find it there according to your convention.
Two simple rules work for me:
// On keypress event call the following method
function AlphaNumCheck(e) {
var charCode = (e.which) ? e.which : e.keyCode;
if (charCode == 8) return true;
var keynum;
var keychar;
var charcheck = /[a-zA-Z0-9]/;
if (window.event) // IE
{
keynum = e.keyCode;
}
else {
if (e.which) // Netscape/Firefox/Opera
{
keynum = e.which;
}
else return true;
}
keychar = String.fromCharCode(keynum);
return charcheck.test(keychar);
}
Further, this article also helps to understand JavaScript alphanumeric validation.
Another way you can get this linker error (as I was) is if you are exporting an instance of a class from a DLL file, but have not declared that class itself as import/export.
#ifdef MYDLL_EXPORTS
#define DLLEXPORT __declspec(dllexport)
#else
#define DLLEXPORT __declspec(dllimport)
#endif
class DLLEXPORT Book // <--- This class must also be declared as export/import
{
public:
Book();
~Book();
int WordCount();
};
DLLEXPORT extern Book book; // <-- This is what I really wanted, to export book object
So even though primarily I was exporting just an instance of the Book class called book
above, I had to declare the Book
class as export/import class as well otherwise calling book.WordCount()
in the other DLL file was causing a link error.
This happened to me. If you are using cocoapods do this:
You can use Scanner Class to find whether a given number could be read as Int or Float type.
import java.util.Scanner;
public class Test {
public static void main(String args[] ) throws Exception {
Scanner sc=new Scanner(System.in);
if(sc.hasNextInt())
System.out.println("This input is of type Integer");
else if(sc.hasNextFloat())
System.out.println("This input is of type Float");
else
System.out.println("This is something else");
}
}
Try This
/^(19[0-9]{2}|2[0-9]{3})\-(0[1-9]|1[0-2])\-(0[1-9]|1[0-9]|2[0-9]|3[0-1])((T|\s)(0[0-9]{1}|1[0-9]{1}|2[0-3]{1})\:(0[0-9]{1}|1[0-9]{1}|2[0-9]{1}|3[0-9]{1}|4[0-9]{1}|5[0-9]{1})\:(0[0-9]{1}|1[0-9]{1}|2[0-9]{1}|3[0-9]{1}|4[0-9]{1}|5[0-9]{1})((\+|\.)[\d+]{4,8})?)?$/
this regular expression valid for :
Remember that this will be cover all case of date and date time with (-) character
// date format, it will be like "2015-01-01"
private static final String DATE_FORMAT = "yyyy-MM-dd";
// convert a string to java.util.Date
public static Date convertStringToJavaDate(String date)
throws ParseException {
DateFormat dataFormat = new SimpleDateFormat(DATE_FORMAT);
return dataFormat.parse(date);
}
// plus days to a date
public static Date plusJavaDays(Date date, int days) {
// convert to jata-time
DateTime fromDate = new DateTime(date);
DateTime toDate = fromDate.plusDays(days);
// convert back to java.util.Date
return toDate.toDate();
}
// return a list of dates between the fromDate and toDate
public static List<Date> getDatesBetween(Date fromDate, Date toDate) {
List<Date> dates = new ArrayList<Date>(0);
Date date = fromDate;
while (date.before(toDate) || date.equals(toDate)) {
dates.add(date);
date = plusJavaDays(date, 1);
}
return dates;
}
Here is a Xamarin.Android version of Tom McFarlin's answer
//Determine screen size
if ((Application.Context.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeLarge) {
Toast.MakeText (this, "Large screen", ToastLength.Short).Show ();
} else if ((Application.Context.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeNormal) {
Toast.MakeText (this, "Normal screen", ToastLength.Short).Show ();
} else if ((Application.Context.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeSmall) {
Toast.MakeText (this, "Small screen", ToastLength.Short).Show ();
} else if ((Application.Context.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeXlarge) {
Toast.MakeText (this, "XLarge screen", ToastLength.Short).Show ();
} else {
Toast.MakeText (this, "Screen size is neither large, normal or small", ToastLength.Short).Show ();
}
//Determine density
DisplayMetrics metrics = new DisplayMetrics();
WindowManager.DefaultDisplay.GetMetrics (metrics);
var density = metrics.DensityDpi;
if (density == DisplayMetricsDensity.High) {
Toast.MakeText (this, "DENSITY_HIGH... Density is " + density, ToastLength.Long).Show ();
} else if (density == DisplayMetricsDensity.Medium) {
Toast.MakeText (this, "DENSITY_MEDIUM... Density is " + density, ToastLength.Long).Show ();
} else if (density == DisplayMetricsDensity.Low) {
Toast.MakeText (this, "DENSITY_LOW... Density is " + density, ToastLength.Long).Show ();
} else if (density == DisplayMetricsDensity.Xhigh) {
Toast.MakeText (this, "DENSITY_XHIGH... Density is " + density, ToastLength.Long).Show ();
} else if (density == DisplayMetricsDensity.Xxhigh) {
Toast.MakeText (this, "DENSITY_XXHIGH... Density is " + density, ToastLength.Long).Show ();
} else if (density == DisplayMetricsDensity.Xxxhigh) {
Toast.MakeText (this, "DENSITY_XXXHIGH... Density is " + density, ToastLength.Long).Show ();
} else {
Toast.MakeText (this, "Density is neither HIGH, MEDIUM OR LOW. Density is " + density, ToastLength.Long).Show ();
}
Since you're going to be dealing with data of a variable length (names, email addresses), then you'd be wanting to use VARCHAR. The amount of space taken up by a VARCHAR field is [field length]
+ 1 bytes, up to max length 255, so I wouldn't worry too much about trying to find a perfect size. Take a look at what you'd imagine might be the longest length might be, then double it and set that as your VARCHAR limit. That said...:
I generally set email fields to be VARCHAR(100) - i haven't come up with a problem from that yet. Names I set to VARCHAR(50).
As the others have said, phone numbers and zip/postal codes are not actually numeric values, they're strings containing the digits 0-9 (and sometimes more!), and therefore you should treat them as a string. VARCHAR(20) should be well sufficient.
Note that if you were to store phone numbers as integers, many systems will assume that a number starting with 0 is an octal (base 8) number! Therefore, the perfectly valid phone number "0731602412" would get put into your database as the decimal number "124192010"!!
This one is ugly, but just want to throw there some other options to the mix. This one has no loops. I use it for debugging purposes
var myObject = {a:1,b:2,c:3,d:{a:1,b:2,c:3,e:{a:1}}}
var myStrObj = JSON.stringify(myObject)
var myHtmlTableObj = myStrObj.replace(/{/g,"<table><tr><td>").replace(/:/g,"</td><td>","g").replace(/,/g,"</td></tr><tr><td>","g").replace(/}/g,"</table>")
$('#myDiv').html(myHtmlTableObj)
Example:
var myObject = {a:1,b:2,c:3,d:{a:1,b:2,c:3,e:{a:1}}}_x000D_
var myStrObj = JSON.stringify(myObject)_x000D_
var myHtmlTableObj = myStrObj.replace(/\"/g,"").replace(/{/g,"<table><tr><td>").replace(/:/g,"</td><td>","g").replace(/,/g,"</td></tr><tr><td>","g").replace(/}/g,"</table>")_x000D_
_x000D_
$('#myDiv').html(myHtmlTableObj)
_x000D_
#myDiv table td{background:whitesmoke;border:1px solid lightgray}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<div id='myDiv'>table goes here</div>
_x000D_
Without using any extra plugins,
var myOptions = {
val1 : 'text1',
val2 : 'text2'
};
var mySelect = $('#mySelect');
$.each(myOptions, function(val, text) {
mySelect.append(
$('<option></option>').val(val).html(text)
);
});
If you had lots of options, or this code needed to be run very frequently, then you should look into using a DocumentFragment instead of modifying the DOM many times unnecessarily. For only a handful of options, I'd say it's not worth it though.
------------------------------- Added --------------------------------
DocumentFragment
is good option for speed enhancement, but we cannot create option element using document.createElement('option')
since IE6 and IE7 are not supporting it.
What we can do is, create a new select element and then append all options. Once loop is finished, append it to actual DOM object.
var myOptions = {
val1 : 'text1',
val2 : 'text2'
};
var _select = $('<select>');
$.each(myOptions, function(val, text) {
_select.append(
$('<option></option>').val(val).html(text)
);
});
$('#mySelect').append(_select.html());
This way we'll modify DOM for only one time!
There is a specific property for this. It is called CharacterCasing and you could set it to Upper
TextBox1.CharacterCasing = CharacterCasing.Upper;
In ASP.NET you could try to add this to your textbox style
style="text-transform:uppercase;"
You could find an example here: http://www.w3schools.com/cssref/pr_text_text-transform.asp
Activity
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableLayout
android:id="@+id/mytable"
android:layout_width="match_parent"
android:layout_height="match_parent">
</TableLayout>
</HorizontalScrollView>
Your Class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testtable);
table = (TableLayout)findViewById(R.id.mytable);
showTableLayout();
}
public void showTableLayout(){
Date date = new Date();
int rows = 80;
int colums = 10;
table.setStretchAllColumns(true);
table.bringToFront();
for(int i = 0; i < rows; i++){
TableRow tr = new TableRow(this);
for(int j = 0; j < colums; j++)
{
TextView txtGeneric = new TextView(this);
txtGeneric.setTextSize(18);
txtGeneric.setText( dateFormat.format(date) + "\t\t\t\t" );
tr.addView(txtGeneric);
/*txtGeneric.setHeight(30); txtGeneric.setWidth(50); txtGeneric.setTextColor(Color.BLUE);*/
}
table.addView(tr);
}
}
select sys_extract_utc(systimestamp) from dual;
Won't work on Oracle 8, though.
The way to close resources are context managers, aka the with
statement:
class Foo(object):
def __init__(self):
self.bar = None
def __enter__(self):
if self.bar != 'open':
print 'opening the bar'
self.bar = 'open'
return self # this is bound to the `as` part
def close(self):
if self.bar != 'closed':
print 'closing the bar'
self.bar = 'close'
def __exit__(self, *err):
self.close()
if __name__ == '__main__':
with Foo() as foo:
print foo, foo.bar
output:
opening the bar
<__main__.Foo object at 0x17079d0> open
closing the bar
2) Python's objects get deleted when their reference count is 0. In your example the del foo
removes the last reference so __del__
is called instantly. The GC has no part in this.
class Foo(object):
def __del__(self):
print "deling", self
if __name__ == '__main__':
import gc
gc.disable() # no gc
f = Foo()
print "before"
del f # f gets deleted right away
print "after"
output:
before
deling <__main__.Foo object at 0xc49690>
after
The gc
has nothing to do with deleting your and most other objects. It's there to clean up when simple reference counting does not work, because of self-references or circular references:
class Foo(object):
def __init__(self, other=None):
# make a circular reference
self.link = other
if other is not None:
other.link = self
def __del__(self):
print "deling", self
if __name__ == '__main__':
import gc
gc.disable()
f = Foo(Foo())
print "before"
del f # nothing gets deleted here
print "after"
gc.collect()
print gc.garbage # The GC knows the two Foos are garbage, but won't delete
# them because they have a __del__ method
print "after gc"
# break up the cycle and delete the reference from gc.garbage
del gc.garbage[0].link, gc.garbage[:]
print "done"
output:
before
after
[<__main__.Foo object at 0x22ed8d0>, <__main__.Foo object at 0x22ed950>]
after gc
deling <__main__.Foo object at 0x22ed950>
deling <__main__.Foo object at 0x22ed8d0>
done
3) Lets see:
class Foo(object):
def __init__(self):
raise Exception
def __del__(self):
print "deling", self
if __name__ == '__main__':
f = Foo()
gives:
Traceback (most recent call last):
File "asd.py", line 10, in <module>
f = Foo()
File "asd.py", line 4, in __init__
raise Exception
Exception
deling <__main__.Foo object at 0xa3a910>
Objects are created with __new__
then passed to __init__
as self
. After a exception in __init__
, the object will typically not have a name (ie the f =
part isn't run) so their ref count is 0. This means that the object is deleted normally and __del__
is called.
Check if sendmail is enabled, mostly if your server is provided by another company.
"Struct pointers" aren't entities that need a naming convention clause to cover them. They're just struct WhatEver *
. DON'T hide the fact that there is a pointer involved with a clever and "obvious" typedef. It serves no purpose, is longer to type, and destroys the balance between declaration and access.
I got the same error, and fixed it with the following PHP in my back-end script:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
Following command worked for me, all the local committed changes are dropped & local is reset to the same as remote origin/master branch.
git reset --hard origin
I believe you can do this:
gem "foo", path: "/path/to/foo"
I tried following code, which works for me.
private boolean executeCommand(){
System.out.println("executeCommand");
Runtime runtime = Runtime.getRuntime();
try
{
Process mIpAddrProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int mExitValue = mIpAddrProcess.waitFor();
System.out.println(" mExitValue "+mExitValue);
if(mExitValue==0){
return true;
}else{
return false;
}
}
catch (InterruptedException ignore)
{
ignore.printStackTrace();
System.out.println(" Exception:"+ignore);
}
catch (IOException e)
{
e.printStackTrace();
System.out.println(" Exception:"+e);
}
return false;
}
This probably isn't the most elegant way to do it, but it gets the job done.
In[1]: import numpy as np
In[2]: import pandas as pd
In[3]: df = pd.DataFrame(np.genfromtxt('/Users/spencerlyon2/Desktop/test.csv', dtype=str)[1:], columns=['ID'])
In[4]: df
Out[4]:
ID
0 00013007854817840016671868
1 00013007854817840016749251
2 00013007854817840016754630
3 00013007854817840016781876
4 00013007854817840017028824
5 00013007854817840017963235
6 00013007854817840018860166
Just replace '/Users/spencerlyon2/Desktop/test.csv'
with the path to your file
Some solutions:
1 Build -> Clean Project
2 Build -> Rebuild Project
3 Built -> Make Project
4 Remove your application from device and try install again
5 Mb you have some problems with actual version of yours app(try to pull actual branch). Also you can check on your emmulator, if yours app is running.
6 Try to use 1,2,3,4 solutions.
Both the Vars() and dict methods will work for the example the OP posted, but they won't work for "loosely" defined objects like:
class foo:
a = 'foo'
b = 'bar'
To print all non-callable attributes, you can use the following function:
def printVars(object):
for i in [v for v in dir(object) if not callable(getattr(object,v))]:
print '\n%s:' % i
exec('print object.%s\n\n') % i
In case you have a BottomBar:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (mBottomBar.getCurrentTabId() == R.id.tab_more) {
getMenuInflater().inflate(R.menu.more_menu, menu);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.preferences:
startActivity(new Intent(this, PreferenceActivity.class));
break;
}
return super.onOptionsItemSelected(item);
}
Then you just need to call:
@Override
public void onBottomBarClick(int tabId) {
supportInvalidateOptionsMenu();
}
No, that is not a valid production according to the "credentials" definition in RFC 2617. You give a valid auth-scheme, but auth-param values must be of the form token "=" ( token | quoted-string )
(see section 1.2), and your example doesn't use "=" that way.
While I agree with Doug Hays' answer, I'll chime in here to say that the reason your code doesn't work is because strtotime() expects an INT as the 2nd argument, not a string (even one that represents a date)
If you turn on max error reporting you'll see this as a "A non well formed numeric value" error which is E_NOTICE level.
I did as follows and it worked: (Current date without timestamp)
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date today = dateFormat.parse(dateFormat.format(new Date()));
Found another interesting solution
SELECT salary
FROM emp
WHERE salary = (SELECT DISTINCT(salary)
FROM emp as e1
WHERE (n) = (SELECT COUNT(DISTINCT(salary))
FROM emp as e2
WHERE e1.salary <= e2.salary))
Sorry. Forgot to write. n is the nth number of salary which you want.
It's also important to realize that simply moving the program break pointer around with brk
and sbrk
doesn't actually allocate the memory, it just sets up the address space. On Linux, for example, the memory will be "backed" by actual physical pages when that address range is accessed, which will result in a page fault, and will eventually lead to the kernel calling into the page allocator to get a backing page.
I had a similar situation. Here's what I was able to do to get a date range in a "where" clause (a modification of marc_s's answer):
where cast(replace(foo.TestDate, '-', '') as datetime)
between cast('20110901' as datetime) and
cast('20510531' as datetime)
Hope that helps...
Just one more suggestion... This was caused for me by some old dll's from an MVC 3 project after upgrading to MVC 5 in the site bin folder on the deployment server. Even though these dll's were no longer used by the code base they appeared to be causing the problem. Cleaned it all out and re-deployed and it was fine.
The error message is giving you most of what you need. This isn't just about the TrustedHosts list; it's saying that in order to use an IP address with the default authentication scheme, you have to ALSO be using HTTPS (which isn't configured by default) and provide explicit credentials. I can tell you're at least not using SSL, because you didn't use the -UseSSL switch.
Note that SSL/HTTPS is not configured by default - that's an extra step you'll have to take. You can't just add -UseSSL.
The default authentication mechanism is Kerberos, and it wants to see real host names as they appear in AD. Not IP addresses, not DNS CNAME nicknames. Some folks will enable Basic authentication, which is less picky - but you should also set up HTTPS since you'd otherwise pass credentials in cleartext. Enable-PSRemoting only sets up HTTP.
Adding names to your hosts file won't work. This isn't an issue of name resolution; it's about how the mutual authentication between computers is carried out.
Additionally, if the two computers involved in this connection aren't in the same AD domain, the default authentication mechanism won't work. Read "help about_remote_troubleshooting" for information on configuring non-domain and cross-domain authentication.
From the docs at http://technet.microsoft.com/en-us/library/dd347642.aspx
HOW TO USE AN IP ADDRESS IN A REMOTE COMMAND
-----------------------------------------------------
ERROR: The WinRM client cannot process the request. If the
authentication scheme is different from Kerberos, or if the client
computer is not joined to a domain, then HTTPS transport must be used
or the destination machine must be added to the TrustedHosts
configuration setting.
The ComputerName parameters of the New-PSSession, Enter-PSSession and
Invoke-Command cmdlets accept an IP address as a valid value. However,
because Kerberos authentication does not support IP addresses, NTLM
authentication is used by default whenever you specify an IP address.
When using NTLM authentication, the following procedure is required
for remoting.
1. Configure the computer for HTTPS transport or add the IP addresses
of the remote computers to the TrustedHosts list on the local
computer.
For instructions, see "How to Add a Computer to the TrustedHosts
List" below.
2. Use the Credential parameter in all remote commands.
This is required even when you are submitting the credentials
of the current user.
Try This,It's working perfect for me,
Follow below steps:
1. Define values in .h file.
#define kNoOfColumsForCollection 3
#define kNoOfRowsForCollection 4
#define kcellSpace 5
#define kCollectionViewCellWidth (self.view.frame.size.width - kcellSpace*kNoOfColumsForCollection)/kNoOfColumsForCollection
#define kCollectionViewCellHieght (self.view.frame.size.height-40- kcellSpace*kNoOfRowsForCollection)/kNoOfRowsForCollection
OR
#define kNoOfColumsForCollection 3
#define kCollectionViewCellWidthHieght (self.view.frame.size.width - 6*kNoOfColumsForCollection)/kNoOfColumsForCollection
2.Add Code in collection View Layout data source methods as below,
#pragma mark Collection View Layout data source methods
// collection view with autolayout
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
return 4;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
return 1;
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
return UIEdgeInsetsMake(4, 4, 4, 4);
}
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return
CGSizeMake(kCollectionViewCellWidth,kCollectionViewCellHieght);
// CGSizeMake (kCollectionViewCellWidthHieght,kCollectionViewCellWidthHieght);
}
Hope this will be help for some one.
You should use apache2ctl -v or apache2 -v for newer Debian or Ubuntu distributions.
apache:/etc/apache2# apache2ctl -v
Server version: Apache/2.2.16 (Debian)
Server built: May 12 2011 11:58:18
or you can use apache2 -V to get more information.
apache2 -V
Server version: Apache/2.2.16 (Debian)
Server built: May 12 2011 11:58:18
Server's Module Magic Number: x
Server loaded: APR 1.4.2, APR-Util 1.3.9
Compiled using: APR 1.2.12, APR-Util 1.3.9
Architecture: 64-bit
Server MPM: Worker
threaded: yes (fixed thread count)
forked: yes (variable process count)
Server compiled with....
You can use a regular expression such as:
var x = "|f|oo||";
var y = x.replace(/^\|+|\|+$/g, "");
alert(y); // f|oo
UPDATE:
Should you wish to generalize this into a function, you can do the following:
var escapeRegExp = function(strToEscape) {
// Escape special characters for use in a regular expression
return strToEscape.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
};
var trimChar = function(origString, charToTrim) {
charToTrim = escapeRegExp(charToTrim);
var regEx = new RegExp("^[" + charToTrim + "]+|[" + charToTrim + "]+$", "g");
return origString.replace(regEx, "");
};
var x = "|f|oo||";
var y = trimChar(x, "|");
alert(y); // f|oo
In these two lines:
mask = cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2)
frame = cv2.circle(frame,(a, b),5,color[i].tolist(),-1)
try instead:
cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2)
cv2.circle(frame,(a, b),5,color[i].tolist(),-1)
I had the same problem and the variables were being returned empty
You can do it like this as well,
let copiedData = JSON.parse(JSON.stringify(data));
This maybe because the textview is too high. Change android:layout_height of the textview to wrap_content or use
android:gravity="center_vertical"
I was getting a similar error after moving my dev machine from Win7 32bit to Win7 64bit. Error message:
...\Web\Views\Login.cshtml: ASP.net runtime error: [A]System.Web.WebPages.Razor.Configuration.HostSection cannot be cast to [B]System.Web.WebPages.Razor.Configuration.HostSection. Type A originates from System.Web.WebPages.Razor, Version=1.0.0.0 ... Type B originates from ... Version=2.0.0.0
Turns out I had both versions in the GAC. The View web.config
referenced v1 but the app was referencing v2. Removed the referenced assemblies and re-added v1. of System.Web.WebPages.Razor
, etc.
When you open a file, the system points to the beginning of the file. Any read or write you do will happen from the beginning. A seek()
operation moves that pointer to some other part of the file so you can read or write at that place.
So, if you want to read the whole file but skip the first 20 bytes, open the file, seek(20)
to move to where you want to start reading, then continue with reading the file.
Or say you want to read every 10th byte, you could write a loop that does seek(9, 1)
(moves 9 bytes forward relative to the current positions), read(1)
(reads one byte), repeat.
If your working on embedded projects or specialized platforms static libraries are the only way to go, also many times they are less of a hassle to compile into your application. Also having projects and makefile that include everything makes life happier.
A couple other options:
Use the comma operator to create an array:
$cars = ,"bmw"
$cars.GetType().FullName
# Outputs: System.Object[]
Use array subexpression syntax:
$cars = @("bmw")
$cars.GetType().FullName
# Outputs: System.Object[]
If you don't want an object array you can downcast to the type you want e.g. a string array.
[string[]] $cars = ,"bmw"
[string[]] $cars = @("bmw")
You can have a look at Eclipse color theme, also which has a hell of a lot of options for customizing font, background color, etc.
A constexpr symbolic constant must be given a value that is known at compile time. For example:
?constexpr int max = 100;
void use(int n)
{
constexpr int c1 = max+7; // OK: c1 is 107
constexpr int c2 = n+7; // Error: we don’t know the value of c2
// ...
}
To handle cases where the value of a “variable” that is initialized with a value that is not known at compile time but never changes after initialization, C++ offers a second form of constant (a const). For Example:
?constexpr int max = 100;
void use(int n)
{
constexpr int c1 = max+7; // OK: c1 is 107
const int c2 = n+7; // OK, but don’t try to change the value of c2
// ...
c2 = 7; // error: c2 is a const
}
Such “const variables” are very common for two reasons:
Reference : "Programming: Principles and Practice Using C++" by Stroustrup
I know this is an old question, but it took me some time to sort this out given the sparse Angular documentation. The RouteProvider and routeParams is the way to go. The route wires up the URL to your Controller/View and the routeParams can be passed into the controller.
Check out the Angular seed project. Within the app.js you'll find an example for the route provider. To use params simply append them like this:
$routeProvider.when('/view1/:param1/:param2', {
templateUrl: 'partials/partial1.html',
controller: 'MyCtrl1'
});
Then in your controller inject $routeParams:
.controller('MyCtrl1', ['$scope','$routeParams', function($scope, $routeParams) {
var param1 = $routeParams.param1;
var param2 = $routeParams.param2;
...
}]);
With this approach you can use params with a url such as: "http://www.example.com/view1/param1/param2"
Reverse a String without even using a new string. Lets say
String input = "Mark Henry";
//Just to convert into char array. One can simply take input in char array.
Char[] array = input.toCharArray(input);
int a = input.length;
for(int i=0; i<(array.length/2 -1) ; i++)
{
array[i] = array[i] + array[a];
array[a] = array[i] - array[a];
array[i] = array[i] - array[a--];
}
You can also use the following code :
package com.agileinfotech.bsviewer.ldap;
import java.util.Hashtable;
import java.util.ResourceBundle;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
public class LDAPLoginAuthentication {
public LDAPLoginAuthentication() {
// TODO Auto-generated constructor
}
ResourceBundle resBundle = ResourceBundle.getBundle("settings");
@SuppressWarnings("unchecked")
public String authenticateUser(String username, String password) {
String strUrl = "success";
Hashtable env = new Hashtable(11);
boolean b = false;
String Securityprinciple = "cn=" + username + "," + resBundle.getString("UserSearch");
env.put(Context.INITIAL_CONTEXT_FACTORY, resBundle.getString("InitialContextFactory"));
env.put(Context.PROVIDER_URL, resBundle.getString("Provider_url"));
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, Securityprinciple);
env.put(Context.SECURITY_CREDENTIALS, password);
try {
// Create initial context
DirContext ctx = new InitialDirContext(env);
// Close the context when we're done
b = true;
ctx.close();
} catch (NamingException e) {
b = false;
} finally {
if (b) {
strUrl = "success";
} else {
strUrl = "failer";
}
}
return strUrl;
}
}
To answer your query on "How to convert 2.3423424666767E13 to 23423424666767"
You can use a decimal formatter for formatting decimal numbers.
double d = 2.3423424666767E13;
DecimalFormat decimalFormat = new DecimalFormat("#");
System.out.println(decimalFormat.format(d));
Output : 23423424666767
The Date object handles 8601 as it's first parameter:
var d = new Date("2014-04-07T13:58:10.104Z");_x000D_
console.log(d.toString());
_x000D_
This is based on Cmyker's update for Chart.js 2. (posted as another answer as I can't comment yet)
I had an issue with the text alignment on Chrome when the legend is displayed as the chart height does not include this so it's not aligned correctly in the middle. Fixed this by accounting for this in the calculation of fontSize and textY.
I calculated percentage inside the method rather than a set value as I have multiple of these on the page. Assumptions are that your chart only has 2 values (otherwise what is the percentage of? and that the first is the one you want to show the percentage for. I have a bunch of other charts too so I do a check for type = doughnut. I'm only using doughnuts to show percentages so it works for me.
Text color seems a bit hit and miss depending on what order things run in etc so I ran into an issue when resizing that the text would change color (between black and the primary color in one case, and secondary color and white in another) so I "save" whatever the existing fill style was, draw the text (in the color of the primary data) then restore the old fill style. (Preserving the old fill style doesn't seem needed but you never know.)
https://jsfiddle.net/g733tj8h/
Chart.pluginService.register({
beforeDraw: function(chart) {
var width = chart.chart.width,
height = chart.chart.height,
ctx = chart.chart.ctx,
type = chart.config.type;
if (type == 'doughnut')
{
var percent = Math.round((chart.config.data.datasets[0].data[0] * 100) /
(chart.config.data.datasets[0].data[0] +
chart.config.data.datasets[0].data[1]));
var oldFill = ctx.fillStyle;
var fontSize = ((height - chart.chartArea.top) / 100).toFixed(2);
ctx.restore();
ctx.font = fontSize + "em sans-serif";
ctx.textBaseline = "middle"
var text = percent + "%",
textX = Math.round((width - ctx.measureText(text).width) / 2),
textY = (height + chart.chartArea.top) / 2;
ctx.fillStyle = chart.config.data.datasets[0].backgroundColor[0];
ctx.fillText(text, textX, textY);
ctx.fillStyle = oldFill;
ctx.save();
}
}
});
var data = {_x000D_
labels: ["Red","Blue"],_x000D_
datasets: [_x000D_
{_x000D_
data: [300, 50],_x000D_
backgroundColor: ["#FF6384","#36A2EB"],_x000D_
}]_x000D_
};_x000D_
_x000D_
Chart.pluginService.register({_x000D_
beforeDraw: function(chart) {_x000D_
var width = chart.chart.width,_x000D_
height = chart.chart.height,_x000D_
ctx = chart.chart.ctx,_x000D_
type = chart.config.type;_x000D_
_x000D_
if (type == 'doughnut')_x000D_
{_x000D_
var percent = Math.round((chart.config.data.datasets[0].data[0] * 100) /_x000D_
(chart.config.data.datasets[0].data[0] +_x000D_
chart.config.data.datasets[0].data[1]));_x000D_
var oldFill = ctx.fillStyle;_x000D_
var fontSize = ((height - chart.chartArea.top) / 100).toFixed(2);_x000D_
_x000D_
ctx.restore();_x000D_
ctx.font = fontSize + "em sans-serif";_x000D_
ctx.textBaseline = "middle"_x000D_
_x000D_
var text = percent + "%",_x000D_
textX = Math.round((width - ctx.measureText(text).width) / 2),_x000D_
textY = (height + chart.chartArea.top) / 2;_x000D_
_x000D_
ctx.fillStyle = chart.config.data.datasets[0].backgroundColor[0];_x000D_
ctx.fillText(text, textX, textY);_x000D_
ctx.fillStyle = oldFill;_x000D_
ctx.save();_x000D_
}_x000D_
}_x000D_
});_x000D_
_x000D_
var myChart = new Chart(document.getElementById('myChart'), {_x000D_
type: 'doughnut',_x000D_
data: data,_x000D_
options: {_x000D_
responsive: true,_x000D_
legend: {_x000D_
display: true_x000D_
}_x000D_
}_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.bundle.js"></script>_x000D_
<canvas id="myChart"></canvas>
_x000D_
You can add the id="MyID123"
at the start of the cartHTML text appends.
The first line would therefore be:
var cartHTML = '<div id="MyID123" class="soft_add_wrapper" onmouseover="setTimer();">';
-OR-
If you want the ID to be in a variable, then something like this:
var MyIDvariable = "MyID123";
var cartHTML = '<div id="'+MyIDvariable+'" class="soft_add_wrapper" onmouseover="setTimer();">';
/* ... the rest of your code ... */