For InstallShield MSI based projects I have found the following to work:
setup.exe /s /x /b"C:\FolderInWhichMSIWillBeExtracted" /v"/qn"
This command will lead to an extracted MSI in a directory you can freely specify and a silently failed uninstall of the product.
The command line basically tells the setup.exe to attempt to uninstall the product (/x) and do so silently (/s). While doing that it should extract the MSI to a specific location (/b).
The /v command passes arguments to Windows Installer, in this case the /qn argument. The /qn argument disables any GUI output of the installer.
There's no supported way to do this, but won't you have to examine the files related to each installer to figure out how to actually install them after extracting them? Assuming you can spend the time to figure out which command-line applies, here are some candidate parameters that normally allow you to extract an installation.
MSI Based (may not result in a usable image for an InstallScript MSI installation):
setup.exe /a /s /v"/qn TARGETDIR=\"choose-a-location\""
or, to also extract prerequisites (for versions where it works),
setup.exe /a"choose-another-location" /s /v"/qn TARGETDIR=\"choose-a-location\""
InstallScript based:
setup.exe /s /extract_all
Suite based (may not be obvious how to install the resulting files):
setup.exe /silent /stage_only ISRootStagePath="choose-a-location"
if you are using visual studio , enable the build property "Prefer 32-bit". see image below.
Here's a workaround for installing the 64-bit version of the Microsoft Access Database Engine 2010 redistributable on a system with a 32-bit MS Office version installed:
Now you can start a 32-bit MS Office application without the "re-configuring" issue. Note that the "mso.dll" registry value will already be present if a 64-bit version of MS Office is installed. In this case the value should not be deleted or renamed.
Also if you do not want to use the "/passive" command line parameter you can edit the AceRedist.msi file to remove the MS Office architecture check:
You can now use this file to install the Microsoft Access Database Engine 2010 redistributable on a system where a "conflicting" version of MS Office is installed (e.g. 64-bit version on system with 32-bit MS Office version) Make sure that you rename the "mso.dll" registry value as explained above (if needed).
Looking at the code (runner/__init__.py
), I think you can probably set it in your inventory file :
[whatever]
some-host ansible_sudo_pass='foobar'
There seem to be some provision in ansible.cfg
config file too, but not implemented right now (constants.py
).
That is because the words are wrapping and are going on new lines hence stretching the TR. This should fix your problem:
overflow:hidden;
Put that in the TR styles Although it should work, why not just let it stretch o0
PS. i aint tested it so dont hate XD
You can send email without Outlook in VBScript using the CDO.Message object. You will need to know the address of your SMTP server to use this:
Set MyEmail=CreateObject("CDO.Message")
MyEmail.Subject="Subject"
MyEmail.From="[email protected]"
MyEmail.To="[email protected]"
MyEmail.TextBody="Testing one two three."
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing")=2
'SMTP Server
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.server.com"
'SMTP Port
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25
MyEmail.Configuration.Fields.Update
MyEmail.Send
set MyEmail=nothing
If your SMTP server requires a username and password then paste these lines in above the MyEmail.Configuration.Fields.Update
line:
'SMTP Auth (For Windows Auth set this to 2)
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")=1
'Username
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername")="username"
'Password
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword")="password"
More information on using CDO to send email with VBScript can be found on the link below: http://www.paulsadowski.com/wsh/cdo.htm
The else:
statement is executed when and only when the while loop no longer meets its condition (in your example, when n != 0
is false).
So the output would be this:
5
4
3
2
1
what the...
In ASP.NET MVC 3 Preview1 you can import a namespace on all your razor views with this code in Global.asax.cs
Microsoft.WebPages.Compilation.CodeGeneratorSettings.AddGlobalImport("Namespace.Namespace");
I hope in RTM this gets done through Web.config section.
you can try
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader("<root><node1></node1></root>"));
Document doc = db.parse(is);
refer this http://www.java2s.com/Code/Java/XML/ParseanXMLstringUsingDOMandaStringReader.htm
You have to perform following steps to do this, which are as follows
Map your domain upto public folder of your project (i.e. /var/www/html/yourproject/public) (if using linux)
Go to your public folder edit your .htaccess
file there
AddHandler application/x-httpd-php72 .php
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect non-www to www
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Redirect non-http to https
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
# Remove index.php
RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]
</IfModule>
https
, it protect that.The problem will be that you cannot represent 0.575 exactly as a binary floating point number (eg a double). Though I don't know exactly it seems that the representation closest is probably just a bit lower and so when rounding it uses the true representation and rounds down.
If you want to avoid this problem then use a more appropriate data type. decimal
will do what you want:
Math.Round(0.575M, 2, MidpointRounding.AwayFromZero)
Result: 0.58
The reason that 0.75 does the right thing is that it is easy to represent in binary floating point since it is simple 1/2 + 1/4 (ie 2^-1 +2^-2). In general any finite sum of powers of two can be represented in binary floating point. Exceptions are when your powers of 2 span too great a range (eg 2^100+2 is not exactly representable).
Edit to add:
Formatting doubles for output in C# might be of interest in terms of understanding why its so hard to understand that 0.575 is not really 0.575. The DoubleConverter in the accepted answer will show that 0.575 as an Exact String is 0.5749999999999999555910790149937383830547332763671875
You can see from this why rounding give 0.57.
$ThatTime ="14:08:10";
if (time() >= strtotime($ThatTime)) {
echo "ok";
}
A solution using DateTime
(that also regards the timezone).
$dateTime = new DateTime($ThatTime);
if ($dateTime->diff(new DateTime)->format('%R') == '+') {
echo "OK";
}
The max length of a varchar is
65535
divided by the max byte length of a character in the character set the column is set to (e.g. utf8=3 bytes, ucs2=2, latin1=1).
minus 2 bytes to store the length
minus the length of all the other columns
minus 1 byte for every 8 columns that are nullable. If your column is null/not null this gets stored as one bit in a byte/bytes called the null mask, 1 bit per column that is nullable.
You could always add to the original .show() method so you don't have to trigger events every time you show something or if you need it to work with legacy code:
jQuery(function($) {
var _oldShow = $.fn.show;
$.fn.show = function(speed, oldCallback) {
return $(this).each(function() {
var obj = $(this),
newCallback = function() {
if ($.isFunction(oldCallback)) {
oldCallback.apply(obj);
}
obj.trigger('afterShow');
};
// you can trigger a before show if you want
obj.trigger('beforeShow');
// now use the old function to show the element passing the new callback
_oldShow.apply(obj, [speed, newCallback]);
});
}
});
jQuery(function($) {
$('#test')
.bind('beforeShow', function() {
alert('beforeShow');
})
.bind('afterShow', function() {
alert('afterShow');
})
.show(1000, function() {
alert('in show callback');
})
.show();
});
This effectively lets you do something beforeShow and afterShow while still executing the normal behavior of the original .show() method.
You could also create another method so you don't have to override the original .show() method.
In a situation where you have this:
enum fruit {
apple,
orange,
grape,
banana,
// etc.
};
I like to put this in the header file where the enum is defined:
static inline char *stringFromFruit(enum fruit f)
{
static const char *strings[] = { "apple", "orange", "grape", "banana", /* continue for rest of values */ };
return strings[f];
}
A solution where the logo is truly centered and the links are justified.
The max recommended number of links for the nav is 6, depending on the length of the words in eache link.
If you have 5 links, insert an empty link and style it with:
class="hidden-xs" style="visibility: hidden;"
in this way the number of links is always even.
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<style>_x000D_
.navbar-nav > li {_x000D_
float: none;_x000D_
vertical-align: bottom;_x000D_
}_x000D_
#site-logo {_x000D_
position: relative;_x000D_
vertical-align: bottom;_x000D_
bottom: -35px;_x000D_
}_x000D_
#site-logo a {_x000D_
margin-top: -53px;_x000D_
}_x000D_
</style>_x000D_
<nav class="navbar navbar-default navbar-fixed-top">_x000D_
<div class="container">_x000D_
<div class="navbar-header">_x000D_
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">_x000D_
<span class="sr-only">Nav</span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
</button>_x000D_
</div>_x000D_
<div id="navbar" class="collapse navbar-collapse">_x000D_
<ul class="nav nav-justified navbar-nav center-block">_x000D_
<li class="active"><a href="#">First Link</a></li>_x000D_
<li><a href="#">Second Link</a></li>_x000D_
<li><a href="#">Third Link</a></li>_x000D_
<li id="site-logo" class="hidden-xs"><a href="#"><img id="logo-navbar-middle" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/32877/logo-thing.png" width="200" alt="Logo Thing main logo"></a></li>_x000D_
<li><a href="#">Fourth Link</a></li>_x000D_
<li><a href="#">Fifth Link</a></li>_x000D_
<li class="hidden-xs" style="visibility: hidden;"><a href="#">Sixth Link</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
</nav>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>_x000D_
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
_x000D_
To see result click on run snippet and then full page
The problem is that you're not initializing the pointer. You've created a pointer to "anywhere you want"—which could be the address of some other variable, or the middle of your code, or some memory that isn't mapped at all.
You need to create an int
variable somewhere in memory for the int *
variable to point at.
Your second example does this, but it does other things that aren't relevant here. Here's the simplest thing you need to do:
int main(){
int variable;
int *ptr = &variable;
*ptr = 20;
printf("%d", *ptr);
return 0;
}
Here, the int
variable isn't initialized—but that's fine, because you're just going to replace whatever value was there with 20
. The key is that the pointer is initialized to point to the variable
. In fact, you could just allocate some raw memory to point to, if you want:
int main(){
void *memory = malloc(sizeof(int));
int *ptr = (int *)memory;
*ptr = 20;
printf("%d", *ptr);
free(memory);
return 0;
}
Let a
be a string and b
the string you look for. Use a.substr
to get the last n characters of a
and compare them to b (where n is the length of b
)
Or use std::equal
(include <algorithm>
)
Ex:
bool EndsWith(const string& a, const string& b) {
if (b.size() > a.size()) return false;
return std::equal(a.begin() + a.size() - b.size(), a.end(), b.begin());
}
If you also want to keep hash and get parameter, you can do something like this (fill redirectMap at filter init):
String uri = request.getRequestURI();
String[] uriParts = uri.split("[#?]");
String path = uriParts[0];
String rest = uri.substring(uriParts[0].length());
if(redirectMap.containsKey(path)) {
response.sendRedirect(redirectMap.get(path) + rest);
} else {
chain.doFilter(request, response);
}
You use std::find
from <algorithm>
, which works equally well for std::list
and std::vector
. std::vector
does not have its own search/find function.
#include <list>
#include <algorithm>
int main()
{
std::list<int> ilist;
ilist.push_back(1);
ilist.push_back(2);
ilist.push_back(3);
std::list<int>::iterator findIter = std::find(ilist.begin(), ilist.end(), 1);
}
Note that this works for built-in types like int
as well as standard library types like std::string
by default because they have operator==
provided for them. If you are using using std::find
on a container of a user-defined type, you should overload operator==
to allow std::find
to work properly: EqualityComparable
concept
just in case you are using a remote access and want to dump all database data, you can use:
pg_dump -a -h your_host -U your_user -W -Fc your_database > DATA.dump
it will create a dump with all database data and use
pg_restore -a -h your_host -U your_user -W -Fc your_database < DATA.dump
to insert the same data in your data base considering you have the same structure
One point is that it may be easier to do:
$("<div class=foo id=bar style='color:white;bgcolor:blue;font-size:12pt'></div>")
Then to do all of that with jquery calls.
To add the privileges needed to the files add and grant right to the following local user: SQLServerMSSQLUser$COMPUTERNAME$INSTANCENAME, where COMPUTERNAME and INSTANCENAME has to be replaced with name of computer and MSSQL instance respectively.
These are all great suggestions, but if I were you, I would do this in your view model. Within your view model, you can create a relay command that you can then bind to the click event in your item template. To determine if the same item was selected, you can store a reference to your selected item in your view model. I like to use MVVM Light to handle the binding. This makes your project much easier to modify in the future, and allows you to set the binding in Blend.
When all is said and done, your XAML will look like what Sergey suggested. I would avoid using the code behind in your view. I'm going to avoid writing code in this answer, because there is a ton of examples out there.
Here is one: How to use RelayCommand with the MVVM Light framework
If you require an example, please comment, and I will add one.
~Cheers
I said I wasn't going to do an example, but I am. Here you go.
1) In your project, add MVVM Light Libraries Only.
2) Create a class for your view. Generally speaking, you have a view model for each view (view: MainWindow.xaml && viewModel: MainWindowViewModel.cs)
3) Here is the code for the very, very, very basic view model:
All included namespace (if they show up here, I am assuming you already added the reference to them. MVVM Light is in Nuget)
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
Now add a basic public class:
/// <summary>
/// Very basic model for example
/// </summary>
public class BasicModel
{
public string Id { get; set; }
public string Text { get; set; }
/// <summary>
/// Constructor
/// </summary>
/// <param name="text"></param>
public BasicModel(string text)
{
this.Id = Guid.NewGuid().ToString();
this.Text = text;
}
}
Now create your viewmodel:
public class MainWindowViewModel : ViewModelBase
{
public MainWindowViewModel()
{
ModelsCollection = new ObservableCollection<BasicModel>(new List<BasicModel>() {
new BasicModel("Model one")
, new BasicModel("Model two")
, new BasicModel("Model three")
});
}
private BasicModel _selectedBasicModel;
/// <summary>
/// Stores the selected mode.
/// </summary>
/// <remarks>This is just an example, may be different.</remarks>
public BasicModel SelectedBasicModel
{
get { return _selectedBasicModel; }
set { Set(() => SelectedBasicModel, ref _selectedBasicModel, value); }
}
private ObservableCollection<BasicModel> _modelsCollection;
/// <summary>
/// List to bind to
/// </summary>
public ObservableCollection<BasicModel> ModelsCollection
{
get { return _modelsCollection; }
set { Set(() => ModelsCollection, ref _modelsCollection, value); }
}
}
In your viewmodel, add a relaycommand. Please note, I made this async and had it pass a parameter.
private RelayCommand<string> _selectItemRelayCommand;
/// <summary>
/// Relay command associated with the selection of an item in the observablecollection
/// </summary>
public RelayCommand<string> SelectItemRelayCommand
{
get
{
if (_selectItemRelayCommand == null)
{
_selectItemRelayCommand = new RelayCommand<string>(async (id) =>
{
await selectItem(id);
});
}
return _selectItemRelayCommand;
}
set { _selectItemRelayCommand = value; }
}
/// <summary>
/// I went with async in case you sub is a long task, and you don't want to lock you UI
/// </summary>
/// <returns></returns>
private async Task<int> selectItem(string id)
{
this.SelectedBasicModel = ModelsCollection.FirstOrDefault(x => x.Id == id);
Console.WriteLine(String.Concat("You just clicked:", SelectedBasicModel.Text));
//Do async work
return await Task.FromResult(1);
}
In the code behind for you view, create a property for you viewmodel and set the datacontext for your view to the viewmodel (please note, there are other ways to do this, but I am trying to make this a simple example.)
public partial class MainWindow : Window
{
public MainWindowViewModel MyViewModel { get; set; }
public MainWindow()
{
InitializeComponent();
MyViewModel = new MainWindowViewModel();
this.DataContext = MyViewModel;
}
}
In your XAML, you need to add some namespaces to the top of your code
<Window x:Class="Basic_Binding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:Custom="clr-namespace:GalaSoft.MvvmLight;assembly=GalaSoft.MvvmLight"
Title="MainWindow" Height="350" Width="525">
I added "i" and "Custom."
Here is the ListView:
<ListView
Grid.Row="0"
Grid.Column="0"
HorizontalContentAlignment="Stretch"
ItemsSource="{Binding ModelsCollection}"
ItemTemplate="{DynamicResource BasicModelDataTemplate}">
</ListView>
Here is the ItemTemplate for the ListView:
<DataTemplate x:Key="BasicModelDataTemplate">
<Grid>
<TextBlock Text="{Binding Text}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseLeftButtonUp">
<i:InvokeCommandAction
Command="{Binding DataContext.SelectItemRelayCommand,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ItemsControl}}}"
CommandParameter="{Binding Id}">
</i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBlock>
</Grid>
</DataTemplate>
Run your application, and check out the output window. You can use a converter to handle the styling of the selected item.
This may seem really complicated, but it makes life a lot easier down the road when you need to separate your view from your ViewModel (e.g. develop a ViewModel for multiple platforms.) Additionally, it makes working in Blend 10x easier. Once you develop your ViewModel, you can hand it over to a designer who can make it look very artsy :). MVVM Light adds some functionality to make Blend recognize your ViewModel. For the most part, you can do just about everything you want to in the ViewModel to affect the view.
If anyone reads this, I hope you find this helpful. If you have questions, please let me know. I used MVVM Light in this example, but you could do this without MVVM Light.
~Cheers
I found a solution that adds columns at runtime, and binds to a DataTable
.
Unfortunately, with 47 columns defined this way, it doesn't bind to the data fast enough for me. Any suggestions?
xaml
<DataGrid
Name="dataGrid"
AutoGenerateColumns="False"
ItemsSource="{Binding}">
</DataGrid>
xaml.cs using System.Windows.Data;
if (table != null) // table is a DataTable
{
foreach (DataColumn col in table.Columns)
{
dataGrid.Columns.Add(
new DataGridTextColumn
{
Header = col.ColumnName,
Binding = new Binding(string.Format("[{0}]", col.ColumnName))
});
}
dataGrid.DataContext = table;
}
Try below code:
$(document).ready(function(){
$('#about').css({'background-color':'black'});
});
If you will never need to serialize your objects to byte array and send/store them, then you don't need to worry about it. If you do, then you must consider your serialVersionUID since the deserializer of the object will match it to the version of object its classloader has. Read more about it in the Java Language Specification.
Check this link.. It will definitely solve your problem.. There are plenty of solutions to make cross domain GET Ajax calls BUT POST REQUEST FOR CROSS DOMAIN IS SOLVED HERE. It took me 3 days to figure it out.
There is no way to update an existing ADT bundle that you might have downloaded.
You can do one of two options:
Install Eclipse from eclipse.org and install ADT by pointing to the update site: https://dl-ssl.google.com/android/eclipse
Download bundles from:
Linux 64 bit VM: http://dl.google.com/android/adt/adt-bundle-linux-x86_64-20140702.zip
Linux 32 bit VM: http://dl.google.com/android/adt/adt-bundle-linux-x86-20140702.zip
Mac: http://dl.google.com/android/adt/adt-bundle-mac-x86_64-20140702.zip
Windows 32 bit: http://dl.google.com/android/adt/adt-bundle-windows-x86-20140702.zip
Windows 64 bit: http://dl.google.com/android/adt/adt-bundle-windows-x86_64-20140702.zip
Starting with ADT bundle 23.0.2, you should be able to update to future versions of ADT.
The almighty switch
works well here:
'one
two
three' > file
$regex = '^t'
switch -regex -file file {
$regex { "line is $_" }
}
Output:
line is two
line is three
I would normally go for .loc/.iloc
as suggested by Ted, but one may also select a row by tranposing the DataFrame. To stay in the example above, df.T[2]
gives you row 2 of df
.
Remember that, converting from List to Set will remove duplicates from collection because List supports duplicates but Set does not support duplicates in Java.
Direct Conversion : The most common and simple way to convert a List to a Set
// Creating a list of strings
List<String> list = Arrays.asList("One", "Two", "Three", "Four");
// Converting a list to set
Set<String> set = new HashSet<>(list);
Apache Commons Collections : You may also use the Commons Collections API to convert a List to a Set :-
// Creating a list of strings
List<String> list = Arrays.asList("One", "Two", "Three", "Four");
// Creating a set with the same number of members in the list
Set<String> set = new HashSet<>(4);
// Adds all of the elements in the list to the target set
CollectionUtils.addAll(set, list);
Using Stream : Another way is to convert given list to stream, then stream to set :-
// Creating a list of strings
List<String> list = Arrays.asList("One", "Two", "Three", "Four");
// Converting to set using stream
Set<String> set = list.stream().collect(Collectors.toSet());
I got this error because I was doing File.Move to a file path without a file name, need to specify the full path in the destination.
Why would we want to check if an array is empty
? Arrays don't grow or shrink in the same that lists do. Starting with a 'empty' array, and growing with np.append
is a frequent novice error.
Using a list in if alist:
hinges on its boolean value:
In [102]: bool([])
Out[102]: False
In [103]: bool([1])
Out[103]: True
But trying to do the same with an array produces (in version 1.18):
In [104]: bool(np.array([]))
/usr/local/bin/ipython3:1: DeprecationWarning: The truth value
of an empty array is ambiguous. Returning False, but in
future this will result in an error. Use `array.size > 0` to
check that an array is not empty.
#!/usr/bin/python3
Out[104]: False
In [105]: bool(np.array([1]))
Out[105]: True
and bool(np.array([1,2])
produces the infamous ambiguity error.
The accepted answer suggests size
:
In [11]: x = np.array([])
In [12]: x.size
Out[12]: 0
But I (and most others) check the shape
more than the size
:
In [13]: x.shape
Out[13]: (0,)
Another thing in its favor is that it 'maps' on to an empty
list:
In [14]: x.tolist()
Out[14]: []
But there are other other arrays with 0 size
, that aren't 'empty' in that last sense:
In [15]: x = np.array([[]])
In [16]: x.size
Out[16]: 0
In [17]: x.shape
Out[17]: (1, 0)
In [18]: x.tolist()
Out[18]: [[]]
In [19]: bool(x.tolist())
Out[19]: True
np.array([[],[]])
is also size 0, but shape (2,0) and len
2.
While the concept of an empty
list is well defined, an empty array
is not well defined. One empty list is equal to another. The same can't be said for a size 0
array.
The answer really depends on
You can try this way:
open('u.item', encoding='utf8', errors='ignore')
This is what the code would look like in a batch file(tested, works):
powershell -Command "& {set-location 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'; set-location ZoneMap\Domains; new-item SERVERNAME; set-location SERVERNAME; new-itemproperty . -Name http -Value 2 -Type DWORD;}"
Based on the information from:
http://dmitrysotnikov.wordpress.com/2008/06/27/powershell-script-in-a-bat-file/
The main differenece is that bidirectional relationship provides navigational access in both directions, so that you can access the other side without explicit queries. Also it allows you to apply cascading options to both directions.
Note that navigational access is not always good, especially for "one-to-very-many" and "many-to-very-many" relationships. Imagine a Group
that contains thousands of User
s:
How would you access them? With so many User
s, you usually need to apply some filtering and/or pagination, so that you need to execute a query anyway (unless you use collection filtering, which looks like a hack for me). Some developers may tend to apply filtering in memory in such cases, which is obviously not good for performance. Note that having such a relationship can encourage this kind of developers to use it without considering performance implications.
How would you add new User
s to the Group
? Fortunately, Hibernate looks at the owning side of relationship when persisting it, so you can only set User.group
. However, if you want to keep objects in memory consistent, you also need to add User
to Group.users
. But it would make Hibernate to fetch all elements of Group.users
from the database!
So, I can't agree with the recommendation from the Best Practices. You need to design bidirectional relationships carefully, considering use cases (do you need navigational access in both directions?) and possible performance implications.
See also:
For example, if you want to change com.example.app
to my.awesome.game
, then:
In your Project pane, click on the little gear icon ( )
Uncheck the Compact Empty Middle Packages
option
Your package directory will now be broken up into individual directories
Individually select each directory you want to rename, and:
Right-click it
Select Refactor
Click on Rename
In the pop-up dialog, click on Rename Package
instead of Rename Directory
Enter the new name and hit Refactor
Click Do Refactor in the bottom
Allow a minute to let Android Studio update all changes
Note: When renaming com
in Android Studio, it might give a warning. In such case, select Rename All
Now open your Gradle Build File (build.gradle
- Usually app
or mobile
). Update the applicationId
in the defaultConfig
to your new Package Name and Sync Gradle, if it hasn't already been updated automatically:
You may need to change the package=
attribute in your manifest.
Clean and Rebuild.
Done! Anyway, Android Studio needs to make this process a little simpler.
You could use ob_start();
before you send any output. This will tell to PHP to keep all the output in a buffer until the script execution ends, so you still can change the header.
Usually I don't use output buffering, for simple projects I keep all the logic on the first part of my script, then I output all HTML
.
We can do like below:
const item= {
image: require("../../assets/dashboard/project1.jpeg"),
location: "Chennai",
status: 1,
projectId: 1
}
<Image source={item.image} style={[{ width: 150, height: 150}]} />
Final conclusion: arithmetic on a void*
is illegal in both C and C++.
GCC allows it as an extension, see Arithmetic on void
- and Function-Pointers (note that this section is part of the "C Extensions" chapter of the manual). Clang and ICC likely allow void*
arithmetic for the purposes of compatibility with GCC. Other compilers (such as MSVC) disallow arithmetic on void*
, and GCC disallows it if the -pedantic-errors
flag is specified, or if the -Werror-pointer-arith
flag is specified (this flag is useful if your code base must also compile with MSVC).
Quotes are taken from the n1256 draft.
The standard's description of the addition operation states:
6.5.6-2: For addition, either both operands shall have arithmetic type, or one operand shall be a pointer to an object type and the other shall have integer type.
So, the question here is whether void*
is a pointer to an "object type", or equivalently, whether void
is an "object type". The definition for "object type" is:
6.2.5.1: Types are partitioned into object types (types that fully describe objects) , function types (types that describe functions), and incomplete types (types that describe objects but lack information needed to determine their sizes).
And the standard defines void
as:
6.2.5-19: The
void
type comprises an empty set of values; it is an incomplete type that cannot be completed.
Since void
is an incomplete type, it is not an object type. Therefore it is not a valid operand to an addition operation.
Therefore you cannot perform pointer arithmetic on a void
pointer.
Originally, it was thought that void*
arithmetic was permitted, because of these sections of the C standard:
6.2.5-27: A pointer to void shall have the same representation and alignment requirements as a pointer to a character type.
However,
The same representation and alignment requirements are meant to imply interchangeability as arguments to functions, return values from functions, and members of unions.
So this means that printf("%s", x)
has the same meaning whether x
has type char*
or void*
, but it does not mean that you can do arithmetic on a void*
.
Editor's note: This answer has been edited to reflect the final conclusion.
<form method="POST" action="chk_kw.php">
<select name="website_string">
<option selected="selected"></option>
<option value="abc">abc</option>
<option value="def">def</option>
<option value="hij">hij</option>
</select>
<input type="submit">
</form>
print_r($_POST);
,
it'll show what's being submitted an the respective element name.To get the submitted value of the element in question do:
$website_string = $_POST['website_string'];
Maybe you can try something like this:
Using a directive
directive('watchChange', function() {
return {
scope: {
onchange: '&watchChange'
},
link: function(scope, element, attrs) {
element.on('input', function() {
scope.onchange();
});
}
};
});
Where you have written the code
public class Main {
public static void main(String args[])
{
Calculate obj = new Calculate(1,2,'+');
obj.getAnswer();
}
}
Here you have to run the class "Main" instead of the class you created at the start of the program. To do so pls go to Run Configuration and search for this class name"Main" which is having the main method inside this(public static void main(String args[])). And you will get your output.
I suggest using concat()
if you are using nodeJS. In all other cases, I have found that slice(0)
works fine.
Because (a.y - b.y) is probably less then (a.x - b.x) and in your code the casting is done after the divide operation so the result is an integer so 0.
You should cast to float before the / operation
Vadim Shender response is great. You can also use a simpler decorator like below:
import datetime
def calc_timing(original_function):
def new_function(*args,**kwargs):
start = datetime.datetime.now()
x = original_function(*args,**kwargs)
elapsed = datetime.datetime.now()
print("Elapsed Time = {0}".format(elapsed-start))
return x
return new_function()
@calc_timing
def a_func(*variables):
print("do something big!")
just use onkeypress event like below:
<input type="text" name="onlyalphabet" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)">
There is a computer vision package called HALCON from MVTec whose demos could give you good algorithm ideas. There is plenty of examples similar to your problem that you could run in demo mode and then look at the operators in the code and see how to implement them from existing OpenCV operators.
I have used this package to quickly prototype complex algorithms for problems like this and then find how to implement them using existing OpenCV features. In particular for your case you could try to implement in OpenCV the functionality embedded in the operator find_scaled_shape_model. Some operators point to the scientific paper regarding algorithm implementation which can help to find out how to do something similar in OpenCV. Hope this helps...
I am using such code in config.php:
$lang = 'ru'; // this language will be used if there is no any lang information from useragent (for example, from command line, wget, etc...
if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'],0,2);
$tmp_value = $_COOKIE['language'];
if (!empty($tmp_value)) $lang = $tmp_value;
switch ($lang)
{
case 'ru':
$config['language'] = 'russian';
setlocale(LC_ALL,'ru_RU.UTF-8');
break;
case 'uk':
$config['language'] = 'ukrainian';
setlocale(LC_ALL,'uk_UA.UTF-8');
break;
case 'foo':
$config['language'] = 'foo';
setlocale(LC_ALL,'foo_FOO.UTF-8');
break;
default:
$config['language'] = 'english';
setlocale(LC_ALL,'en_US.UTF-8');
break;
}
.... and then i'm using usualy internal mechanizm of CI
o, almost forget! in views i using buttons, which seting cookie 'language' with language, prefered by user.
So, first this code try to detect "preffered language" setted in user`s useragent (browser). Then code try to read cookie 'language'. And finaly - switch sets language for CI-application
/* 1 */ Foo* foo1 = new Foo ();
Creates an object of type Foo
in dynamic memory. foo1
points to it. Normally, you wouldn't use raw pointers in C++, but rather a smart pointer. If Foo
was a POD-type, this would perform value-initialization (it doesn't apply here).
/* 2 */ Foo* foo2 = new Foo;
Identical to before, because Foo
is not a POD type.
/* 3 */ Foo foo3;
Creates a Foo
object called foo3
in automatic storage.
/* 4 */ Foo foo4 = Foo::Foo();
Uses copy-initialization to create a Foo
object called foo4
in automatic storage.
/* 5 */ Bar* bar1 = new Bar ( *new Foo() );
Uses Bar
's conversion constructor to create an object of type Bar
in dynamic storage. bar1
is a pointer to it.
/* 6 */ Bar* bar2 = new Bar ( *new Foo );
Same as before.
/* 7 */ Bar* bar3 = new Bar ( Foo foo5 );
This is just invalid syntax. You can't declare a variable there.
/* 8 */ Bar* bar3 = new Bar ( Foo::Foo() );
Would work and work by the same principle to 5 and 6 if bar3
wasn't declared on in 7.
5 & 6 contain memory leaks.
Syntax like new Bar ( Foo::Foo() );
is not usual. It's usually new Bar ( (Foo()) );
- extra parenthesis account for most-vexing parse. (corrected)
I'll throw jsTree into the ring, too. I've found it fairly adaptable to your particular situation. It's packed as a jQuery plugin.
It can run from a variety of data sources, but my favorite is a simple nested list, as described by @joe_coolish or here:
<ul>
<li>
Item 1
<ul>
<li>Item 1.1</li>
...
</ul>
</li>
...
</ul>
This structure fails gracefully into a static tree when JS is not available in the client, and is easy enough to read and understand from a coding perspective.
A belated post:
Use the search regex pattern as a Record Separator (RS) in awk
This allows your regex to span \n
-delimited lines (if you need it).
printf 'X \n moo X\n XX\n' |
awk -vRS='X[^X]*X' 'END{print (NR<2?0:NR-1)}'
Something like this should resolve the issue..
Vue.component(
'example-component',
require('./components/ExampleComponent.vue').default);
wget -S -O - http://google.com
works as expected for me, but with a caveat: the headers are considered debugging information and as such they are sent to the standard error rather than the standard output. If you are redirecting the standard output to a file or another process, you will only get the document contents.
You can try redirecting the standard error to the standard output as a possible solution. For example, in bash
:
$ wget -q -S -O - 2>&1 | grep ...
or
$ wget -q -S -O - 1>wget.txt 2>&1
The -q
option suppresses the progress bar and some other annoyingly chatty parts of the wget
output.
If memory serves correct, the reg add
command will NOT create the entire directory path if it does not exist. Meaning that if any of the parent registry keys do not exist then they must be created manually one by one. It is really annoying, I know! Example:
@echo off
reg add "HKCU\Software\Policies"
reg add "HKCU\Software\Policies\Microsoft"
reg add "HKCU\Software\Policies\Microsoft\Internet Explorer"
reg add "HKCU\Software\Policies\Microsoft\Internet Explorer\Control Panel"
reg add "HKCU\Software\Policies\Microsoft\Internet Explorer\Control Panel" /v HomePage /t REG_DWORD /d 1 /f
pause
If you want an recent copy of npgsql, then go here
This can be installed via package manager console as
PM> Install-Package Npgsql
You can over that by using GROUP BY
like this:
SELECT ID, Email, ProductName, ProductModel
FROM Products
GROUP BY Email
you use the scrollTop attribute
var position = document.getElementById('id').scrollTop;
You can turn autocommit ON by setting implicit_transactions OFF:
SET IMPLICIT_TRANSACTIONS OFF
When the setting is ON, it returns to implicit transaction mode. In implicit transaction mode, every change you make starts a transactions which you have to commit manually.
Maybe an example is clearer. This will write a change to the database:
SET IMPLICIT_TRANSACTIONS ON
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
COMMIT TRANSACTION
This will not write a change to the database:
SET IMPLICIT_TRANSACTIONS ON
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
ROLLBACK TRANSACTION
The following example will update a row, and then complain that there's no transaction to commit:
SET IMPLICIT_TRANSACTIONS OFF
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
ROLLBACK TRANSACTION
Like Mitch Wheat said, autocommit is the default for Sql Server 2000 and up.
Those integer types are all defined in stdint.h
We have open-sourced our lightweight async REST client library for Android, you might find it useful if you have minimal requirements and don't want to handle the multithreading yourself - it is very OK for basic communications but not a full-blown REST client library.
It's called libRESTfulClient and can be found on GitHub.
The usual way to use assertRaises
is to call a function:
self.assertRaises(TypeError, test_function, args)
to test that the function call test_function(args) raises a TypeError.
The problem with self.testListNone[:1]
is that Python evaluates the expression immediately, before the assertRaises
method is called. The whole reason why test_function
and args
is passed as separate arguments to self.assertRaises
is to allow assertRaises
to call test_function(args)
from within a try...except
block, allowing assertRaises
to catch the exception.
Since you've defined self.testListNone = None
, and you need a function to call, you might use operator.itemgetter like this:
import operator
self.assertRaises(TypeError, operator.itemgetter, (self.testListNone,slice(None,1)))
since
operator.itemgetter(self.testListNone,slice(None,1))
is a long-winded way of saying self.testListNone[:1]
, but which separates the function (operator.itemgetter
) from the arguments.
"abcdefgh..".IndexOf("d")
returns 3
In general returns first occurrence index, if not present returns -1
In C++ the C-style initializers were replaced by constructors which by compile time can ensure that only valid initializations are performed (i.e. after initialization the object members are consistent).
It is a good practice, but sometimes a pre-initialization is handy, like in your example. OOP solves this by abstract classes or creational design patterns.
In my opinion, using this secure way kills the simplicity and sometimes the security trade-off might be too expensive, since simple code does not need sophisticated design to stay maintainable.
As an alternative solution, I suggest to define macros using lambdas to simplify the initialization to look almost like C-style:
struct address {
int street_no;
const char *street_name;
const char *city;
const char *prov;
const char *postal_code;
};
#define ADDRESS_OPEN [] { address _={};
#define ADDRESS_CLOSE ; return _; }()
#define ADDRESS(x) ADDRESS_OPEN x ADDRESS_CLOSE
The ADDRESS macro expands to
[] { address _={}; /* definition... */ ; return _; }()
which creates and calls the lambda. Macro parameters are also comma separated, so you need to put the initializer into brackets and call like
address temp_address = ADDRESS(( _.city = "Hamilton", _.prov = "Ontario" ));
You could also write generalized macro initializer
#define INIT_OPEN(type) [] { type _={};
#define INIT_CLOSE ; return _; }()
#define INIT(type,x) INIT_OPEN(type) x INIT_CLOSE
but then the call is slightly less beautiful
address temp_address = INIT(address,( _.city = "Hamilton", _.prov = "Ontario" ));
however you can define the ADDRESS macro using general INIT macro easily
#define ADDRESS(x) INIT(address,x)
I ran into this problem after a complete removal and then fresh install of MySQL. Specifically:
Library not loaded: /usr/local/opt/mysql/lib/libmysqlclient.20.dylib
I had not even touched my Rails app.
Reinstalling the mysql2
gem solved this problem.
$ gem uninstall mysql2
$ gem install mysql2 -v 0.3.18 # (specifying the version found in my Gemfile.lock)
[MySQL 5.7.10, Rails 4.0.0, Ruby 2.0.0, Mac OS X Yosemite 10.10]
I had problems installing some Wordpress plugins on my local server running php56 on OSX10.11. They failed connection on the external API over SSL.
Installing openSSL didn't solved my problem. But then I figured out that CURL also needed to be reinstalled.
This solved my problem using Homebrew.
brew rm curl && brew install curl --with-openssl
brew uninstall php56 && brew install php56 --with-homebrew-curl --with-openssl
Thanks unwired your solution was very clean. I was using horizontal bootstrap forms and made a couple modifications to allow for a single handler and form css.
html: - UPDATED to use Bootstrap's has-feedback and form-control-feedback
<div class="container">
<form class="form-horizontal">
<div class="form-group has-feedback">
<label for="txt1" class="col-sm-2 control-label">Label 1</label>
<div class="col-sm-10">
<input id="txt1" type="text" class="form-control hasclear" placeholder="Textbox 1">
<span class="clearer glyphicon glyphicon-remove-circle form-control-feedback"></span>
</div>
</div>
<div class="form-group has-feedback">
<label for="txt2" class="col-sm-2 control-label">Label 2</label>
<div class="col-sm-10">
<input id="txt2" type="text" class="form-control hasclear" placeholder="Textbox 2">
<span class="clearer glyphicon glyphicon-remove-circle form-control-feedback"></span>
</div>
</div>
<div class="form-group has-feedback">
<label for="txt3" class="col-sm-2 control-label">Label 3</label>
<div class="col-sm-10">
<input id="txt3" type="text" class="form-control hasclear" placeholder="Textbox 3">
<span class="clearer glyphicon glyphicon-remove-circle form-control-feedback"></span>
</div>
</div>
</form>
</div>
javascript:
$(".hasclear").keyup(function () {
var t = $(this);
t.next('span').toggle(Boolean(t.val()));
});
$(".clearer").hide($(this).prev('input').val());
$(".clearer").click(function () {
$(this).prev('input').val('').focus();
$(this).hide();
});
example: http://www.bootply.com/130682
Forwarding the example by @ritiek, I'm a beginner in ML too, maybe this kind of formatting will help see the name instead of just class number.
images = np.vstack([x, y])
prediction = model.predict(images)
print(prediction)
i = 1
for things in prediction:
if(things == 0):
print('%d.It is cancer'%(i))
else:
print('%d.Not cancer'%(i))
i = i + 1
Combination of lambda and map function can also do the job:
list_ = ['a', 'b', 'b', 'c']
sum(map(lambda x: x=="b", list_))
:2
If you are using Authentication, I recommend adding the following in web.config file.
In my case, users are redirected to the login page upon timing out:
<authentication mode="Forms">
<forms defaultUrl="Login.aspx" timeout="120"/>
</authentication>
let i: Int = 20
func getTypeName(v: Any) -> String {
let fullName = _stdlib_demangleName(_stdlib_getTypeName(i))
if let range = fullName.rangeOfString(".") {
return fullName.substringFromIndex(range.endIndex)
}
return fullName
}
println("Var type is \(getTypeName(i)) = \(i)")
In a similar case, I wanted to avoid always calling addClass or removeClass due to performance issues. I've split the scroll handler function into two individual functions, used according to the current state. I also added a debounce functionality according to this article: https://developers.google.com/web/fundamentals/performance/rendering/debounce-your-input-handlers
var $header = jQuery( ".clearHeader" );
var appScroll = appScrollForward;
var appScrollPosition = 0;
var scheduledAnimationFrame = false;
function appScrollReverse() {
scheduledAnimationFrame = false;
if ( appScrollPosition > 500 )
return;
$header.removeClass( "darkHeader" );
appScroll = appScrollForward;
}
function appScrollForward() {
scheduledAnimationFrame = false;
if ( appScrollPosition < 500 )
return;
$header.addClass( "darkHeader" );
appScroll = appScrollReverse;
}
function appScrollHandler() {
appScrollPosition = window.pageYOffset;
if ( scheduledAnimationFrame )
return;
scheduledAnimationFrame = true;
requestAnimationFrame( appScroll );
}
jQuery( window ).scroll( appScrollHandler );
Maybe someone finds this helpful.
The string
class has a constructor that takes a NULL-terminated C-string:
char arr[ ] = "This is a test";
string str(arr);
// You can also assign directly to a string.
str = "This is another string";
// or
str = arr;
You're misinformed about fcntl()
not always being reliable. It's untrue.
To mark a socket as non-blocking the code is as simple as:
// where socketfd is the socket you want to make non-blocking
int status = fcntl(socketfd, F_SETFL, fcntl(socketfd, F_GETFL, 0) | O_NONBLOCK);
if (status == -1){
perror("calling fcntl");
// handle the error. By the way, I've never seen fcntl fail in this way
}
Under Linux, on kernels > 2.6.27 you can also create sockets non-blocking from the outset using socket()
and accept4()
.
e.g.
// client side
int socketfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
// server side - see man page for accept4 under linux
int socketfd = accept4( ... , SOCK_NONBLOCK);
It saves a little bit of work, but is less portable so I tend to set it with fcntl()
.
The split
method will create an array. So you need to access the third element in your case..
(arrays are 0-indexed) You need to access result[2]
to get the url
var result = $(row).text().split('|');
alert( result[2] );
You do not give us enough information to know what row
is, exactly.. So depending on how you acquire the variable row
you might need to do one of the following.
row
is a string then row.split('|');
$(row).text().split('|');
input
element then $(row).val().split('|');
I found the solution for the above program, which had the goal of signing in to http://rediff.com
public class Handle_popupNAlert
{
public static void main(String[] args ) throws InterruptedException
{
WebDriver driver= new FirefoxDriver();
driver.get("http://www.rediff.com/");
WebElement sign = driver.findElement(By.xpath("//html/body/div[3]/div[3]/span[4]/span/a"));
sign.click();
Set<String> windowId = driver.getWindowHandles(); // get window id of current window
Iterator<String> itererator = windowId.iterator();
String mainWinID = itererator.next();
String newAdwinID = itererator.next();
driver.switchTo().window(newAdwinID);
System.out.println(driver.getTitle());
Thread.sleep(3000);
driver.close();
driver.switchTo().window(mainWinID);
System.out.println(driver.getTitle());
Thread.sleep(2000);
WebElement email_id= driver.findElement(By.xpath("//*[@id='c_uname']"));
email_id.sendKeys("hi");
Thread.sleep(5000);
driver.close();
driver.quit();
}
}
Guys this is really simple.
login via ssh
into your pi
execute
vncserver -geometry 1200x1600
This will generate a new session :1
connect with your vnc client at ipaddress:1
Thats it.
#include <QTextStream>
...
qDebug()<<"Bla bla bla";
Depending on the location of your config file System.Reflection.Assembly.GetExecutingAssembly().Location
might do what you need.
You can use zip
:
>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> for x, y in zip(a, b):
... print x, y
...
1 a
2 b
3 c
? Just at the bottom of your project settings .?
URL : https://gitlab.com/{USER_NAME}/{PROJECT_NAME}/edit
If by ID:
$('#datepicker').datepicker({
format: 'dd/mm/yyyy'
});
If by Class:
$('.datepicker').datepicker({
format: 'dd/mm/yyyy'
});
You can delete multiple branches on windows using Git GUI:
As defined in App_start.BundleConfig, it's just calling
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
Nothing happens even if you remove that section.
public static string DataTable2String(DataTable dataTable)
{
StringBuilder sb = new StringBuilder();
if (dataTable != null)
{
string seperator = " | ";
#region get min length for columns
Hashtable hash = new Hashtable();
foreach (DataColumn col in dataTable.Columns)
hash[col.ColumnName] = col.ColumnName.Length;
foreach (DataRow row in dataTable.Rows)
for (int i = 0; i < row.ItemArray.Length; i++)
if (row[i] != null)
if (((string)row[i]).Length > (int)hash[dataTable.Columns[i].ColumnName])
hash[dataTable.Columns[i].ColumnName] = ((string)row[i]).Length;
int rowLength = (hash.Values.Count + 1) * seperator.Length;
foreach (object o in hash.Values)
rowLength += (int)o;
#endregion get min length for columns
sb.Append(new string('=', (rowLength - " DataTable ".Length) / 2));
sb.Append(" DataTable ");
sb.AppendLine(new string('=', (rowLength - " DataTable ".Length) / 2));
if (!string.IsNullOrEmpty(dataTable.TableName))
sb.AppendLine(String.Format("{0,-" + rowLength + "}", String.Format("{0," + ((rowLength + dataTable.TableName.Length) / 2).ToString() + "}", dataTable.TableName)));
#region write values
foreach (DataColumn col in dataTable.Columns)
sb.Append(seperator + String.Format("{0,-" + hash[col.ColumnName] + "}", col.ColumnName));
sb.AppendLine(seperator);
sb.AppendLine(new string('-', rowLength));
foreach (DataRow row in dataTable.Rows)
{
for (int i = 0; i < row.ItemArray.Length; i++)
{
sb.Append(seperator + String.Format("{0," + hash[dataTable.Columns[i].ColumnName] + "}", row[i]));
if (i == row.ItemArray.Length - 1)
sb.AppendLine(seperator);
}
}
#endregion write values
sb.AppendLine(new string('=', rowLength));
}
else
sb.AppendLine("================ DataTable is NULL ================");
return sb.ToString();
}
output:
======================= DataTable =======================
MyTable
| COL1 | COL2 | COL3 1000000ng name |
----------------------------------------------------------
| 1 | 2 | 3 |
| abc | Dienstag, 12. März 2013 | xyz |
| Have | a nice | day! |
==========================================================
If you see this error when running tests, make sure you have imported the module the pipe belongs to, e.g.:
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [CustomPipeModule],
declarations: [...],
providers: [...],
...
}).compileComponents();
}));
Delete all the apk files from platfroms >> android >> build >> generated >> outputs >> apk and run command cordova run android
Use break
and continue
to do this. Breaking nested loops can be done in Python using the following:
for a in range(...):
for b in range(..):
if some condition:
# break the inner loop
break
else:
# will be called if the previous loop did not end with a `break`
continue
# but here we end up right after breaking the inner loop, so we can
# simply break the outer loop as well
break
Another way is to wrap everything in a function and use return
to escape from the loop.
When you run your application as an jar, your Manifest.MF
file should know which class has the main method.
To add this information when SpringBoot compiles your code, add start-class
property on your pom file.
E.g.:
<properties>
<start-class>com.example.DemoApplication</start-class>
</properties>
The LDF file holds the database transaction log. See, for example, http://www.databasedesign-resource.com/sql-server-transaction-log.html for a full explanation. There are ways to shrink the transaction file; for example, see http://support.microsoft.com/kb/873235.
Just want to add some description over @Jackpap answer:
automaticallyImplyLeading:
This checks whether we want to apply the back widget(leading widget) over the app bar or not. If the automaticallyImplyLeading is false then automatically space is given to the title and if If the leading widget is true, then this parameter has no effect.
void main() {
runApp(
new MaterialApp(
home: new Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false, // Used for removing back buttoon.
title: new Center(
child: new Text("Demo App"),
),
),
body: new Container(
child: new Center(
child: Text("Hello world!"),
),
),
),
),
);
}
go to your website via FTP/Cpanel
, find maintenance.flag
and remove
pytest --capture=tee-sys
was recently added (v5.4.0). You can capture as well as see the output on stdout/err.
You shouldn't be using the BinaryFormatter
for this - that's for serializing .Net types to a binary file so they can be read back again as .Net types.
If it's stored in the database, hopefully, as a varbinary
- then all you need to do is get the byte array from that (that will depend on your data access technology - EF and Linq to Sql, for example, will create a mapping that makes it trivial to get a byte array) and then write it to the file as you do in your last line of code.
With any luck - I'm hoping that fileContent
here is the byte array? In which case you can just do
System.IO.File.WriteAllBytes("hello.pdf", fileContent);
HTML Elements
An HTML element usually consists of a start tag and end tag, with the content inserted in between:
<tagname>Content goes here...</tagname>
The HTML element is everything from the start tag to the end tag. Source
HTML Attributes
An attribute is used to define the characteristics of an HTML element and is placed inside the element's opening tag. All attributes are made up of two parts: a name and a value.
HTML Tag vs Element
"Elements" and "tags" are terms that are widely confused. HTML documents contain tags, but do not contain the elements. The elements are only generated after the parsing step, from these tags. Source: wikipedia > HTML_element
An HTML element is defined by a starting tag. If the element contains other content, it ends with a closing tag.
For example <p>
is starting tag of a paragraph and </p>
is closing tag of the same paragraph but <p>This is paragraph</p>
is a paragraph element.
Source:tutorialspoint > html_elements
While awk
's printf
can be used, you may want to look into pr
or (on BSDish systems) rs
for formatting.
This worked for me, converts to nested JSON to easy to read YAML
string JSONDeserialized {get; set;}
public int indentLevel;
private bool JSONDictionarytoYAML(Dictionary<string, object> dict)
{
bool bSuccess = false;
indentLevel++;
foreach (string strKey in dict.Keys)
{
string strOutput = "".PadLeft(indentLevel * 3) + strKey + ":";
JSONDeserialized+="\r\n" + strOutput;
object o = dict[strKey];
if (o is Dictionary<string, object>)
{
JSONDictionarytoYAML((Dictionary<string, object>)o);
}
else if (o is ArrayList)
{
foreach (object oChild in ((ArrayList)o))
{
if (oChild is string)
{
strOutput = ((string)oChild);
JSONDeserialized += strOutput + ",";
}
else if (oChild is Dictionary<string, object>)
{
JSONDictionarytoYAML((Dictionary<string, object>)oChild);
JSONDeserialized += "\r\n";
}
}
}
else
{
strOutput = o.ToString();
JSONDeserialized += strOutput;
}
}
indentLevel--;
return bSuccess;
}
usage
Dictionary<string, object> JSONDic = new Dictionary<string, object>();
JavaScriptSerializer js = new JavaScriptSerializer();
try {
JSONDic = js.Deserialize<Dictionary<string, object>>(inString);
JSONDeserialized = "";
indentLevel = 0;
DisplayDictionary(JSONDic);
return JSONDeserialized;
}
catch (Exception)
{
return "Could not parse input JSON string";
}
One risk of using the keyboard shortcut is that it requires using a non-ASCII encoding. That might be fine, but if your source is loaded by different editors in different locales, you might hit trouble somewhere along the line.
It might be safer to use either ’
or ’
(which are equivalent) as both are ASCII.
// hh:mm will print hours in 12hrs clock and mins (e.g. 02:30)
System.out.println(DateTimeFormatter.ofPattern("hh:mm").format(LocalTime.now()));
// HH:mm will print hours in 24hrs clock and mins (e.g. 14:30)
System.out.println(DateTimeFormatter.ofPattern("HH:mm").format(LocalTime.now()));
// hh:mm a will print hours in 12hrs clock, mins and AM/PM (e.g. 02:30 PM)
System.out.println(DateTimeFormatter.ofPattern("hh:mm a").format(LocalTime.now()));
I don't know if this was true at the time of the original posting, but the siblings method allows selectors, so a reduction of what the OP listed should work.
$(this).siblings(':not(.closedTab)');
Copy it over. It's really that simple. :)
On the client side, just edit .git/config in the client's local repo to point your remotes to the new URL as necessary.
Get rid of the parentheses.
Sample batch file:
echo "%1"
if ("%1"=="") echo match1
if "%1"=="" echo match2
Output from running above script:
C:\>echo ""
""
C:\>if ("" == "") echo match1
C:\>if "" == "" echo match2
match2
I think it is actually taking the parentheses to be part of the strings and they are being compared.
You've simply got it backwards. Specifying a minimum width would make the select menu always be at least that width, so it will continue expanding to 90% no matter what the window size is, also being at least the size of its longest option.
You need to use max-width
instead. This way, it will let the select menu expand to its longest option, but if that expands past your set maximum of 90% width, crunch it down to that width.
The most easy solution is to set color filter to the background image of a button as I saw here
You can do as follow:
if ('need to set button disable')
button.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
else
button.getBackground().setColorFilter(null);
Hope I helped someone...
You don't even need to cast, it is implicit.
int i = 3;
float f = i;
A full list/table of implicit numeric conversions can be seen here http://msdn.microsoft.com/en-us/library/y5b434w4.aspx
You can use:
npm show {pkg} version
(so npm show express version
will return now 3.0.0rc3
).
Try adding this:
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls";
By looking at your debug logs, you can notice that the failing PhpMailer log shows this:
(..snip..)
SMTP -> ERROR: AUTH not accepted from server: 250 orion.bommtempo.net.br Hello admin-teste.bommtempo.com.br [200.155.129.6]
(..snip..)
503 AUTH command used when not advertised
(..snip..)
While your successful PEAR log shows this:
DEBUG: Send: STARTTLS
DEBUG: Recv: 220 TLS go ahead
My guess is that explicitly asking PHPMailer to use TLS will put it on the right track.
Also, make sure you're using the latest versin of PHPMailer.
You can use Oracle.ManagedDataAccess NuGet package too (.NET >= 4.0, database >= 10g Release 2).
=== What about future proofing and code reuse? ===
If you don't write the code to free the objects, then you are limiting the code to only being safe to use when you can depend on the memory being free'd by the process being closed ... i.e. small one-time use projects or "throw-away"[1] projects)... where you know when the process will end.
If you do write the code that free()s all your dynamically allocated memory, then you are future proofing the code and letting others use it in a larger project.
[1] regarding "throw-away" projects. Code used in "Throw-away" projects has a way of not being thrown away. Next thing you know ten years have passed and your "throw-away" code is still being used).
I heard a story about some guy who wrote some code just for fun to make his hardware work better. He said "just a hobby, won't be big and professional". Years later lots of people are using his "hobby" code.
All you need is to give the AnchorPane
an ID, and then you can get the Stage
from that.
@FXML private AnchorPane ap;
Stage stage = (Stage) ap.getScene().getWindow();
From here, you can add in the Listener
that you need.
Edit: As stated by EarthMind below, it doesn't have to be the AnchorPane
element; it can be any element that you've defined.
Just because you have a project inside the workspace directory doesn't mean Eclipse opens it or even sees it automatically. You must use File - Import - General - Import existing project into workspace to have your project in Eclipse.
The mappedBy
attribute is referencing customer
while the property is mCustomer
, hence the error message. So either change your mapping into:
/** The collection of stores. */
@OneToMany(mappedBy = "mCustomer", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Collection<Store> stores;
Or change the entity property into customer
(which is what I would do).
The mappedBy reference indicates "Go look over on the bean property named 'customer' on the thing I have a collection of to find the configuration."
You can use Array.Resize()
, documented in MSDN.
But yeah, I agree with Corey, if you need a dynamically sized data structure, we have List
s for that.
Important: Array.Resize()
doesn't resize the array (the method name is misleading), it creates a new array and only replaces the reference you passed to the method.
An example:
var array1 = new byte[10];
var array2 = array1;
Array.Resize<byte>(ref array1, 20);
// Now:
// array1.Length is 20
// array2.Length is 10
// Two different arrays.
Don't change the DNS on the phone. Instead, connect with wifi to the local network and you are all set.
At my office, we have internal servers with internal DNS that are not exposed to the Internet. I just connect with iPhone to the office wifi and can then access them fine.
YMMV, but instead of configuring the phone DNS, it feels to me that just setting up local internal DNS and wifi is a cleaner and easier solution.
This API gives you the current time and several formats in JSON - https://market.mashape.com/parsify/format#time. Here's a sample response:
{
"time": {
"daysInMonth": 31,
"millisecond": 283,
"second": 42,
"minute": 55,
"hour": 1,
"date": 6,
"day": 3,
"week": 10,
"month": 2,
"year": 2013,
"zone": "+0000"
},
"formatted": {
"weekday": "Wednesday",
"month": "March",
"ago": "a few seconds",
"calendar": "Today at 1:55 AM",
"generic": "2013-03-06T01:55:42+00:00",
"time": "1:55 AM",
"short": "03/06/2013",
"slim": "3/6/2013",
"hand": "Mar 6 2013",
"handTime": "Mar 6 2013 1:55 AM",
"longhand": "March 6 2013",
"longhandTime": "March 6 2013 1:55 AM",
"full": "Wednesday, March 6 2013 1:55 AM",
"fullSlim": "Wed, Mar 6 2013 1:55 AM"
},
"array": [
2013,
2,
6,
1,
55,
42,
283
],
"offset": 1362534942283,
"unix": 1362534942,
"utc": "2013-03-06T01:55:42.283Z",
"valid": true,
"integer": false,
"zone": 0
}
Not sure if there's terrible reasons to do this or not, but it seems to work with me on the latest version of Chrome/Firefox without any visible performance problems with quite a lot of elements on the page.
*:not(:hover)>.parent-hover-show{
display:none;
}
But this way, all you need is to apply parent-hover-show
to an element and the rest is taken care of, and you can keep whatever default display type you want without it always being "block" or making multiple classes for each type.
If you're converting an HTML doc into a PDF page, but the page spills onto two pages, try reducing the font size. Of course you can also decrease the spacing between paragraphs (with the CSS margin-top/margin-bottom styles), or even the left and right gutters with margins. But to my eye, keep things in proportion and just make the text a little smaller:
p { font-size: 90%; }
or
body { font-size: 9.5pt }
building on mwigdahls answer. if you also need to do grouping here is how to get it to look like
group, csv
'group1', 'paul, john'
'group2', 'mary'
--drop table #user
create table #user (groupName varchar(25), username varchar(25))
insert into #user (groupname, username) values ('apostles', 'Paul')
insert into #user (groupname, username) values ('apostles', 'John')
insert into #user (groupname, username) values ('family','Mary')
select
g1.groupname
, stuff((
select ', ' + g.username
from #user g
where g.groupName = g1.groupname
order by g.username
for xml path('')
),1,2,'') as name_csv
from #user g1
group by g1.groupname
The free Python book Dive Into Python has a chapter on unit testing that you might find useful.
If you follow modern practices you should probably write the tests while you are writing your project, and not wait until your project is nearly finished.
Bit late now, but now you know for next time. :)
Rather than a brute force loop through the list (eg 1 to 10000), rather use an iterative search approach : The List needs to be sorted by the element to be tested.
Start search at the middle element size()/2 eg 5000 if search item greater than element at 5000, then test the element at the midpoint between the upper(10000) and midpoint(5000) - 7500
keep doing this until you reach the match (or use a brute force loop through once you get down to a smaller range (eg 20 items)
You can search a list of 10000 in around 13 to 14 tests, rather than potentially 9999 tests.
I had same problem in my organization.
After many attempts, I came to the following solution:
I applied to the system administrator to change the proxy authentication type from Kerberos to NTLM. I'm not sure if it was mandatory (I'm an ignoramus in this matter), but my application was approved.
After that I add Git setting
git config --global http.proxyauthmethod ntlm
Only after that I was able to clone my repository
It looks like you are trying to read an object from JSON that actually describes an array. Java objects are mapped to JSON objects with curly braces {}
but your JSON actually starts with square brackets []
designating an array.
What you actually have is a List<product>
To describe generic types, due to Java's type erasure, you must use a TypeReference
. Your deserialization could read: myProduct = objectMapper.readValue(productJson, new TypeReference<List<product>>() {});
A couple of other notes: your classes should always be PascalCased. Your main method can just be public static void main(String[] args) throws Exception
which saves you all the useless catch
blocks.
A good example of using the Generic Repository pattern and implementing a generic solution for this might look something like this.
public IList<TEntity> Get<TParamater>(IList<Expression<Func<TEntity, TParamater>>> includeProperties)
{
foreach (var include in includeProperties)
{
query = query.Include(include);
}
return query.ToList();
}
@Justin Pollard xml code works really good. As a side note you can add a ripple effect with the following xml lines.
<item>
<ripple
xmlns:android="http://schemas.android.com/apk/res/android"
android:color="?android:colorControlHighlight" >
<item android:id="@android:id/mask">
<shape android:shape="oval" >
<solid android:color="#FFBB00" />
</shape>
</item>
<item>
<shape android:shape="oval" >
<solid android:color="@color/ColorPrimary" />
</shape>
</item>
</ripple>
</item>
Here is my Java code for Selenium WebDriver. Write the following method and call it during assertion:
protected boolean isElementPresent(By by){
try{
driver.findElement(by);
return true;
}
catch(NoSuchElementException e){
return false;
}
}
Maybe it's possible to debug PHP on Visual Studio, but it's simpler and more logical to use Eclipse PDT or Netbeans IDE for your PHP projects, aside from Visual Studio if you need to use both technologies from two different vendors.
Right now, it has not been exposed at API level yet. However you can achieve it using something similar to this
<ng-container cdkColumnDef="userId" >
<md-header-cell *cdkHeaderCellDef [ngClass]="'customWidthClass'"> ID </md-header-cell>
<md-cell *cdkCellDef="let row" [ngClass]="'customWidthClass'"> {{row.id}} </md-cell>
</ng-container>
In css, you need to add this custom class -
.customWidthClass{
flex: 0 0 75px;
}
Feel free to enter the logic to append class or custom width in here. It will apply custom width for the column.
Since md-table uses flex
, we need to give fixed width in flex manner. This simply explains -
0 = don't grow (shorthand for flex-grow)
0 = don't shrink (shorthand for flex-shrink)
75px = start at 75px (shorthand for flex-basis)
Plunkr here - https://plnkr.co/edit/v7ww6DhJ6zCaPyQhPRE8?p=preview
I would like to add the following point.
You can also make it a const &
and const &&
So,
struct s{
void val1() const {
// *this is const here. Hence this function cannot modify any member of *this
}
void val2() const & {
// *this is const& here
}
void val3() const && {
// The object calling this function should be const rvalue only.
}
void val4() && {
// The object calling this function should be rvalue reference only.
}
};
int main(){
s a;
a.val1(); //okay
a.val2(); //okay
// a.val3() not okay, a is not rvalue will be okay if called like
std::move(a).val3(); // okay, move makes it a rvalue
}
Feel free to improve the answer. I am no expert
Does this work?
display_errors = Off
Also, what version of php are you using?
For each iteration of the ng-repeat loop, line
is a reference to an object in your array. Therefore, to preview the value, use {{line.text}}
.
Similarly, to databind to the text, databind to the same: ng-model="line.text"
. You don't need to use value
when using ng-model (actually you shouldn't).
For a more in-depth look at scopes and ng-repeat, see What are the nuances of scope prototypal / prototypical inheritance in AngularJS?, section ng-repeat.
There is no b['body']
in python. You have to use get_payload.
if isinstance(mailEntity.get_payload(), list):
for eachPayload in mailEntity.get_payload():
...do things you want...
...real mail body is in eachPayload.get_payload()...
else:
...means there is only text/plain part....
...use mailEntity.get_payload() to get the body...
Good Luck.
No, you cannot do that. I invite you to read a POST definition.
Or this page: HTTP, request methods
(1) Set the tabindex
attribute:
<div id="mydiv" tabindex="0" />
(2) Bind to keydown:
$('#mydiv').on('keydown', function(event) {
//console.log(event.keyCode);
switch(event.keyCode){
//....your actions for the keys .....
}
});
To set the focus on start:
$(function() {
$('#mydiv').focus();
});
To remove - if you don't like it - the div
focus border, set outline: none
in the CSS.
See the table of keycodes for more keyCode
possibilities.
All of the code assuming you use jQuery.
#You can set height and width like this:
myGraphView.setLayoutParams(new LayoutParams(width, height));
Use autossh. It's the tool that's meant for monitoring the ssh connection.
Prerequisite:
Your APK needs to be signed by system as correctly pointed out earlier. One way to achieve that is building the AOSP image yourself and adding the source code into the build.
Code:
Once installed as a system app, you can use the package manager methods to install and uninstall an APK as following:
Install:
public boolean install(final String apkPath, final Context context) {
Log.d(TAG, "Installing apk at " + apkPath);
try {
final Uri apkUri = Uri.fromFile(new File(apkPath));
final String installerPackageName = "MyInstaller";
context.getPackageManager().installPackage(apkUri, installObserver, PackageManager.INSTALL_REPLACE_EXISTING, installerPackageName);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
Uninstall:
public boolean uninstall(final String packageName, final Context context) {
Log.d(TAG, "Uninstalling package " + packageName);
try {
context.getPackageManager().deletePackage(packageName, deleteObserver, PackageManager.DELETE_ALL_USERS);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
To have a callback once your APK is installed/uninstalled you can use this:
/**
* Callback after a package was installed be it success or failure.
*/
private class InstallObserver implements IPackageInstallObserver {
@Override
public void packageInstalled(String packageName, int returnCode) throws RemoteException {
if (packageName != null) {
Log.d(TAG, "Successfully installed package " + packageName);
callback.onAppInstalled(true, packageName);
} else {
Log.e(TAG, "Failed to install package.");
callback.onAppInstalled(false, null);
}
}
@Override
public IBinder asBinder() {
return null;
}
}
/**
* Callback after a package was deleted be it success or failure.
*/
private class DeleteObserver implements IPackageDeleteObserver {
@Override
public void packageDeleted(String packageName, int returnCode) throws RemoteException {
if (packageName != null) {
Log.d(TAG, "Successfully uninstalled package " + packageName);
callback.onAppUninstalled(true, packageName);
} else {
Log.e(TAG, "Failed to uninstall package.");
callback.onAppUninstalled(false, null);
}
}
@Override
public IBinder asBinder() {
return null;
}
}
/**
* Callback to give the flow back to the calling class.
*/
public interface InstallerCallback {
void onAppInstalled(final boolean success, final String packageName);
void onAppUninstalled(final boolean success, final String packageName);
}
===> Tested on Android 8.1 and worked well.
SELECT DISTINCT groups.id,
(SELECT COUNT(*) FROM group_members
WHERE member_id = groups.id) AS memberCount
FROM groups
Create a class like this:
public class Data
{
public string Id {get; set;}
public string Name {get; set;}
public string First_Name {get; set;}
public string Last_Name {get; set;}
public string Username {get; set;}
public string Gender {get; set;}
public string Locale {get; set;}
}
(I'm not 100% sure, but if that doesn't work you'll need use [DataContract]
and [DataMember]
for DataContractJsonSerializer
.)
Then create JSonSerializer
:
private static readonly XmlObjectSerializer Serializer = new DataContractJsonSerializer(typeof(Data));
and deserialize object:
// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(contents);
using(var stream = new MemoryStream(byteArray))
{
(Data)Serializer.ReadObject(stream);
}
I tried a few of these things until I got one to work in both Firefox and IE. This is what I came up with.
$("#my-Select").val($("#my-Select" + " option").filter(function() { return this.text == myText }).val());
another way of writing it in a more readable fasion:
var valofText = $("#my-Select" + " option").filter(function() {
return this.text == myText
}).val();
$(ElementID).val(valofText);
Pseudocode:
$("#my-Select").val( getValOfText( myText ) );
Take a Look at this Plugin
Makes your code as easy as -> $('SelectorToPrint').printElement();
A java.util.Date
object is a kind of timestamp - it contains a number of milliseconds since January 1, 1970, 00:00:00 UTC. So you can't use a standard Date
object to contain just a day / month / year, without a time.
As far as I know, there's no really easy way to compare dates by only taking the date (and not the time) into account in the standard Java API. You can use class Calendar
and clear the hour, minutes, seconds and milliseconds:
Calendar cal = Calendar.getInstance();
cal.clear(Calendar.HOUR_OF_DAY);
cal.clear(Calendar.AM_PM);
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
Do the same with another Calendar
object that contains the date that you want to compare it to, and use the after()
or before()
methods to do the comparison.
As explained into the Javadoc of java.util.Calendar.clear(int field):
The HOUR_OF_DAY, HOUR and AM_PM fields are handled independently and the the resolution rule for the time of day is applied. Clearing one of the fields doesn't reset the hour of day value of this Calendar. Use set(Calendar.HOUR_OF_DAY, 0) to reset the hour value.
edit - The answer above is from 2010; in Java 8, there is a new date and time API in the package java.time
which is much more powerful and useful than the old java.util.Date
and java.util.Calendar
classes. Use the new date and time classes instead of the old ones.
How host name verification should be done is defined in RFC 6125, which is quite recent and generalises the practice to all protocols, and replaces RFC 2818, which was specific to HTTPS. (I'm not even sure Java 7 uses RFC 6125, which might be too recent for this.)
From RFC 2818 (Section 3.1):
If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.
[...]
In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI.
Essentially, the specific problem you have comes from the fact that you're using IP addresses in your CN and not a host name. Some browsers might work because not all tools follow this specification strictly, in particular because "most specific" in RFC 2818 isn't clearly defined (see discussions in RFC 6215).
If you're using keytool
, as of Java 7, keytool
has an option to include a Subject Alternative Name (see the table in the documentation for -ext
): you could use -ext san=dns:www.example.com
or -ext san=ip:10.0.0.1
.
EDIT:
You can request a SAN in OpenSSL by changing openssl.cnf
(it will pick the copy in the current directory if you don't want to edit the global configuration, as far as I remember, or you can choose an explicit location using the OPENSSL_CONF
environment variable).
Set the following options (find the appropriate sections within brackets first):
[req]
req_extensions = v3_req
[ v3_req ]
subjectAltName=IP:10.0.0.1
# or subjectAltName=DNS:www.example.com
There's also a nice trick to use an environment variable for this (rather in than fixing it in a configuration file) here: http://www.crsr.net/Notes/SSL.html
You can go to Design mode and select "Fix" at the bottom of the warning. Then a pop up will appear (seems like it's going to register the new string) and voila, the error is fixed.
If you're looking for something that behaves like an enumeration (because I see you are defining an object and attaching a sequential ID 0, 1, 2 and contains a name field that you don't want to misspell (e.g. name vs naaame), you're better off defining an enumeration because the sequential ID is taken care of automatically, and provides type verification for you out of the box.
enum TestStatus {
Available, // 0
Ready, // 1
Started, // 2
}
class Test {
status: TestStatus
}
var test = new Test();
test.status = TestStatus.Available; // type and spelling is checked for you,
// and the sequence ID is automatic
The values above will be automatically mapped, e.g. "0" for "Available", and you can access them using TestStatus.Available
. And Typescript will enforce the type when you pass those around.
You wanted an array of objects, (not exactly an object with keys "0", "1" and "2"), so let's define the type of the object, first, then a type of a containing array.
class TestStatus {
id: number
name: string
constructor(id, name){
this.id = id;
this.name = name;
}
}
type Statuses = Array<TestStatus>;
var statuses: Statuses = [
new TestStatus(0, "Available"),
new TestStatus(1, "Ready"),
new TestStatus(2, "Started")
]
I think your problem is that the :after psuedo-element requires the content: property set inside it. You need to tell it to insert something. You could even just have it insert the image directly:
ul li:after {
content: url('../images/small_triangle.png');
}
This works for up to 5 dates and handles nulls. Just couldn't get it to work as an Inline function.
CREATE FUNCTION dbo.MinDate(@Date1 datetime = Null,
@Date2 datetime = Null,
@Date3 datetime = Null,
@Date4 datetime = Null,
@Date5 datetime = Null)
RETURNS Datetime AS
BEGIN
--USAGE select dbo.MinDate('20120405',null,null,'20110305',null)
DECLARE @Output datetime;
WITH Datelist_CTE(DT)
AS (
SELECT @Date1 AS DT WHERE @Date1 is not NULL UNION
SELECT @Date2 AS DT WHERE @Date2 is not NULL UNION
SELECT @Date3 AS DT WHERE @Date3 is not NULL UNION
SELECT @Date4 AS DT WHERE @Date4 is not NULL UNION
SELECT @Date5 AS DT WHERE @Date5 is not NULL
)
Select @Output=Min(DT) FROM Datelist_CTE
RETURN @Output
END
Unless you have very, very well-behaved data, this is a non-trivial challenge. A naive approach would be to tokenize on whitespace and assume that a three-token result is [first, middle, last] and a two-token result is [first, last], but you're going to have to deal with multi-word surnames (e.g. "Van Buren") and multiple middle names.
Here are some links that I found on face recognition libraries.
Image Identification links:
Adding a file, and then deleting it is the kind of operation that's considered an error - and so SVN is telling you. You told it to expect some file data and then don't supply it when you commit, the red lights flash and the sirens go off!
The answer is to undo your add, alternatively commit the file and then use 'svn rm' to remove it from the filesystem and the repo.
Using Google's guava library
String[] firstArray = {"test1","","test2","test4","",null};
Iterable<String> st=Iterables.filter(Arrays.asList(firstArray),new Predicate<String>() {
@Override
public boolean apply(String arg0) {
if(arg0==null) //avoid null strings
return false;
if(arg0.length()==0) //avoid empty strings
return false;
return true; // else true
}
});
$(window).scroll(function() {
$('.logo_container, .slogan').css({
"opacity" : ".1",
"transition" : "opacity .8s ease-in-out"
});
});
Check the fiddle: http://jsfiddle.net/2k3hfwo0/2/
Try this to avoid to_char limitations:
SELECT
regexp_replace(regexp_replace(n,'^-\'||s,'-0'||s),'^\'||s,'0'||s)
FROM (SELECT -0.89 n,RTrim(1/2,5) s FROM dual);
it seems as if it comes when u have an previous compiled version of your program running
You should not initialize your variable to an empty object, but let it be undefined
or null
until the conditions exist where it should have a non-null
/undefined
value:
$scope.card;
if (someCondition = true) {
$scope.card = {};
}
Then your template:
ng-show="card"
I tried to change target sdk to 13 but does not works!!
then when I changed compileSdkVersion 13
to compileSdkVersion 14
is compiled successfully :)
NOTE: I Work with Android Studio not Eclipse
From Resetting SQL Server Identity Columns:
Retrieving the identity for the table Employees
:
DBCC checkident ('Employees')
Repairing the identity seed (if for some reason the database is inserting duplicate identities):
DBCC checkident ('Employees', reseed)
Changing the identity seed for the table Employees
to 1000:
DBCC checkident ('Employees', reseed, 1000)
The next row inserted will begin at 1001.
No need for cut or magic, in bash you can cut a string like so:
ORGSTRING="123456"
CUTSTRING=${ORGSTRING:0:-3}
echo "The original string: $ORGSTRING"
echo "The new, shorter and faster string: $CUTSTRING"
I'm having the same problem, but it gets solved with installation of python-dev
.
Before installing PIL, run following command:
sudo apt-get install python-dev
Then install PIL:
pip install PIL
you could use a defaultdict. It will let you set dictionary values without worrying if the key already exists. If you access a key that has not been initialized yet it will return a value you specify (in the below example it will return None)
from collections import defaultdict
your_dict = defaultdict(lambda : None)
You could also use Perl6::Junction.
use Perl6::Junction qw'any';
my @arr = ( 1, 2, 3 );
if( any(@arr) == 1 ){ ... }
Try this:-
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Online Student Portal</title>
</head>
<body>
<form action="">
<input type="button" value="Add Students" onclick="window.location.href='Students.html';"/>
<input type="button" value="Add Courses" onclick="window.location.href='Courses.html';"/>
<input type="button" value="Student Payments" onclick="window.location.href='Payment.html';"/>
</form>
</body>
</html>
If you want more datesource configs e.g.
spring.datasource.test-while-idle=true
spring.datasource.time-between-eviction-runs-millis=30000
spring.datasource.validation-query=select 1
you could use below code
@Bean
public DataSource dataSource() {
DataSource dataSource = new DataSource(); // org.apache.tomcat.jdbc.pool.DataSource;
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setTestWhileIdle(testWhileIdle);
dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMills);
dataSource.setValidationQuery(validationQuery);
return dataSource;
}
refer: Spring boot jdbc Connection
You can use boost::optional
(or std::optional
for newer versions), which was developed in particular for decision of your problem:
boost::optional<int> y[50];
....
geoGraph.y[x] = nums[x];
....
const size_t size_y = sizeof(y)/sizeof(y[0]); //!!!! correct size of y!!!!
for(int i=0; i<size_y;i++){
if(y[i]) { //check for null
p[i].SetPoint(Recto.Height()-x,*y[i]);
....
}
}
P.S. Do not use C-type array -> use std::array or std::vector:
std::array<int, 50> y; //not int y[50] !!!
This also works
sudo usermod -aG <group> <user>
Then restart vm
Process Monitor allows you to monitor file and registry activity of various processes.
//Try this if you can't use -std=c++11:-
int number=55;
char tempStr[32] = {0};
sprintf(tempStr, "%d", number);
One need to update Newtonsoft.Json -Version GO to Tools => NuGet Package Manager => Package Manager Console and Type Install-Package Newtonsoft.Json -Version 12.0.2 in Package Manager Console Window.
Aside from limiting the columns selected to reduce bandwidth and memory:
DataTable t;
t.Columns.Remove("columnName");
t.Columns.RemoveAt(columnIndex);
Rules for padding:
Why Rule 2: Consider the following struct,
If we were to create an array(of 2 structs) of this struct, No padding will be required at the end:
Therefore, size of struct = 8 bytes
Assume we were to create another struct as below:
If we were to create an array of this struct, there are 2 possibilities, of the number of bytes of padding required at the end.
A. If we add 3 bytes at the end and align it for int and not Long:
B. If we add 7 bytes at the end and align it for Long:
The start address of the second array is a multiple of 8(i.e 24). The size of the struct = 24 bytes
Therefore, by aligning the start address of the next array of the struct to a multiple of the largest member(i.e if we were to create an array of this struct, the first address of the second array must start at an address which is a multiple of the largest member of the struct. Here it is, 24(3 * 8)), we can calculate the number of padding bytes required at the end.
Building on @Waterscroll's response, if you want to use async and await in node 8+:
const fs = require('fs');
const util = require('util');
const readdir = util.promisify(fs.readdir);
const unlink = util.promisify(fs.unlink);
const directory = 'test';
async function toRun() {
try {
const files = await readdir(directory);
const unlinkPromises = files.map(filename => unlink(`${directory}/${filename}`));
return Promise.all(unlinkPromises);
} catch(err) {
console.log(err);
}
}
toRun();
Short answer:
int
uses up 4 bytes of memory (and it CANNOT contain a decimal), double
uses 8 bytes of memory. Just different tools for different purposes.
ALTER TABLE myTable ALTER COLUMN myColumn {DataType} NULL
where {DataType}
is the current data type of that column (For example int
or varchar(10)
)
Chrome Version: 68.0.3440.106
Just restart Chrome (in your address bar):
chrome://restart
js-xlsx library makes it easy to convert Excel/CSV files into JSON objects.
Download the xlsx.full.min.js file from here. Write below code on your HTML page Edit the referenced js file link (xlsx.full.min.js) and link of Excel file
<!doctype html>
<html>
<head>
<title>Excel to JSON Demo</title>
<script src="xlsx.full.min.js"></script>
</head>
<body>
<script>
/* set up XMLHttpRequest */
var url = "http://myclassbook.org/wp-content/uploads/2017/12/Test.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
var arraybuffer = oReq.response;
/* convert data to binary string */
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
/* Call XLSX */
var workbook = XLSX.read(bstr, {
type: "binary"
});
/* DO SOMETHING WITH workbook HERE */
var first_sheet_name = workbook.SheetNames[0];
/* Get worksheet */
var worksheet = workbook.Sheets[first_sheet_name];
console.log(XLSX.utils.sheet_to_json(worksheet, {
raw: true
}));
}
oReq.send();
</script>
</body>
</html>
Input:
Output:
Any reason you're not just using a simple for...in
loop?
var sample = { a: 1 , b: 2 , c:3 };
var summed = 0;
for (var key in sample) {
summed += sample[key];
};
If you are also trying to gzip dynamic pages (like aspx) and it isnt working, its probably because the option is not enabled (you need to install the Dynamic Content Compression module using Windows Features):
http://support.esri.com/en/knowledgebase/techarticles/detail/38616
I needed this for links, so I wrapped the span with an a-tag and a div, then centered the span tag itself
HTML
<div>
<a class="tester" href="#">
<span>Home</span>
</a>
</div>
CSS
.tester{
display: inline-block;
width: 9em;
height: 3em;
text-align: center;
}
.tester>span{
position: relative;
top: 25%;
}
I want to add something on @Michael Laffargue's post:
jqXHR.done()
is faster!
jqXHR.success()
have some load time in callback and sometimes can overkill script. I find that on hard way before.
UPDATE:
Using jqXHR.done()
, jqXHR.fail()
and jqXHR.always()
you can better manipulate with ajax request. Generaly you can define ajax in some variable or object and use that variable or object in any part of your code and get data faster. Good example:
/* Initialize some your AJAX function */
function call_ajax(attr){
var settings=$.extend({
call : 'users',
option : 'list'
}, attr );
return $.ajax({
type: "POST",
url: "//exapmple.com//ajax.php",
data: settings,
cache : false
});
}
/* .... Somewhere in your code ..... */
call_ajax({
/* ... */
id : 10,
option : 'edit_user'
change : {
name : 'John Doe'
}
/* ... */
}).done(function(data){
/* DO SOMETHING AWESOME */
});
Actually, valueOf
uses parseInt
internally. The difference is parseInt
returns an int
primitive while valueOf
returns an Integer
object. Consider from the Integer.class source:
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s, 10);
}
public static Integer valueOf(String s, int radix) throws NumberFormatException {
return Integer.valueOf(parseInt(s, radix));
}
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
As for parsing with a comma, I'm not familiar with one. I would sanitize them.
int million = Integer.parseInt("1,000,000".replace(",", ""));
You need to install the driver first. Follow the instructions on the Android's developers website:
In file config/database.php where :
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
Change this line to this :
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
The best solution would be to do these steps :
Run the project again, login into h2 and delete the table called "schema_version".
drop table schema_version;
Now make V2__create_shipwreck.sql file with ddl and rerun the project again.
Do remember this, add version 4.1.2 for flyway-core in pom.xml like
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
<version>4.1.2</version>
</dependency>
It should work now. Hope this will help.
For anyone interested, I ran into this same issue when using css modules and react css modules.
Most components have an associated css module style, and in this example my Button has its own css file, as does the Promo parent component. But I want to pass some additional styles to Button from Promo
So the style
able Button looks like this:
Button.js
import React, { Component } from 'react'
import CSSModules from 'react-css-modules'
import styles from './Button.css'
class Button extends Component {
render() {
let button = null,
className = ''
if(this.props.className !== undefined){
className = this.props.className
}
button = (
<button className={className} styleName='button'>
{this.props.children}
</button>
)
return (
button
);
}
};
export default CSSModules(Button, styles, {allowMultiple: true} )
In the above Button component the Button.css styles handle the common button styles. In this example just a .button
class
Then in my component where I want to use the Button, and I also want to modify things like the position of the button, I can set extra styles in Promo.css
and pass through as the className
prop. In this example again called .button
class. I could have called it anything e.g. promoButton
.
Of course with css modules this class will be .Promo__button___2MVMD
whereas the button one will be something like .Button__button___3972N
Promo.js
import React, { Component } from 'react';
import CSSModules from 'react-css-modules';
import styles from './Promo.css';
import Button from './Button/Button'
class Promo extends Component {
render() {
return (
<div styleName='promo' >
<h1>Testing the button</h1>
<Button className={styles.button} >
<span>Hello button</span>
</Button>
</div>
</Block>
);
}
};
export default CSSModules(Promo, styles, {allowMultiple: true} );
When I create an executable jar with dependencies (using this guide), all properties files are packaged into that jar too. How to stop it from happening? Thanks.
Properties files from where? Your main jar? Dependencies?
In the former case, putting resources under src/test/resources
as suggested is probably the most straight forward and simplest option.
In the later case, you'll have to create a custom assembly descriptor with special excludes/exclude
in the unpackOptions
.
The difference is that in the first case the retrieved user is not tracked by the context so when you are going to save the user back to database you must attach it and set correctly state of the user so that EF knows that it should update existing user instead of inserting a new one. In the second case you don't need to do that if you load and save the user with the same context instance because the tracking mechanism handles that for you.
In short:
import matplotlib.dates as mdates
myFmt = mdates.DateFormatter('%d')
ax.xaxis.set_major_formatter(myFmt)
Many examples on the matplotlib website. The one I most commonly use is here
I had the same issue (in Eclipse Juno), but I just wanted to change the default workspace to the one I'm using. There is a setting in:
ECLIPSE_DIRECTORY/configuration/config.ini
that is causing a specific workspace to be loaded without prompting for a workspace. If you just want to change the default workspace, you can just modify the value or add it if it doesn't exist:
[email protected]/some_workspace
or
osgi.instance.area.default=/some/absolute/path/some_workspace
The SpeechRecognition
library requires Python 3.3 or up:
Requirements
[...]
The first software requirement is Python 3.3 or better. This is required to use the library.
and from the Trove classifiers:
Programming Language :: Python
Programming Language :: Python :: 3
Programming Language :: Python :: 3.3
Programming Language :: Python :: 3.4
The urllib.request
module is part of the Python 3 standard library; in Python 2 you'd use urllib2
here.
>ssh user@serverip -p portnumber
>sudo bash (if user does not have bash shell else skip this line)
>cd /home/user/.ssh
>echo ssh_rsa...this is the key >> authorized_keys
I wrote with parameters that are predefined
They are not "predefined" logically, somewhere inside your code. But as arguments of SP they have no default values and are required. To avoid passing those params explicitly you have to define default values in SP definition:
Alter Procedure [Test]
@StartDate AS varchar(6) = NULL,
@EndDate AS varchar(6) = NULL
AS
...
NULLs or empty strings or something more sensible - up to you. It does not matter since you are overwriting values of those arguments in the first lines of SP.
Now you can call it without passing any arguments e.g.
exec dbo.TEST
The same error is produced in MariaDB (10.1.36-MariaDB) by using the combination of parenthesis and the COLLATE statement. My SQL was different, the error was the same, I had:
SELECT *
FROM table1
WHERE (field = 'STRING') COLLATE utf8_bin;
Omitting the parenthesis was solving it for me.
SELECT *
FROM table1
WHERE field = 'STRING' COLLATE utf8_bin;
In case you have some parameters to pass to a function and want a value in return. Here I am passing "12345" as an argument to a function and after processing returning variable XYZ which will be assigned to VALUE
#!/bin/bash
getValue()
{
ABC=$1
XYZ="something"$ABC
echo $XYZ
}
VALUE=$( getValue "12345" )
echo $VALUE
Output:
something12345
var seconds = 0;
setInterval(function () {
seconds++;
}, 1000);
There you go, now you have a variable counting seconds elapsed. Since I don't know the context, you'll have to decide whether you want to attach that variable to an object or make it global.
Set interval is simply a function that takes a function as it's first parameter and a number of milliseconds to repeat the function as it's second parameter.
You could also solve this by saving and comparing times.
EDIT: This answer will provide very inconsistent results due to things such as the event loop and the way browsers may choose to pause or delay processing when a page is in a background tab. I strongly recommend using the accepted answer.
I think you should not consider any specific parser implementation. Java API for XML Processing lets you use any conforming parser implementation in a standard way. The code should be much more portable, and when you realise that a specific parser has grown too old, you can replace it with another without changing a line of your code (if you do it correctly).
Basically there are three ways of handling XML in a standard way:
Forget about proprietary APIs such as JDOM or Apache ones (i.e. Apache Xerces XMLSerializer) because will tie you to a specific implementation that can evolve in time or lose backwards compatibility, which will make you change your code in the future when you want to upgrade to a new version of JDOM or whatever parser you use. If you stick to Java standard API (using factories and interfaces) your code will be much more modular and maintainable.
There is no need to say that all (I haven't checked all, but I'm almost sure) of the parsers proposed comply with a JAXP implementation so technically you can use all, no matter which.
Kotlin Version:
recyclerview.addItemDecoration(DividerItemDecoration(this, LinearLayoutManager.VERTICAL))
while (<@INC>)
This joins the paths in @INC together in a string, separated by spaces, then calls glob() on the string, which then iterates through the space-separated components (unless there are file-globbing meta-characters.)
This doesn't work so well if there are paths in @INC containing spaces, \, [], {}, *, ?, or ~, and there seems to be no reason to avoid the safe alternative:
for (@INC)