To adjust the length of the samples:
set key samplen X
(default is 4)
To adjust the vertical spacing of the samples:
set key spacing X
(default is 1.25)
and (for completeness), to adjust the fontsize:
set key font "<face>,<size>"
(default depends on the terminal)
And of course, all these can be combined into one line:
set key samplen 2 spacing .5 font ",8"
Note that you can also change the position of the key using set key at <position>
or any one of the pre-defined positions (which I'll just defer to help key
at this point)
In certain scenarios utilizing Bash's concatenation ability might be appropriate.
temp='this string is very long '
temp+='so I will separate it onto multiple lines'
echo $temp
this string is very long so I will separate it onto multiple lines
name=[value]...
...In the context where an assignment statement is assigning a value to a shell variable or array index, the += operator can be used to append to or add to the variable's previous value. When += is applied to a variable for which the integer attribute has been set, value is evaluated as an arithmetic expression and added to the variable's current value, which is also evaluated. When += is applied to an array variable using compound assignment (see Arrays below), the variable's value is not unset (as it is when using =), and new values are appended to the array beginning at one greater than the array's maximum index (for indexed arrays) or added as additional key-value pairs in an associative array. When applied to a string-valued variable, value is expanded and appended to the variable's value.
simply don't close in
remove in.close()
from your code.
The CSS code would be:
box-shadow: 0 0 10px 5px white;
That will shadow the entire DIV no matter its shape!
Right click on the server, then Add/Remove, then remove any projects that are in the Configured panel. Then right click on the server and choose "Clean..." from the context menu. Then the Server Locations option will be enabled.
ezpz's answer is almost perfect, but I hope I can add a little more.
Geo asked about time in milliseconds; this sounds like an integer quantity, and I wouldn't take the detour through floating-point land. Thus my approach would be:
irb(main):038:0> t8 = Time.now
=> Sun Nov 01 15:18:04 +0100 2009
irb(main):039:0> t9 = Time.now
=> Sun Nov 01 15:18:18 +0100 2009
irb(main):040:0> dif = t9 - t8
=> 13.940166
irb(main):041:0> (1000 * dif).to_i
=> 13940
Multiplying by an integer 1000 preserves the fractional number perfectly and may be a little faster too.
If you're dealing with dates and times, you may need to use the DateTime class. This works similarly but the conversion factor is 24 * 3600 * 1000 = 86400000 .
I've found DateTime's strptime and strftime functions invaluable in parsing and formatting date/time strings (e.g. to/from logs). What comes in handy to know is:
The formatting characters for these functions (%H, %M, %S, ...) are almost the same as for the C functions found on any Unix/Linux system; and
There are a few more: In particular, %L does milliseconds!
Swift 4 updated :
extension UIView {
var screenShot: UIImage? {
if #available(iOS 10, *) {
let renderer = UIGraphicsImageRenderer(bounds: self.bounds)
return renderer.image { (context) in
self.layer.render(in: context.cgContext)
}
} else {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 5);
if let _ = UIGraphicsGetCurrentContext() {
drawHierarchy(in: bounds, afterScreenUpdates: true)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return screenshot
}
return nil
}
}
}
in Vue 2.5.1 for button works
<button @click="firstFunction(); secondFunction();">Ok</button>
You can use $.browser to detect the browser name. possible values are :
or get a boolean flag: $.browser.msie will be true if the browser is MSIE.
as for the version number, if you are only interested in the major release number - you can use parseInt($.browser.version, 10). no need to parse the $.browser.version string yourself.
Anyway, The $.support property is available for detection of support for particular features rather than relying on $.browser.
You shouldn't use both ngRoute
and UI-router
. Here's a sample code for UI-router:
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
_x000D_
$stateProvider_x000D_
.state('state1', {_x000D_
url: "/state1",_x000D_
templateUrl: "partials/state1.html",_x000D_
controller: 'YourCtrl'_x000D_
})_x000D_
_x000D_
.state('state2', {_x000D_
url: "/state2",_x000D_
templateUrl: "partials/state2.html",_x000D_
controller: 'YourOtherCtrl'_x000D_
});_x000D_
$urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?
You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router
This is how you would drop the constraint
ALTER TABLE <schema_name, sysname, dbo>.<table_name, sysname, table_name>
DROP CONSTRAINT <default_constraint_name, sysname, default_constraint_name>
GO
With a script
-- t-sql scriptlet to drop all constraints on a table
DECLARE @database nvarchar(50)
DECLARE @table nvarchar(50)
set @database = 'dotnetnuke'
set @table = 'tabs'
DECLARE @sql nvarchar(255)
WHILE EXISTS(select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where constraint_catalog = @database and table_name = @table)
BEGIN
select @sql = 'ALTER TABLE ' + @table + ' DROP CONSTRAINT ' + CONSTRAINT_NAME
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where constraint_catalog = @database and
table_name = @table
exec sp_executesql @sql
END
Credits go to Jon Galloway http://weblogs.asp.net/jgalloway/archive/2006/04/12/442616.aspx
Window > Show view > Server
or right click on the server in "Servers" view, select "Properties".You may want to follow the steps above before starting the server. Because server location section goes grayed-unreachable.
Actually you don't get the meaning of Boolean method.It always return true if the variable is not null or empty.
var variable = some value;
Boolean(variable);
If my variable have some value then it will
return true
else
return false
You can't use Boolean as you think.
One liner FTW. I like to keep it simple. Why not use one command that contains ALL the arguments needed? This is how I like it - this creates an x509 certificate and its PEM key:
openssl req -x509 \
-nodes -days 365 -newkey rsa:4096 \
-keyout self.key.pem \
-out self-x509.crt \
-subj "/C=US/ST=WA/L=Seattle/CN=example.com/[email protected]"
That single command contains all the answers you would normally provide for the certificate details. This way you can set the parameters and run the command, get your output - then go for coffee.
Using collections.defaultdict
is a big time-saver when you're building dicts and don't know beforehand which keys you're going to have.
Here it's used twice: for the resulting dict, and for each of the values in the dict.
import collections
def aggregate_names(errors):
result = collections.defaultdict(lambda: collections.defaultdict(list))
for real_name, false_name, location in errors:
result[real_name][false_name].append(location)
return result
Combining this with your code:
dictionary = aggregate_names(previousFunction(string))
Or to test:
EXAMPLES = [
('Fred', 'Frad', 123),
('Jim', 'Jam', 100),
('Fred', 'Frod', 200),
('Fred', 'Frad', 300)]
print aggregate_names(EXAMPLES)
My comment was deleted because I provided a link to a similar question I answered here. Ergo, I'll answer it more descriptively this time. Here goes.
You could do this easily by creating a CreateRoles
method in your startup
class. This helps check if the roles are created, and creates the roles if they aren't; on application startup. Like so.
private async Task CreateRoles(IServiceProvider serviceProvider)
{
//initializing custom roles
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
string[] roleNames = { "Admin", "Manager", "Member" };
IdentityResult roleResult;
foreach (var roleName in roleNames)
{
var roleExist = await RoleManager.RoleExistsAsync(roleName);
if (!roleExist)
{
//create the roles and seed them to the database: Question 1
roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
}
}
//Here you could create a super user who will maintain the web app
var poweruser = new ApplicationUser
{
UserName = Configuration["AppSettings:UserName"],
Email = Configuration["AppSettings:UserEmail"],
};
//Ensure you have these values in your appsettings.json file
string userPWD = Configuration["AppSettings:UserPassword"];
var _user = await UserManager.FindByEmailAsync(Configuration["AppSettings:AdminUserEmail"]);
if(_user == null)
{
var createPowerUser = await UserManager.CreateAsync(poweruser, userPWD);
if (createPowerUser.Succeeded)
{
//here we tie the new user to the role
await UserManager.AddToRoleAsync(poweruser, "Admin");
}
}
}
and then you could call the CreateRoles(serviceProvider).Wait();
method from the Configure
method in the Startup class.
ensure you have IServiceProvider
as a parameter in the Configure
class.
Using role-based authorization in a controller to filter user access: Question 2
You can do this easily, like so.
[Authorize(Roles="Manager")]
public class ManageController : Controller
{
//....
}
You can also use role-based authorization in the action method like so. Assign multiple roles, if you will
[Authorize(Roles="Admin, Manager")]
public IActionResult Index()
{
/*
.....
*/
}
While this works fine, for a much better practice, you might want to read about using policy based role checks. You can find it on the ASP.NET core documentation here, or this article I wrote about it here
For the different python versions:
Visual C++ |CPython
--------------------
14.0 |3.5
10.0 |3.3, 3.4
9.0 |2.6, 2.7, 3.0, 3.1, 3.2
Source: Windows Compilers for py
Also refer: this answer
The interface
keyword indicates that you are declaring a traditional interface class in Java.
The @interface
keyword is used to declare a new annotation type.
See docs.oracle tutorial on annotations for a description of the syntax.
See the JLS if you really want to get into the details of what @interface
means.
check this out, works on firefox and IE
<style>
html, body
{
height: 100%;
}
.content
{
min-height: 100%;
}
.footer
{
position: relative;
clear: both;
}
</style>
<body>
<div class="content">Page content
</div>
<div class="footer">this is my footer
</div>
</body>
Automatically not split data to multi pages. You may split manually.
If your ( rowCount * rowHeight ) > 420mm ( A3 Height in mm ) add new page function. ( Sorry I can't edit your code without run ) After add new page leftMargin, topMargin = 0; ( start over ) I added sample code with yours. I hope it's right.
else {
doc.margins = 1;
doc.setFont("Times ");
doc.setFontType("normal ");
doc.setFontSize(11);
if ( rowCount * rowHeight > 420 ) {
doc.addPage();
rowCount = 3; // skip 1 and 2 above
} else {
// now rowcount = 3 ( top of new page for 3 )
// j is your x axis cell index ( j start from 0 on $.each function ) or you can add cellCount like rowCount and replace with
// rowcount is your y axis cell index
left = ( ( j ) * ( cellWidth + leftMargin );
top = ( ( rowcount - 3 ) * ( rowHeight + topMargin );
doc.cell( leftMargin, top, cellWidth, rowHeight, cellContent, i);
// 1st=left margin 2nd parameter=top margin, 3rd=row cell width 4th=Row height
}
}
You can convert html directly to pdf lossless. Youtube video for html => pdf example
Expand to database name >> expand to table >> expand to keys >> copy the name of key then execute the below command:
ALTER TABLE Test DROP UQ__test__3213E83EB607700F;
Here UQ__test__3213E83EB607700F is the name of unique key which was created on a particular column on test table.
You have to read
database column
here. You could have a look on following code snippet
string connectionString = ConfigurationManager.ConnectionStrings["NameOfYourSqlConnectionString"].ConnectionString;
using (var _connection = new SqlConnection(connectionString))
{
_connection.Open();
using (SqlCommand command = new SqlCommand("SELECT SomeColumnName FROM TableName", _connection))
{
SqlDataReader sqlDataReader = command.ExecuteReader();
if (sqlDataReader.HasRows)
{
while (sqlDataReader.Read())
{
string YourFirstDataBaseTableColumn = sqlDataReader["SomeColumn"].ToString(); // Remember Type Casting is required here it has to be according to database column data type
string YourSecondDataBaseTableColumn = sqlDataReader["SomeColumn"].ToString();
string YourThridDataBaseTableColumn = sqlDataReader["SomeColumn"].ToString();
}
}
sqlDataReader.Close();
}
_connection.Close();
This is like user3076252's answer, but you'll be choosing a different set of options:
It should find your unbound JRE, but this time with all the numbers in it's name (rather than unbound), and you can select it. It will take a while to search the drive, but you can stop it at any time, and it will save the results, if any.
Warning:
eval()
can be used to execute arbitrary Python code. You should never useeval()
with untrusted strings. (See Security of Python's eval() on untrusted strings?)
This seems simplest.
>>> class Foo(object):
... pass
...
>>> eval("Foo")
<class '__main__.Foo'>
You have to use active in the label to make it work as mentioned above. But you can use checked="checked" and it will work too. It's not necessary but it's more legible and makes more sense as it is more html format compliance.
You can use the next code:
JS
function showname () {
var name = document.getElementById('fileInput');
alert('Selected file: ' + name.files.item(0).name);
alert('Selected file: ' + name.files.item(0).size);
alert('Selected file: ' + name.files.item(0).type);
};
HTML
<body>
<p>
<input type="file" id="fileInput" multiple onchange="showname()"/>
</p>
</body>
You should be able to access the query using dot notation now.
If you want to access say you are receiving a GET request at /checkEmail?type=email&utm_source=xxxx&email=xxxxx&utm_campaign=XX
and you want to fetch out the query used.
var type = req.query.type,
email = req.query.email,
utm = {
source: req.query.utm_source,
campaign: req.query.utm_campaign
};
Params are used for the self defined parameter for receiving request, something like (example):
router.get('/:userID/food/edit/:foodID', function(req, res){
//sample GET request at '/xavg234/food/edit/jb3552'
var userToFind = req.params.userID;//gets xavg234
var foodToSearch = req.params.foodID;//gets jb3552
User.findOne({'userid':userToFind}) //dummy code
.then(function(user){...})
.catch(function(err){console.log(err)});
});
The accepted answer offers a solution which requires changing of the underlying data frame. This is not necessary. One can also simply factorise within the aes()
call directly or create a vector for that instead.
This is certainly not much different than user Drew Steen's answer, but with the important difference of not changing the original data frame.
level_order <- c('virginica', 'versicolor', 'setosa') #this vector might be useful for other plots/analyses
ggplot(iris, aes(x = factor(Species, level = level_order), y = Petal.Width)) + geom_col()
or
level_order <- factor(iris$Species, level = c('virginica', 'versicolor', 'setosa'))
ggplot(iris, aes(x = level_order, y = Petal.Width)) + geom_col()
or
directly in the aes()
call without a pre-created vector:
ggplot(iris, aes(x = factor(Species, level = c('virginica', 'versicolor', 'setosa')), y = Petal.Width)) + geom_col()
Using the awesome psutil
library it's pretty simple:
p = psutil.Process(pid)
p.terminate() #or p.kill()
If you don't want to install a new library, you can use the os
module:
import os
import signal
os.kill(pid, signal.SIGTERM) #or signal.SIGKILL
See also the os.kill
documentation.
If you are interested in starting the command python StripCore.py
if it is not running, and killing it otherwise, you can use psutil
to do this reliably.
Something like:
import psutil
from subprocess import Popen
for process in psutil.process_iter():
if process.cmdline() == ['python', 'StripCore.py']:
print('Process found. Terminating it.')
process.terminate()
break
else:
print('Process not found: starting it.')
Popen(['python', 'StripCore.py'])
Sample run:
$python test_strip.py #test_strip.py contains the code above
Process not found: starting it.
$python test_strip.py
Process found. Terminating it.
$python test_strip.py
Process not found: starting it.
$killall python
$python test_strip.py
Process not found: starting it.
$python test_strip.py
Process found. Terminating it.
$python test_strip.py
Process not found: starting it.
Note: In previous psutil
versions cmdline
was an attribute instead of a method.
true
and false
are not meant to be strings in this context.
You want the literal true
and false
Boolean
values.
startButton.disabled = true;
startButton.disabled = false;
The reason it sort of works (disables the element) is because a non empty string is truthy. So assigning 'false'
to the disabled
property has the same effect of setting it to true
.
if you are anything like me coming from a google search and looking to remove an html element with cool animation, then this could help you:
$(document).ready(function() {_x000D_
_x000D_
var $deleteButton = $('.deleteItem');_x000D_
_x000D_
$deleteButton.on('click', function(event) {_x000D_
_x000D_
event.preventDefault();_x000D_
_x000D_
var $button = $(this);_x000D_
_x000D_
if(confirm('Are you sure about this ?')) {_x000D_
_x000D_
var $item = $button.closest('tr.item');_x000D_
_x000D_
$item.addClass('removed-item')_x000D_
_x000D_
.one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e) {_x000D_
_x000D_
$(this).remove();_x000D_
});_x000D_
}_x000D_
_x000D_
});_x000D_
_x000D_
});
_x000D_
/**_x000D_
* Credit to Sara Soueidan_x000D_
* @link https://github.com/SaraSoueidan/creative-list-effects/blob/master/css/styles-3.css_x000D_
*/_x000D_
_x000D_
.removed-item {_x000D_
-webkit-animation: removed-item-animation .8s cubic-bezier(.65,-0.02,.72,.29);_x000D_
-o-animation: removed-item-animation .8s cubic-bezier(.65,-0.02,.72,.29);_x000D_
animation: removed-item-animation .8s cubic-bezier(.65,-0.02,.72,.29)_x000D_
}_x000D_
_x000D_
@keyframes removed-item-animation {_x000D_
0% {_x000D_
opacity: 1;_x000D_
-webkit-transform: translateX(0);_x000D_
-ms-transform: translateX(0);_x000D_
-o-transform: translateX(0);_x000D_
transform: translateX(0)_x000D_
}_x000D_
_x000D_
30% {_x000D_
opacity: 1;_x000D_
-webkit-transform: translateX(50px);_x000D_
-ms-transform: translateX(50px);_x000D_
-o-transform: translateX(50px);_x000D_
transform: translateX(50px)_x000D_
}_x000D_
_x000D_
80% {_x000D_
opacity: 1;_x000D_
-webkit-transform: translateX(-800px);_x000D_
-ms-transform: translateX(-800px);_x000D_
-o-transform: translateX(-800px);_x000D_
transform: translateX(-800px)_x000D_
}_x000D_
_x000D_
100% {_x000D_
opacity: 0;_x000D_
-webkit-transform: translateX(-800px);_x000D_
-ms-transform: translateX(-800px);_x000D_
-o-transform: translateX(-800px);_x000D_
transform: translateX(-800px)_x000D_
}_x000D_
}_x000D_
_x000D_
@-webkit-keyframes removed-item-animation {_x000D_
0% {_x000D_
opacity: 1;_x000D_
-webkit-transform: translateX(0);_x000D_
transform: translateX(0)_x000D_
}_x000D_
_x000D_
30% {_x000D_
opacity: 1;_x000D_
-webkit-transform: translateX(50px);_x000D_
transform: translateX(50px)_x000D_
}_x000D_
_x000D_
80% {_x000D_
opacity: 1;_x000D_
-webkit-transform: translateX(-800px);_x000D_
transform: translateX(-800px)_x000D_
}_x000D_
_x000D_
100% {_x000D_
opacity: 0;_x000D_
-webkit-transform: translateX(-800px);_x000D_
transform: translateX(-800px)_x000D_
}_x000D_
}_x000D_
_x000D_
@-o-keyframes removed-item-animation {_x000D_
0% {_x000D_
opacity: 1;_x000D_
-o-transform: translateX(0);_x000D_
transform: translateX(0)_x000D_
}_x000D_
_x000D_
30% {_x000D_
opacity: 1;_x000D_
-o-transform: translateX(50px);_x000D_
transform: translateX(50px)_x000D_
}_x000D_
_x000D_
80% {_x000D_
opacity: 1;_x000D_
-o-transform: translateX(-800px);_x000D_
transform: translateX(-800px)_x000D_
}_x000D_
_x000D_
100% {_x000D_
opacity: 0;_x000D_
-o-transform: translateX(-800px);_x000D_
transform: translateX(-800px)_x000D_
}_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width">_x000D_
<title>JS Bin</title>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<table class="table table-striped table-bordered table-hover">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>id</th>_x000D_
<th>firstname</th>_x000D_
<th>lastname</th>_x000D_
<th>@twitter</th>_x000D_
<th>action</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
_x000D_
<tr class="item">_x000D_
<td>1</td>_x000D_
<td>Nour-Eddine</td>_x000D_
<td>ECH-CHEBABY</td>_x000D_
<th>@__chebaby</th>_x000D_
<td><button class="btn btn-danger deleteItem">Delete</button></td>_x000D_
</tr>_x000D_
_x000D_
<tr class="item">_x000D_
<td>2</td>_x000D_
<td>John</td>_x000D_
<td>Doe</td>_x000D_
<th>@johndoe</th>_x000D_
<td><button class="btn btn-danger deleteItem">Delete</button></td>_x000D_
</tr>_x000D_
_x000D_
<tr class="item">_x000D_
<td>3</td>_x000D_
<td>Jane</td>_x000D_
<td>Doe</td>_x000D_
<th>@janedoe</th>_x000D_
<td><button class="btn btn-danger deleteItem">Delete</button></td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
_x000D_
<script src="https://code.jquery.com/jquery.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
"this" keyword refers to current class reference. That means, when it is used inside the method, the 'current' class is still SubClass and so, the answer is explained.
simply use the Out-File cmd but DON'T forget to give an encoding type:
-Encoding UTF8
so use it so:
$log | Out-File -Append C:\as\whatever.csv -Encoding UTF8
-Append is required if you want to write in the file more then once.
The following formula determines if the text "CHECK" appears in cell C10. If it does not, the result is blank. If it does, the result is the work "CHECK".
=IF(ISERROR(FIND("CHECK",C10,1)),"","CHECK")
Use jQuery
Look how easy it would be if you did.
Example:
$('#td1').html('hello world');
Download source code from here (Open Pdf from url in Android Programmatically)
MainActivity.java
package com.deepshikha.openpdf;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
WebView webview;
ProgressBar progressbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView)findViewById(R.id.webview);
progressbar = (ProgressBar) findViewById(R.id.progressbar);
webview.getSettings().setJavaScriptEnabled(true);
String filename ="http://www3.nd.edu/~cpoellab/teaching/cse40816/android_tutorial.pdf";
webview.loadUrl("http://docs.google.com/gview?embedded=true&url=" + filename);
webview.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
// do your stuff here
progressbar.setVisibility(View.GONE);
}
});
}
}
Thanks!
I finally found the fix for this!
As we have found, IB doesn't allow us to change the height of the rounded corner border style. So change it to any of the other styles and set the desired height. In the code change the border style back.
textField.borderStyle = UITextBorderStyleRoundedRect;
I solved my problem with this code
public void setLocale(String lang) {
myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
onConfigurationChanged(conf);
}
@Override
public void onConfigurationChanged(Configuration newConfig)
{
iv.setImageDrawable(getResources().getDrawable(R.drawable.keyboard));
greet.setText(R.string.greet);
textView1.setText(R.string.langselection);
super.onConfigurationChanged(newConfig);
}
There is Effort which is an in memory entity framework database provider. I've not actually tried it... Haa just spotted this was mentioned in the question!
Alternatively you could switch to EntityFrameworkCore which has an in memory database provider built-in.
https://github.com/tamasflamich/effort
I used a factory to get a context, so i can create the context close to its use. This seems to work locally in visual studio but not on my TeamCity build server, not sure why yet.
return new MyContext(@"Server=(localdb)\mssqllocaldb;Database=EFProviders.InMemory;Trusted_Connection=True;");
It may be too late to answer the question but since Google still leads people here, I decide to write my solution here.
That is, since Python 2.7, the math
library has integrated the error function math.erf(x)
The erf()
function can be used to compute traditional statistical functions such as the cumulative standard normal distribution:
from math import *
def phi(x):
#'Cumulative distribution function for the standard normal distribution'
return (1.0 + erf(x / sqrt(2.0))) / 2.0
Ref:
https://docs.python.org/2/library/math.html
https://docs.python.org/3/library/math.html
How are the Error Function and Standard Normal distribution function related?
Try this code my friend...
#include<stdio.h>
int main(){
char *s1, *s2;
char str[10];
printf("type a string: ");
scanf("%s", str);
s1 = &str[0];
s2 = &str[2];
printf("%c\n", *s1); //use %c instead of %s and *s1 which is the content of position 1
printf("%c\n", *s2); //use %c instead of %s and *s3 which is the content of position 1
return 0;
}
In Python 3 the dict.values()
method returns a dictionary view object, not a list like it does in Python 2. Dictionary views have a length, can be iterated, and support membership testing, but don't support indexing.
To make your code work in both versions, you could use either of these:
{names[i]:value for i,value in enumerate(d.values())}
or
values = list(d.values())
{name:values[i] for i,name in enumerate(names)}
By far the simplest, fastest way to do the same thing in either version would be:
dict(zip(names, d.values()))
Note however, that all of these methods will give you results that will vary depending on the actual contents of d
. To overcome that, you may be able use an OrderedDict instead, which remembers the order that keys were first inserted into it, so you can count on the order of what is returned by the values()
method.
Also you can use ss utility to dump sockets statistics.
To dump summary:
ss -s
Total: 91 (kernel 0)
TCP: 18 (estab 11, closed 0, orphaned 0, synrecv 0, timewait 0/0), ports 0
Transport Total IP IPv6
* 0 - -
RAW 0 0 0
UDP 4 2 2
TCP 18 16 2
INET 22 18 4
FRAG 0 0 0
To display all sockets:
ss -a
To display UDP sockets:
ss -u -a
To display TCP sockets:
ss -t -a
Here you can read ss man: ss
I have modified the buffer case like this:
def CountLines(filename):
f = open(filename)
try:
lines = 1
buf_size = 1024 * 1024
read_f = f.read # loop optimization
buf = read_f(buf_size)
# Empty file
if not buf:
return 0
while buf:
lines += buf.count('\n')
buf = read_f(buf_size)
return lines
finally:
f.close()
Now also empty files and the last line (without \n) are counted.
How about this? Here you split the array using the length you want to have.
a = np.random.randint(0,10,[4,4])
a
Out[27]:
array([[1, 5, 8, 7],
[3, 2, 4, 0],
[7, 7, 6, 2],
[7, 4, 3, 0]])
a[0:2,:]
Out[28]:
array([[1, 5, 8, 7],
[3, 2, 4, 0]])
a[2:4,:]
Out[29]:
array([[7, 7, 6, 2],
[7, 4, 3, 0]])
Try creating a shell script like the one below:
#!/bin/bash
mysql --user=[username] --password=[password] --database=[db name] --execute="DELETE FROM tbl_message WHERE DATEDIFF( NOW( ) , timestamp ) >=7"
You can then add this to the cron
You can, of course, show it before making the request, and hide it after it completes:
$('#loading-image').show();
$.ajax({
url: uri,
cache: false,
success: function(html){
$('.info').append(html);
},
complete: function(){
$('#loading-image').hide();
}
});
I usually prefer the more general solution of binding it to the global ajaxStart and ajaxStop events, that way it shows up for all ajax events:
$('#loading-image').bind('ajaxStart', function(){
$(this).show();
}).bind('ajaxStop', function(){
$(this).hide();
});
32-bit builds of PHP:
64-bit builds of PHP:
Numbers are inclusive.
Note: some 64-bit builds once used 32-bit integers, particularly older Windows builds of PHP
Values outside of these ranges are represented by floating point values, as are non-integer values within these ranges. The interpreter will automatically determine when this switch to floating point needs to happen based on whether the result value of a calculation can't be represented as an integer.
PHP has no support for "unsigned" integers as such, limiting the maximum value of all integers to the range of a "signed" integer.
In PHP use .=
to append strings, and not +=
.
Why does this output 0? [...] Does PHP not like += with strings?
+=
is an arithmetic operator to add a number to another number. Using that operator with strings leads to an automatic type conversion. In the OP's case the strings have been converted to integers of the value 0
.
More about operators in PHP:
There is a version conflict between jar/dependency please check all version of spring is same. if you use maven remove version of dependency and use Spring.io dependency.it handle version conflict. Add this in your pom
<dependency>
<groupId>io.spring.platform</groupId>
<artifactId>platform-bom</artifactId>
<version>2.0.1.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
TortoiseSVN contains a console svn client, but by default the corresponding option is not enabled during installation.
The svn.exe
executable is not standalone and it depends on some other files in the distribution but this should not be a problem in most cases.
Once installed you might need to add the folder containing svn.exe
to the system PATH
as described here so that it is available in your console. To check if it was already added by the installer open a new console and type echo %PATH%
. Use set
on its own to see all environmental variables.
also you can check the version of symfony and versions of all other installed packages by running
composer show
or
composer show | grep sonata
to get versions of specific packages like sonata etc.
You can also have a look at this related question. That user reported that using a join provided better performance than using a sub query.
I had a similar question and actually used one of the answers with BeautifulSoup. The problem was it was really slow. I ended up using library called selectolax. It's pretty limited but it works for this task. The only issue was that I had manually remove unnecessary white spaces. But it seems to be working much faster that BeautifulSoup solution.
from selectolax.parser import HTMLParser
def get_text_selectolax(html):
tree = HTMLParser(html)
if tree.body is None:
return None
for tag in tree.css('script'):
tag.decompose()
for tag in tree.css('style'):
tag.decompose()
text = tree.body.text(separator='')
text = " ".join(text.split()) # this will remove all the whitespaces
return text
You don't need git to accomplish this. Creative use of a bash function will do the trick just fine. If you don't care about messages, just set a default one and forget it.
function gitcom() {
git commit -m "my default commit message"
}
If you were feeling really adventurous you could add, commit and push with one command
function gitzap() {
git add . && git commit -m "whatevs" && git push $1 $2
}
Which you would then run as
gitzap origin master
You could even get deeper and use parse_git_branch to save yourself some keystrokes there, or set a common default of "origin" and "master".
Even though you see the time in HH:MM AM/PM format, on the backend it still works in 24 hour format, you can try using some basic javascript to see that.
I found this to work for me:
iconv -f ISO-8859-14 Agreement.txt -t UTF-8 -o agreement.txt
Paint DOES have set color function.
/**
* Set the paint's color. Note that the color is an int containing alpha
* as well as r,g,b. This 32bit value is not premultiplied, meaning that
* its alpha can be any value, regardless of the values of r,g,b.
* See the Color class for more details.
*
* @param color The new color (including alpha) to set in the paint.
*/
public native void setColor(@ColorInt int color);
As an Android developer, I set paint color like this...
paint.setColor(getResources().getColor(R.color.xxx));
I define the color value on color.xml something like...
<color name="xxx">#008fd2</color>
By the way if you want to the hex RGB value of specific color value, then you can check website like this: http://www.rapidtables.com/web/color/RGB_Color.htm
I hope this helps ! Enjoy coding!
This worked for me :
date -d '20121212 7 days'
date -d '12-DEC-2012 7 days'
date -d '2012-12-12 7 days'
date -d '2012-12-12 4:10:10PM 7 days'
date -d '2012-12-12 16:10:55 7 days'
then you can format output adding parameter '+%Y%m%d'
Seconds with 2 decimal spaces:
Dim startTime As Single 'start timer
MsgBox ("run time: " & Format((Timer - startTime) / 1000000, "#,##0.00") & " seconds") 'end timer
Milliseconds:
Dim startTime As Single 'start timer
MsgBox ("run time: " & Format((Timer - startTime), "#,##0.00") & " milliseconds") 'end timer
Milliseconds with comma seperator:
Dim startTime As Single 'start timer
MsgBox ("run time: " & Format((Timer - startTime) * 1000, "#,##0.00") & " milliseconds") 'end timer
Just leaving this here for anyone that was looking for a simple timer formatted with seconds to 2 decimal spaces like I was. These are short and sweet little timers I like to use. They only take up one line of code at the beginning of the sub or function and one line of code again at the end. These aren't meant to be crazy accurate, I generally don't care about anything less then 1/100th of a second personally, but the milliseconds timer will give you the most accurate run time of these 3. I've also read you can get the incorrect read out if it happens to run while crossing over midnight, a rare instance but just FYI.
use first parameter as your application name. Log.d("your_Application_Name","message");
and in LogCat : create Filter ---> Filter Name & by Log Tag: is equal to 'your_Application_Name' it will create new tab for your application.
Use the function Contains
from the strings package.
import (
"strings"
)
strings.Contains("something", "some") // true
It is possible of course, use -l:
instead of -l
. For example -l:libXYZ.a
to link with libXYZ.a
. Notice the lib
written out, as opposed to -lXYZ
which would auto expand to libXYZ
.
I just wrote a quick plugin to run a test using your same snippet and it works fine
$.fn.test = function() {
return this.each(function(){
var new_id = 5;
$(this).attr('id', this.id + '_' + new_id);
$(this).attr('name', this.name + '_' + new_id);
$(this).attr('value', 'test');
});
};
$(document).ready(function() {
$('#field_id').test()
});
<body>
<div id="container">
<input type="text" name="field_name" id="field_id" value="meh" />
</div>
</body>
So I can only presume something else is going on in your code. Can you provide some more details?
You can actually handle all of this with just a simple template tag. See http://jsfiddle.net/m4ve9/ for an example. Note that I actually didn't need a compile or link property on the super-directive definition.
During the compilation process, Angular pulls in the template values before compiling, so you can attach any further directives there and Angular will take care of it for you.
If this is a super directive that needs to preserve the original internal content, you can use transclude : true
and replace the inside with <ng-transclude></ng-transclude>
Hope that helps, let me know if anything is unclear
Alex
No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<xsl:variable name="mapping">
<item key="1" v1="A" v2="B" />
<item key="2" v1="X" v2="Y" />
</xsl:variable>
<xsl:variable name="mappingNode"
select="document('')//xsl:variable[@name = 'mapping']" />
<xsl:template match="....">
<xsl:variable name="testVariable" select="'1'" />
<xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />
<xsl:variable name="variable1" select="$values/@v1" />
<xsl:variable name="variable2" select="$values/@v2" />
</xsl:template>
</xsl:stylesheet>
In fact, once you've got the values
variable, you may not even need separate variable1
and variable2
variables. You could just use $values/@v1
and $values/@v2
instead.
In some applications TCP is faster (better throughput) than UDP.
This is the case when doing lots of small writes relative to the MTU size. For example, I read an experiment in which a stream of 300 byte packets was being sent over Ethernet (1500 byte MTU) and TCP was 50% faster than UDP.
The reason is because TCP will try and buffer the data and fill a full network segment thus making more efficient use of the available bandwidth.
UDP on the other hand puts the packet on the wire immediately thus congesting the network with lots of small packets.
You probably shouldn't use UDP unless you have a very specific reason for doing so. Especially since you can give TCP the same sort of latency as UDP by disabling the Nagle algorithm (for example if you're transmitting real-time sensor data and you're not worried about congesting the network with lot's of small packets).
type data1.csv > combined.csv
type data2.csv >> combined.csv
type data3.csv >> combined.csv
type data4.csv >> combined.csv
etc.
Assume that your using files without headers and all files have the same columns.
How do I create a new column with Groupby().Sum()?
There are two ways - one straightforward and the other slightly more interesting.
GroupBy.transform()
with 'sum'
@Ed Chum's answer can be simplified, a bit. Call DataFrame.groupby
rather than Series.groupby
. This results in simpler syntax.
# The setup.
df[['Date', 'Data3']]
Date Data3
0 2015-05-08 5
1 2015-05-07 8
2 2015-05-06 6
3 2015-05-05 1
4 2015-05-08 50
5 2015-05-07 100
6 2015-05-06 60
7 2015-05-05 120
df.groupby('Date')['Data3'].transform('sum')
0 55
1 108
2 66
3 121
4 55
5 108
6 66
7 121
Name: Data3, dtype: int64
It's a tad faster,
df2 = pd.concat([df] * 12345)
%timeit df2['Data3'].groupby(df['Date']).transform('sum')
%timeit df2.groupby('Date')['Data3'].transform('sum')
10.4 ms ± 367 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
8.58 ms ± 559 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
GroupBy.sum()
+ Series.map()
I stumbled upon an interesting idiosyncrasy in the API. From what I tell, you can reproduce this on any major version over 0.20 (I tested this on 0.23 and 0.24). It seems like you consistently can shave off a few milliseconds of the time taken by transform
if you instead use a direct function of GroupBy
and broadcast it using map
:
df.Date.map(df.groupby('Date')['Data3'].sum())
0 55
1 108
2 66
3 121
4 55
5 108
6 66
7 121
Name: Date, dtype: int64
Compare with
df.groupby('Date')['Data3'].transform('sum')
0 55
1 108
2 66
3 121
4 55
5 108
6 66
7 121
Name: Data3, dtype: int64
My tests show that map
is a bit faster if you can afford to use the direct GroupBy
function (such as mean
, min
, max
, first
, etc). It is more or less faster for most general situations upto around ~200 thousand records. After that, the performance really depends on the data.
(Left: v0.23, Right: v0.24)
Nice alternative to know, and better if you have smaller frames with smaller numbers of groups. . . but I would recommend transform
as a first choice. Thought this was worth sharing anyway.
Benchmarking code, for reference:
import perfplot
perfplot.show(
setup=lambda n: pd.DataFrame({'A': np.random.choice(n//10, n), 'B': np.ones(n)}),
kernels=[
lambda df: df.groupby('A')['B'].transform('sum'),
lambda df: df.A.map(df.groupby('A')['B'].sum()),
],
labels=['GroupBy.transform', 'GroupBy.sum + map'],
n_range=[2**k for k in range(5, 20)],
xlabel='N',
logy=True,
logx=True
)
Not sure if this help or not but this is a command line tool which let you simply send test mails from a SMTP server priodically. http://code.google.com/p/woodpecker-tester/
I like Postgresql Maestro. I also use their version for MySql. I'm pretty statisfied with their product. Or you can use the free tool PgAdmin.
I appreciate that the other solutions do not depend on any other software tool, but why not just use another programming language that can interface to SQLite such as C#, C++, Go, Haskell, Java, Lua, Python, or Rust?
Avoid /etc/*release* files and run this command instead, it is far more reliable and gives more details:
rpm -qia '*release*'
Input elements have a property called disabled
. When the form submits, just run some code like this:
var myInput = document.getElementById('myInput');
myInput.disabled = true;
I was having the same issue, as everyone else I suppose.. adding the System.setProperties(....) didn't fix it for me.
So my email client is in a separate project uploaded to an artifactory. I'm importing this project into other projects as a gradle dependency. My problem was that I was using implementation
in my build.gradle for javax.mail
, which was causing issues downstream.
I changed this line from implementation
to api
and my downstream project started working and connecting again.
sudo chown -R $USER /usr/local/lib/node_modules This command will work
With xidel:
curl <...> | xidel - -se '$json'
xidel
can probably retrieve the JSON for you as well.
When you are using JVM in 32-bit mode, the maximum heap size that can be allocated is 1280 MB. So, if you want to go beyond that, you need to invoke JVM in 64-mode.
You can use following:
$ java -d64 -Xms512m -Xmx4g HelloWorld
where,
You can tune in -Xms and -Xmx as per you requirements (YMMV)
A very good resource on JVM performance tuning, which might want to look into: http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html
I'm really fond of SPL Library, they offer iterator's, including RecursiveDirectoryIterator.
RegEx is the way to go in most cases.
In some cases, it may be faster to specify more elements or the specific element to perform the replace on:
$(document).ready(function () {
$('.myclass').each(function () {
$('img').each(function () {
$(this).attr('src', $(this).attr('src').replace('_s.jpg', '_n.jpg'));
})
})
});
This does the replace once on each string, but it does it using a more specific selector.
Similar to Olayinka's answer about the configuration file for ADT: I just had the same issue on IntelliJ's IdeaU v14.
I'm working through a tutorial that had me change the starting activity from MyActivity
to MyListActivity
(Which is a list of MyActivity
). I started getting Permissions Denial.
After much trial, toil and pain: In .idea\workspace.xml:
...
<configuration default="false" name="MyApp" type="AndroidRunConfigurationType" factoryName="Android Application">
<module name="MyApp" />
<option name="ACTIVITY_CLASS" value="com.domain.MyApp.MyActivity" />
...
</configuration>
...
I changed the MyActivity
to MyListActivity
, reloaded the project and I'm off to a rolling start again.
Not sure which IDE you are using, but maybe your IDE is overriding or forcing a specific starting activity?
You need no script, only set the correct option and create an environment variable.
shopt -s cdable_vars
in your ~/.bashrc
allows to cd
to the content of environment variables.
Create such an environment variable:
export myjava="/home/tree/projects/java"
and you can use:
cd myjava
All those answers are good, but in fact, if you want to understand, the extension directory need to be right if you want all you uncommented extensions to work. Can write a physical or relative path like
extension_dir = "C:/myStack/php/ext"
or
extension_dir = "../../php/ext"
It's relative to the httpd.exe Apache web server (C:\myStack\apache\bin) But if you want it to work with Composer or anything you need the physical path because the cli mode doesn't use the web server !
This solves the problem of releasing the memory for me!!!
import gc
import pandas as pd
del [[df_1,df_2]]
gc.collect()
df_1=pd.DataFrame()
df_2=pd.DataFrame()
the data-frame will be explicitly set to null
in the above statements
Firstly, the self reference of the dataframe is deleted meaning the dataframe is no longer available to python there after all the references of the dataframe is collected by garbage collector (gc.collect()) and then explicitly set all the references to empty dataframe.
more on the working of garbage collector is well explained in https://stackify.com/python-garbage-collection/
from pyspark.sql.types import IntegerType
data_df = data_df.withColumn("Plays", data_df["Plays"].cast(IntegerType()))
data_df = data_df.withColumn("drafts", data_df["drafts"].cast(IntegerType()))
You can run loop for each column but this is the simplest way to convert string column into integer.
For importing a large SQL file using the command line in MySQL.
First go to file path at the command line. Then,
Option 1:
mysql -u {user_name} -p{password} {database_name} < your_file.sql
It's give a warning mesaage : Using a password on the command line interface can be insecure.
Done.Your file will be imported.
Option 2:
mysql -u {user_name} -p {database_name} < your_file.sql
in this you are not provide sql password then they asked for password just enter password and your file will be imported.
This page on string::string
gives two potential constructors that would do what you want:
string ( const char * s, size_t n );
string ( const string& str, size_t pos, size_t n = npos );
Example:
#include<cstdlib>
#include<cstring>
#include<string>
#include<iostream>
using namespace std;
int main(){
char* p= (char*)calloc(30, sizeof(char));
strcpy(p, "Hello world");
string s(p, 15);
cout << s.size() << ":[" << s << "]" << endl;
string t(p, 0, 15);
cout << t.size() << ":[" << t << "]" << endl;
free(p);
return 0;
}
Output:
15:[Hello world]
11:[Hello world]
The first form considers p
to be a simple array, and so will create (in our case) a string of length 15, which however prints as a 11-character null-terminated string with cout << ...
. Probably not what you're looking for.
The second form will implicitly convert the char*
to a string, and then keep the maximum between its length and the n
you specify. I think this is the simplest solution, in terms of what you have to write.
You can use the following. They all wrap the window
object into a jQuery object.
$(window).load(function () {
topInViewport($("#mydivname"))
});
$(window).resize(function () {
topInViewport($("#mydivname"))
});
$(window).scroll(function () {
topInViewport($("#mydivname"))
});
Or bind to them all using on
:
$(window).on("load resize scroll",function(e){
topInViewport($("#mydivname"))
});
One line
printf "\x$(printf %x 65)"
Two lines
set $(printf %x 65)
printf "\x$1"
Here is one if you do not mind using awk
awk 'BEGIN{printf "%c", 65}'
Bear in mind that it is only worth using anything other than a full table scan to find these values if the number of blocks that contain a row that matches the predicate is significantly smaller than the total number of blocks in the table. That is why Oracle will often decline the use of an index in order to full scan when you use LIKE '%x%' where x is a very small string. For example if the optimizer believes that using an index would still require single-block reads on (say) 20% of the table blocks then a full table scan is probably a better option than an index scan.
Sometimes you know that your predicate is much more selective than the optimizer can estimate. In such a case you can look into supplying an optimizer hint to perform an index fast full scan on the relevant column (particularly if the index is a much smaller segment than the table).
SELECT /*+ index_ffs(users (users.last_name)) */
*
FROM users
WHERE last_name LIKE "%z%"
Kindly check Column ApplicationId datatype in Table aspnet_Users , ApplicationId column datatype should be uniqueidentifier .
*Your parameter order is passed wrongly , Parameter @id should be passed as first argument, but in your script it is placed in second argument..*
So error is raised..
Please refere sample script:
DECLARE @id uniqueidentifier
SET @id = NEWID()
Create Table #temp1(AppId uniqueidentifier)
insert into #temp1 values(@id)
Select * from #temp1
Drop Table #temp1
The public java.util.List
subclasses of the JDK don't provide a fixed size feature that doesn't make part of the List
specification.
You could find it only in Queue
subclasses (for example ArrayBlockingQueue
, a bounded blocking queue backed by an array for example) that handle very specific requirements.
In Java, with a List
type, you could implement it according to two scenarios :
1) The fixed list size is always both the actual and the maximum size.
It sounds as an array definition. So Arrays.asList()
that returns a fixed-size list backed by the specified array is what you are looking for. And as with an array you can neither increase nor decrease its size but only changing its content. So adding and removing operation are not supported.
For example :
Foo[] foosInput= ...;
List<Foo> foos = Arrays.asList(foosInput);
foos.add(new Foo()); // throws an Exception
foos.remove(new Foo()); // throws an Exception
It works also with a collection as input while first we convert it into an array :
Collection<Foo> foosInput= ...;
List<Foo> foos = Arrays.asList(foosInput.toArray(Foo[]::new)); // Java 11 way
// Or
List<Foo> foos = Arrays.asList(foosInput.stream().toArray(Foo[]::new)); // Java 8 way
2) The list content is not known as soon as its creation. So you mean by fixed size list its maximum size.
You could use inheritance (extends ArrayList
) but you should favor composition over that since it allows you to not couple your class with the implementation details of this implementation and provides also flexibility about the implementation of the decorated/composed.
With Guava Forwarding classes you could do :
import com.google.common.collect.ForwardingList;
public class FixedSizeList<T> extends ForwardingList<T> {
private final List<T> delegate;
private final int maxSize;
public FixedSizeList(List<T> delegate, int maxSize) {
this.delegate = delegate;
this.maxSize = maxSize;
}
@Override protected List<T> delegate() {
return delegate;
}
@Override public boolean add(T element) {
assertMaxSizeNotReached(1);
return super.add(element);
}
@Override public void add(int index, T element) {
assertMaxSizeNotReached(1);
super.add(index, element);
}
@Override public boolean addAll(Collection<? extends T> collection) {
assertMaxSizeNotReached(collection.size());
return super.addAll(collection);
}
@Override public boolean addAll(int index, Collection<? extends T> elements) {
assertMaxSizeNotReached(elements.size());
return super.addAll(index, elements);
}
private void assertMaxSizeNotReached(int size) {
if (delegate.size() + size >= maxSize) {
throw new RuntimeException("size max reached");
}
}
}
And use it :
List<String> fixedSizeList = new FixedSizeList<>(new ArrayList<>(), 3);
fixedSizeList.addAll(Arrays.asList("1", "2", "3"));
fixedSizeList.add("4"); // throws an Exception
Note that with composition, you could use it with any List
implementation :
List<String> fixedSizeList = new FixedSizeList<>(new LinkedList<>(), 3);
//...
Which is not possible with inheritance.
LINUX
struct timeval tv;
tv.tv_sec = 30; // 30 Secs Timeout
tv.tv_usec = 0; // Not init'ing this can cause strange errors
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv,sizeof(struct timeval));
WINDOWS
DWORD timeout = SOCKET_READ_TIMEOUT_SEC * 1000;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout));
NOTE: You have put this setting before bind()
function call for proper run
You can index into a string in C# like an array, and you get the character at that index.
Example:
In Java, you would say
str.charAt(8);
In C#, you would say
str[8];
You can download language pack and use "Install or Uninstall display languages" wizard. To do this:
Win+R
, paste lpksetup
and press Enter
Install display languages
buttonBrowse
and pick the *.cab file of the MUI language you downloadedThe difference between a shared project and a class library is that the latter is compiled and the unit of reuse is the assembly.
Whereas with the former, the unit of reuse is the source code, and the shared code is incorporated into each assembly that references the shared project.
This can be useful when you want to create separate assemblies that target specific platforms but still have code that should be shared.
See also here:
The shared project reference shows up under the References node in the Solution Explorer, but the code and assets in the shared project are treated as if they were files linked into the main project.
In previous versions of Visual Studio1, you could share source code between projects by Add -> Existing Item and then choosing to Link. But this was kind of clunky and each separate source file had to be selected individually. With the move to supporting multiple disparate platforms (iOS, Android, etc), they decided to make it easier to share source between projects by adding the concept of Shared Projects.
1 This question and my answer (up until now) suggest that Shared Projects was a new feature in Visual Studio 2015. In fact, they made their debut in Visual Studio 2013 Update 2
You can pass PHP arrays to JavaScript using json_encode
PHP function.
<?php
$phpArray = array(
0 => "Mon",
1 => "Tue",
2 => "Wed",
3 => "Thu",
4 => "Fri",
5 => "Sat",
6 => "Sun",
)
?>
<script type="text/javascript">
var jArray = <?php echo json_encode($phpArray); ?>;
for(var i=0; i<jArray.length; i++){
alert(jArray[i]);
}
</script>
There is one more difference of using the app and listening to http server is when you want to setup for https server
To setup for https, you need the code below:
var https = require('https');
var server = https.createServer(app).listen(config.port, function() {
console.log('Https App started');
});
The app from express will return http server only, you cannot set it in express, so you will need to use the https server command
var express = require('express');
var app = express();
app.listen(1234);
You can configure the output directory using the CONFIGURATION_BUILD_DIR
environment variable.
if(isset($rule["type"]) && ($rule["type"] == "radio") || ($rule["type"] == "checkbox") )
{
if(!isset($data[$field]))
$data[$field]="";
}
You need to specify workseet. Change line
If Worksheet.Cells(i, 1).Value = "X" Then
to
If Worksheets("Sheet2").Cells(i, 1).Value = "X" Then
UPD:
Try to use following code (but it's not the best approach. As @SiddharthRout suggested, consider about using Autofilter):
Sub LastRowInOneColumn()
Dim LastRow As Long
Dim i As Long, j As Long
'Find the last used row in a Column: column A in this example
With Worksheets("Sheet2")
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
MsgBox (LastRow)
'first row number where you need to paste values in Sheet1'
With Worksheets("Sheet1")
j = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
End With
For i = 1 To LastRow
With Worksheets("Sheet2")
If .Cells(i, 1).Value = "X" Then
.Rows(i).Copy Destination:=Worksheets("Sheet1").Range("A" & j)
j = j + 1
End If
End With
Next i
End Sub
Doing that is very easy nowadays. Just add:
data-backdrop="static" data-keyboard="false"
In your modal divider.
You could use KEY
unique key (combination of the data) that changes with props, and that component will be rerendered with updated props.
When you do self.button = Button(...).grid(...)
, what gets assigned to self.button
is the result of the grid()
command, not a reference to the Button
object created.
You need to assign your self.button
variable before packing/griding it.
It should look something like this:
self.button = Button(self,text="Click Me",command=self.color_change,bg="blue")
self.button.grid(row = 2, column = 2, sticky = W)
A little bit late at party, but Java has a new Date Time API in JDK 8. You may want to upgrade your JDK version and embrace the standard. No more messy date/calendar, no more 3rd party jars.
Working during August 2020
use this
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
use one aspect ratio
<div class="embed-responsive embed-responsive-4by3">
<iframe class="embed-responsive-item" src="…"></iframe>
</div>
within iframe use options
<iframe class="embed-responsive-item" src="..."
frameborder="0"
style="
overflow: hidden;
overflow-x: hidden;
overflow-y: hidden;
height: 100%;
width: 100%;
position: absolute;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
"
height="100%"
width="100%"
></iframe>
It is not possible to display alerts from the controller. Because MVC views and controllers are entirely separated from each other. You can only display information in the view only. So it is required to pass the information to be displayed from controller to view by using either ViewBag
, ViewData
or TempData
. If you are trying to display the content stored in TempData["Message"]
, It is possible to perform in the view page by adding few javascript lines.
<script>
alert(@TempData["Message"]);
</script>
Wanted to add an example to funky-future's answer as I kept getting this error:
Uncaught TypeError: element.childNodes is not iterable
use like this:
replaceInText(document.body,"search term","replacement");
it didn't work for me with jQuery selectors.
find($id)
takes an id and returns a single model. If no matching model exist, it returns null
.
findOrFail($id)
takes an id and returns a single model. If no matching model exist, it throws an error1.
first()
returns the first record found in the database. If no matching model exist, it returns null
.
firstOrFail()
returns the first record found in the database. If no matching model exist, it throws an error1.
get()
returns a collection of models matching the query.
pluck($column)
returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists
.
toArray()
converts the model/collection into a simple PHP array.
Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.
Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach
loop is ok, put passing it to array_map
is not. Similarly, if you type-hint an argument as array
, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable
typehint, which can be used to accept both arrays and collections.
If you ever want to get a plain array from a collection, call its all()
method.
1 The error thrown by the findOrFail
and firstOrFail
methods is a ModelNotFoundException
. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.
Optionally, move all your constants to .cpp file without declaration in .h file. Use anonymous namespace to make them invisible beyond the cpp module.
// MyClass.cpp
#include "MyClass.h"
// anonymous namespace
namespace
{
string RE_ANY = "([^\\n]*)";
string RE_ANY_RELUCTANT = "([^\\n]*?)";
}
// member function (static or not)
bool MyClass::foo()
{
// logic that uses constants
return RE_ANY_RELUCTANT.size() > 0;
}
How about this solution for node.js https://github.com/mattbornski/tzwhere
And its Python counterpart: https://github.com/pegler/pytzwhere
Take a look at my answer Maven and dependent modules.
The Maven Reactor plugin is designed to deal with building part of a project.
The particular goal you'll want to use it reactor:make
.
In Java 9, you can use List.of
static factory method in order to create a List
literal. Something like the following:
List<Element> elements = List.of(new Element(1), new Element(2), new Element(3));
This would return an immutable list containing three elements. If you want a mutable list, pass that list to the ArrayList
constructor:
new ArrayList<>(List.of(// elements vararg))
JEP 269 provides some convenience factory methods for Java Collections API. These immutable static factory methods are built into the List
, Set
, and Map
interfaces in Java 9 and later.
Make sure that the "Distributed Transaction Coordinator" Service is running on both database and client. Also make sure you check "Network DTC Access", "Allow Remote Client", "Allow Inbound/Outbound" and "Enable TIP".
To enable Network DTC Access for MS DTC transactions
Open the Component Services snap-in.
To open Component Services, click Start. In the search box, type dcomcnfg, and then press ENTER.
Expand the console tree to locate the DTC (for example, Local DTC) for which you want to enable Network MS DTC Access.
On the Action menu, click Properties.
Click the Security tab and make the following changes: In Security Settings, select the Network DTC Access check box.
In Transaction Manager Communication, select the Allow Inbound and Allow Outbound check boxes.
To trigger an enter keypress, I had to modify @ebynum response, specifically, using the keyCode property.
e = $.Event('keyup');
e.keyCode= 13; // enter
$('input').trigger(e);
Here's an example where I change the background image from one to another with a 2 second alpha fade delay both ways - 2s fadeout of the original image into a 2s fadein into the 2nd image.
public void fadeImageFunction(View view) {
backgroundImage = (ImageView) findViewById(R.id.imageViewBackground);
backgroundImage.animate().alpha(0f).setDuration(2000);
// A new thread with a 2-second delay before changing the background image
new Timer().schedule(
new TimerTask(){
@Override
public void run(){
// you cannot touch the UI from another thread. This thread now calls a function on the main thread
changeBackgroundImage();
}
}, 2000);
}
// this function runs on the main ui thread
private void changeBackgroundImage(){
runOnUiThread(new Runnable() {
@Override
public void run() {
backgroundImage = (ImageView) findViewById(R.id.imageViewBackground);
backgroundImage.setImageResource(R.drawable.supes);
backgroundImage.animate().alpha(1f).setDuration(2000);
}
});
}
Assuming that those are Strings, use the convenient static method sort
…
java.util.Collections.sort(listOfCountryNames)
Have you tried using basicHttpBinding instead of wsHttpBinding? If do not need any authentication and the Ws-* implementations are not required, you'd probably be better off with plain old basicHttpBinding. WsHttpBinding implements WS-Security for message security and authentication.
If you are facing any issues during push ( in windows OS), just remove the cached git account by following the given steps below: 1. Search for Control panel and open the same. 2. Search for Credential Manager and open this. 3. Click on Windows Credentials under Manage your credentials page. 4. Under Generic Credentials click on GitHub. 5. Click on Remove and then confirm by clicking Yes button. 6. Now start pushing the code and you will get GitHub popup to login again and now you are done. Everything will work properly after successful login.
This same issue occurred for me and stack trace
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/XXXXSearch]]
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:192)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/XXXXSearch]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
... 6 more
Caused by: java.lang.IllegalStateException: Unable to complete the scan for annotations for web application [/XXXXSearch]. Possible root causes include a too low setting for -Xss and illegal cyclic inheritance dependencies
at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2109)
at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:1981)
at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1947)
at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1932)
at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1326)
at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:878)
at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:369)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5179)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 6 more
Caused by: java.lang.StackOverflowError
at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269
at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
In my analysis what i found was, this issue is occurred when illegal cyclic inheritance dependencies caused for Tomcat startup annotation processing.
But my project had lot of dependency JARs, and couldn't found which one is responsible for this.
After trying so many unhappy approaches What i did was , I have updated my tomcat plugin to following and ran the same scenario,
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat8-maven-plugin</artifactId>
<version>3.0-r1756463</version>
<\plugin>
Then i was able to find which JAR is caused to this issue ,
Aug 23, 2017 2:32:12 PM org.apache.catalina.startup.ContextConfig processAnnotationsJar
SEVERE: Unable to process Jar entry [cryptix/test/TestLOKI91.class] from Jar [jar:file:/C:/Users/Tharinda/.m2/repository/cryptix/cryptix/1.2.2/cryptix-1.2.2.jar!/] for annotations
java.io.EOFException
at org.apache.tomcat.util.bcel.classfile.FastDataInputStream.readUnsignedShort(FastDataInputStream.java:120)
at org.apache.tomcat.util.bcel.classfile.ClassParser.readAttributes(ClassParser.java:110)
at org.apache.tomcat.util.bcel.classfile.ClassParser.parse(ClassParser.java:94)
at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:1994)
at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:1944)
at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1919)
at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1880)
at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1149)
at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:771)
at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:305)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5120)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Then just solving the issue with cryptix-1.2.2.jar solved this problem.
I strongly recommend to move tomcat8-maven-plugin which seems stable and less buggy at the moment.
It's possible to get this done using seaborn.lineplot()
but it involves some additional work of converting numpy arrays to pandas dataframe. Here's a complete example:
# imports
import seaborn as sns
import numpy as np
import pandas as pd
# inputs
In [41]: num = np.array([1, 2, 3, 4, 5])
In [42]: sqr = np.array([1, 4, 9, 16, 25])
# convert to pandas dataframe
In [43]: d = {'num': num, 'sqr': sqr}
In [44]: pdnumsqr = pd.DataFrame(d)
# plot using lineplot
In [45]: sns.set(style='darkgrid')
In [46]: sns.lineplot(x='num', y='sqr', data=pdnumsqr)
Out[46]: <matplotlib.axes._subplots.AxesSubplot at 0x7f583c05d0b8>
And we get the following plot:
Frankly speaking, your case works fine for me!
I'm using Angular 5.
<script type='text/javascript'>
var base = window.location.href.substring(0, window.location.href.toLowerCase().indexOf('index.aspx'))
document.write('<base href="' + base + '" />');
</script>
TypeScript is a strict syntactical superset of JavaScript hence
Enum names live under the same rules as normal variable names, i.e. no spaces or dots in the middle of the names... I still consider the first one to be rather friendly though...
opacity
will make both text and background transparent. Use a semi-transparent background-color instead, by using a rgba()
value for example. Works on IE8+
This is sort of covered by the various responses above, but the first time I read this article I missed an important fact, which led to a minor bug in my code...
Session.Clear()
will CLEAR the values of all the keys but will NOT cause the session end event to fire.
Session.Abandon()
will NOT clear the values on the current request. IF another page is requested, the values will be gone for that one. However, abandon WILL throw the event.
So, in my case (and perhaps in yours?), I needed Clear()
followed by Abandon()
.
@denver_citizen and @Peter Szanto's answers didn't quite work for me, but I modified them to account for:
DECLARE @Debug bit = 0;
-- List of tables to truncate
select
SchemaName, Name
into #tables
from (values
('schema', 'table')
,('schema2', 'table2')
) as X(SchemaName, Name)
BEGIN TRANSACTION TruncateTrans;
with foreignKeys AS (
SELECT
SCHEMA_NAME(fk.schema_id) as SchemaName
,fk.Name as ConstraintName
,OBJECT_NAME(fk.parent_object_id) as TableName
,SCHEMA_NAME(t.SCHEMA_ID) as ReferencedSchemaName
,OBJECT_NAME(fk.referenced_object_id) as ReferencedTableName
,fc.constraint_column_id
,COL_NAME(fk.parent_object_id, fc.parent_column_id) AS ColumnName
,COL_NAME(fk.referenced_object_id, fc.referenced_column_id) as ReferencedColumnName
,fk.delete_referential_action_desc
,fk.update_referential_action_desc
FROM sys.foreign_keys AS fk
JOIN sys.foreign_key_columns AS fc
ON fk.object_id = fc.constraint_object_id
JOIN #tables tbl
ON OBJECT_NAME(fc.referenced_object_id) = tbl.Name
JOIN sys.tables t on OBJECT_NAME(t.object_id) = tbl.Name
and SCHEMA_NAME(t.schema_id) = tbl.SchemaName
and t.OBJECT_ID = fc.referenced_object_id
)
select
quotename(fk.ConstraintName) AS ConstraintName
,quotename(fk.SchemaName) + '.' + quotename(fk.TableName) AS TableName
,quotename(fk.ReferencedSchemaName) + '.' + quotename(fk.ReferencedTableName) AS ReferencedTableName
,replace(fk.delete_referential_action_desc, '_', ' ') AS DeleteAction
,replace(fk.update_referential_action_desc, '_', ' ') AS UpdateAction
,STUFF((
SELECT ',' + quotename(fk2.ColumnName)
FROM foreignKeys fk2
WHERE fk2.ConstraintName = fk.ConstraintName and fk2.SchemaName = fk.SchemaName
ORDER BY fk2.constraint_column_id
FOR XML PATH('')
),1,1,'') AS ColumnNames
,STUFF((
SELECT ',' + quotename(fk2.ReferencedColumnName)
FROM foreignKeys fk2
WHERE fk2.ConstraintName = fk.ConstraintName and fk2.SchemaName = fk.SchemaName
ORDER BY fk2.constraint_column_id
FOR XML PATH('')
),1,1,'') AS ReferencedColumnNames
into #FKs
from foreignKeys fk
GROUP BY fk.SchemaName, fk.ConstraintName, fk.TableName, fk.ReferencedSchemaName, fk.ReferencedTableName, fk.delete_referential_action_desc, fk.update_referential_action_desc
-- Drop FKs
select
identity(int,1,1) as ID,
'ALTER TABLE ' + fk.TableName + ' DROP CONSTRAINT ' + fk.ConstraintName AS script
into #scripts
from #FKs fk
-- Truncate
insert into #scripts
select distinct
'TRUNCATE TABLE ' + quotename(tbl.SchemaName) + '.' + quotename(tbl.Name) AS script
from #tables tbl
-- Recreate
insert into #scripts
select
'ALTER TABLE ' + fk.TableName +
' WITH CHECK ADD CONSTRAINT ' + fk.ConstraintName +
' FOREIGN KEY ('+ fk.ColumnNames +')' +
' REFERENCES ' + fk.ReferencedTableName +' ('+ fk.ReferencedColumnNames +')' +
' ON DELETE ' + fk.DeleteAction COLLATE Latin1_General_CI_AS_KS_WS + ' ON UPDATE ' + fk.UpdateAction COLLATE Latin1_General_CI_AS_KS_WS AS script
from #FKs fk
DECLARE @script nvarchar(MAX);
DECLARE curScripts CURSOR FOR
select script
from #scripts
order by ID
OPEN curScripts
WHILE 1=1 BEGIN
FETCH NEXT FROM curScripts INTO @script
IF @@FETCH_STATUS != 0 BREAK;
print @script;
IF @Debug = 0
EXEC (@script);
END
CLOSE curScripts
DEALLOCATE curScripts
drop table #scripts
drop table #FKs
drop table #tables
COMMIT TRANSACTION TruncateTrans;
add your service to providers[] array in app.module.ts file. Like below
// here my service is CarService
app.module.ts
import {CarsService} from './cars.service';
providers: [CarsService] // you can include as many services you have
You should be using the strict not equals
comparison operator !==
so that if the user inputs "null"
then you won't get to the else
.
no need to do a replacement. the regex will give you what u wanted directly:
"(?<=_)[^_]*\.jpg"
tested with grep:
echo "3.04_somename.jpg"|grep -oP "(?<=_)[^_]*\.jpg"
somename.jpg
No, you cannot do that. I invite you to read a POST definition.
Or this page: HTTP, request methods
update tb set f1=1 where id in (select top 100 id from tb where f1=0)
Return an Array Of Objects
private static Object[] f ()
{
double x =1.0;
int y= 2 ;
return new Object[]{Double.valueOf(x),Integer.valueOf(y)};
}
package com.example.sandeep.googlemapsample;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
GoogleMap.OnMarkerDragListener,
GoogleMap.OnMapLongClickListener,
GoogleMap.OnMarkerClickListener,
View.OnClickListener {
private static final String TAG = "MapsActivity";
private GoogleMap mMap;
private double longitude;
private double latitude;
private GoogleApiClient googleApiClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//Initializing googleApiClient
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// googleMapOptions.mapType(googleMap.MAP_TYPE_HYBRID)
// .compassEnabled(true);
// Add a marker in Sydney and move the camera
LatLng india = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(india).title("Marker in India"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(india));
mMap.setOnMarkerDragListener(this);
mMap.setOnMapLongClickListener(this);
}
//Getting current location
private void getCurrentLocation() {
mMap.clear();
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (location != null) {
//Getting longitude and latitude
longitude = location.getLongitude();
latitude = location.getLatitude();
//moving the map to location
moveMap();
}
}
private void moveMap() {
/**
* Creating the latlng object to store lat, long coordinates
* adding marker to map
* move the camera with animation
*/
LatLng latLng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions()
.position(latLng)
.draggable(true)
.title("Marker in India"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
mMap.getUiSettings().setZoomControlsEnabled(true);
}
@Override
public void onClick(View view) {
Log.v(TAG,"view click event");
}
@Override
public void onConnected(@Nullable Bundle bundle) {
getCurrentLocation();
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onMapLongClick(LatLng latLng) {
// mMap.clear();
mMap.addMarker(new MarkerOptions().position(latLng).draggable(true));
}
@Override
public void onMarkerDragStart(Marker marker) {
Toast.makeText(MapsActivity.this, "onMarkerDragStart", Toast.LENGTH_SHORT).show();
}
@Override
public void onMarkerDrag(Marker marker) {
Toast.makeText(MapsActivity.this, "onMarkerDrag", Toast.LENGTH_SHORT).show();
}
@Override
public void onMarkerDragEnd(Marker marker) {
// getting the Co-ordinates
latitude = marker.getPosition().latitude;
longitude = marker.getPosition().longitude;
//move to current position
moveMap();
}
@Override
protected void onStart() {
googleApiClient.connect();
super.onStart();
}
@Override
protected void onStop() {
googleApiClient.disconnect();
super.onStop();
}
@Override
public boolean onMarkerClick(Marker marker) {
Toast.makeText(MapsActivity.this, "onMarkerClick", Toast.LENGTH_SHORT).show();
return true;
}
}
Model:
namespace MvcApplicationrazor.Models
{
public class CountryModel
{
public List<State> StateModel { get; set; }
public SelectList FilteredCity { get; set; }
}
public class State
{
public int Id { get; set; }
public string StateName { get; set; }
}
public class City
{
public int Id { get; set; }
public int StateId { get; set; }
public string CityName { get; set; }
}
}
Controller:
public ActionResult Index()
{
CountryModel objcountrymodel = new CountryModel();
objcountrymodel.StateModel = new List<State>();
objcountrymodel.StateModel = GetAllState();
return View(objcountrymodel);
}
//Action result for ajax call
[HttpPost]
public ActionResult GetCityByStateId(int stateid)
{
List<City> objcity = new List<City>();
objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
return Json(obgcity);
}
// Collection for state
public List<State> GetAllState()
{
List<State> objstate = new List<State>();
objstate.Add(new State { Id = 0, StateName = "Select State" });
objstate.Add(new State { Id = 1, StateName = "State 1" });
objstate.Add(new State { Id = 2, StateName = "State 2" });
objstate.Add(new State { Id = 3, StateName = "State 3" });
objstate.Add(new State { Id = 4, StateName = "State 4" });
return objstate;
}
//collection for city
public List<City> GetAllCity()
{
List<City> objcity = new List<City>();
objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
return objcity;
}
View:
@model MvcApplicationrazor.Models.CountryModel
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
function GetCity(_stateId) {
var procemessage = "<option value='0'> Please wait...</option>";
$("#ddlcity").html(procemessage).show();
var url = "/Test/GetCityByStateId/";
$.ajax({
url: url,
data: { stateid: _stateId },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#ddlcity").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
</script>
<h4>
MVC Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm())
{
@Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
<br />
<br />
<select id="ddlcity" name="ddlcity" style="width: 200px">
</select>
<br /><br />
}
Using the Package Manager, you need to re-install Entity Framework:
Uninstall-Package EntityFramework -Force
Then install it for each project:
Install-Package EntityFramework
Then do not forget to restart the studio.
System.Threading.Timer
is a plain timer. It calls you back on a thread pool thread (from the worker pool).
System.Timers.Timer
is a System.ComponentModel.Component
that wraps a System.Threading.Timer
, and provides some additional features used for dispatching on a particular thread.
System.Windows.Forms.Timer
instead wraps a native message-only-HWND and uses Window Timers to raise events in that HWNDs message loop.
If your app has no UI, and you want the most light-weight and general-purpose .Net timer possible, (because you are happy figuring out your own threading/dispatching) then System.Threading.Timer
is as good as it gets in the framework.
I'm not fully clear what the supposed 'not thread safe' issues with System.Threading.Timer
are. Perhaps it is just same as asked in this question: Thread-safety of System.Timers.Timer vs System.Threading.Timer, or perhaps everyone just means that:
it's easy to write race conditions when you're using timers. E.g. see this question: Timer (System.Threading) thread safety
re-entrancy of timer notifications, where your timer event can trigger and call you back a second time before you finish processing the first event. E.g. see this question: Thread-safe execution using System.Threading.Timer and Monitor
Although this is an old document, but it helped me resolve the problem of 'HintPath' being ignored on another machine. It was because the referenced DLL needed to be in source control as well:
Excerpt:
To include and then reference an outer-system assembly 1. In Solution Explorer, right-click the project that needs to reference the assembly,,and then click Add Existing Item. 2. Browse to the assembly, and then click OK. The assembly is then copied into the project folder and automatically added to VSS (assuming the project is already under source control). 3. Use the Browse button in the Add Reference dialog box to set a file reference to assembly in the project folder.
This has been answered before (although this question was first!):
"You should use java.net.URI to do this, as the URLDecoder class does x-www-form-urlencoded decoding which is wrong (despite the name, it's for form data)."
As URL class documentation states:
The recommended way to manage the encoding and decoding of URLs is to use URI, and to convert between these two classes using toURI() and URI.toURL().
The URLEncoder and URLDecoder classes can also be used, but only for HTML form encoding, which is not the same as the encoding scheme defined in RFC2396.
Basically:
String url = "https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type";
System.out.println(new java.net.URI(url).getPath());
will give you:
https://mywebsite/docs/english/site/mybook.do?request_type
This is the same as thefreeman but more in pythonic way using list and dictionary comprehension
columns = cursor.description
result = [{columns[index][0]:column for index, column in enumerate(value)} for value in cursor.fetchall()]
pprint.pprint(result)
$rootScope.$broadcast is a convenient way to raise a "global" event which all child scopes can listen for. You only need to use $rootScope
to broadcast the message, since all the descendant scopes can listen for it.
The root scope broadcasts the event:
$rootScope.$broadcast("myEvent");
Any child Scope can listen for the event:
$scope.$on("myEvent",function () {console.log('my event occurred');} );
Why we use $rootScope.$broadcast? You can use $watch
to listen for variable changes and execute functions when the variable state changes. However, in some cases, you simply want to raise an event that other parts of the application can listen for, regardless of any change in scope variable state. This is when $broadcast
is helpful.
You simply combine the ideas of a link to another page, as with href=foo.html
, and a link to an element on the same page, as with href=#bar
, so that the fragment like #bar
is written immediately after the URL that refers to another page:
<a href="foo.html#bar">Some nice link text</a>
The target is specified the same was as when linking inside one page, e.g.
<div id="bar">
<h2>Some heading</h2>
Some content
</div>
or (if you really want to link specifically to a heading only)
<h2 id="bar">Some heading</h2>
Just put a '!' in front of the boolean expression
My guess is a wrong version of project A jar in your local maven repository. It seems that the dependency is resolved otherwise I think maven does not start compiling but usually these compiling error means that you have a version mix up. try to make a maven clean install
of your project A and see if it changes something for the project B...
Also a little more information on your setting could be useful:
in angular-2 attribute syntax is
<div [attr.role]="myAriaRole">
Binds attribute role to the result of expression myAriaRole.
so can use like
[attr.role]="myAriaRole ? true: null"
As @PaulTheCyclist says, If using IISExpress anonymous authentication is enabled by default, windows authentication is disabled.
This can be changed in what I'm sure used to be called PropertyPages (NOT right-click -> properties). Select the web project
This is a bit high-level answer for applications which want to seamlessly fit into the Windows environment. Technical details of playing particular sound were provided in other answers. Besides that, always note these two points:
Use five standard system sounds in typical scenarios, i.e.
Asterisk - play when you want to highlight current event
Question - play with questions (system message box window plays this one)
Exclamation - play with excalamation icon (system message box window plays this one)
Beep (default system sound)
Critical stop ("Hand") - play with error (system message box window plays this one)
Methods of class System.Media.SystemSounds
will play them for you.
Implement any other sounds as customizable by your users in Sound control panel
pip3 install --user markdown
python3 -m markdown readme.md > readme.html
It doesn't handle GitHub extensions, but it is better than nothing. I believe you can extend the module to handle the GitHub additions.
I suggest you to read the Enumeration: Traversing a Collection’s Elements part of the Collections Programming Guide for Cocoa. There is a sample code for your need.
I have written this article about the ICommand interface.
The idea - creating a universal command that takes two delegates: one is called when ICommand.Execute (object param)
is invoked, the second checks the status of whether you can execute the command (ICommand.CanExecute (object param))
.
Requires the method to switching event CanExecuteChanged
. It is called from the user interface elements for switching the state CanExecute()
command.
public class ModelCommand : ICommand
{
#region Constructors
public ModelCommand(Action<object> execute)
: this(execute, null) { }
public ModelCommand(Action<object> execute, Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
#endregion
#region ICommand Members
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return _canExecute != null ? _canExecute(parameter) : true;
}
public void Execute(object parameter)
{
if (_execute != null)
_execute(parameter);
}
public void OnCanExecuteChanged()
{
CanExecuteChanged(this, EventArgs.Empty);
}
#endregion
private readonly Action<object> _execute = null;
private readonly Predicate<object> _canExecute = null;
}
You can do it this with two replace's
//let stw be "John Smith $100,000.00 M"
sb_trim = Regex.Replace(stw, @"\s+\$|\s+(?=\w+$)", ",");
//sb_trim becomes "John Smith,100,000.00,M"
sb_trim = Regex.Replace(sb_trim, @"(?<=\d),(?=\d)|[.]0+(?=,)", "");
//sb_trim becomes "John Smith,100000,M"
sw.WriteLine(sb_trim);
Looping through all the files in the folder is relatively easy:
files = dir('*.csv');
for file = files'
csv = load(file.name);
% Do some stuff
end
Something like this?
<a href="#" onClick="MyWindow=window.open('http://www.google.com','MyWindow','width=600,height=300'); return false;">Click Here</a>
awk
solution that deals with stdin
Since column
is not POSIX, maybe this is:
mycolumn() (
file="${1:--}"
if [ "$file" = - ]; then
file="$(mktemp)"
cat > "${file}"
fi
awk '
FNR == 1 { if (NR == FNR) next }
NR == FNR {
for (i = 1; i <= NF; i++) {
l = length($i)
if (w[i] < l)
w[i] = l
}
next
}
{
for (i = 1; i <= NF; i++)
printf "%*s", w[i] + (i > 1 ? 1 : 0), $i
print ""
}
' "$file" "$file"
if [ "$1" = - ]; then
rm "$file"
fi
)
Test:
printf '12 1234 1
12345678 1 123
1234 123456 123456
' > file
Test commands:
mycolumn file
mycolumn <file
mycolumn - <file
Output for all:
12 1234 1
12345678 1 123
1234 123456 123456
See also:
To print the columns with a specific string, you use the // search pattern. For example, if you are looking for second columns that contains abc:
awk '$2 ~ /abc/'
... and if you want to print only a particular column:
awk '$2 ~ /abc/ { print $3 }'
... and for a particular line number:
awk '$2 ~ /abc/ && FNR == 5 { print $3 }'
This below query worked for me. This can able to show the databases,tables,column names,data types and columns count.
**select table_schema Schema_Name ,table_name TableName,column_name ColumnName,ordinal_position "Position",column_type DataType,COUNT(1) ColumnCount
FROM information_schema.columns
GROUP by table_schema,table_name,column_name,ordinal_position, column_type;**
If you want to do multiple $ne
then do
db.users.find({name : {$nin : ["mary", "dick", "jane"]}})
ECLIPSE PHOTON ON MAC
Get your current JAVA_HOME path /Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home
open /Users/you/eclipse/jee-photon/Eclipse.app/Contents/Eclipse/ and click on package content. Then open eclipse.ini file using any text file editor.
Edit your -VM argument as below( Make sure the Java Path is same as $JAVA_HOME)
-vm
/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/jre/bin
I came here because of the error message, turns out I had two tables with the same name.
Simply Used this: MessageBox.Show(cmd4.CommandText.ToString()); in c#.net and this will show you main query , Copy it and run in database .
Your code works also for me. However, another workaround can be to get the plot's axis and then change only the y-values:
x1,x2,y1,y2 = plt.axis()
plt.axis((x1,x2,25,250))
Use these sizes 57x57, 72x72, 114x114, 144x144 then do this in the head of your document:
<link rel="apple-touch-icon" href="apple-touch-icon-iphone.png" />
<link rel="apple-touch-icon" sizes="72x72" href="apple-touch-icon-ipad.png" />
<link rel="apple-touch-icon" sizes="114x114" href="apple-touch-icon-iphone4.png" />
This will look good on all apple devices. ;)
you can combine asList and split
Arrays.asList(CommaSeparated.split("\\s*,\\s*"))
An absolute xpath in HTML DOM starts with /html e.g.
/html/body/div[5]/div[2]/div/div[2]/div[2]/h2[1]
and a relative xpath finds the closed id to the dom element and generates xpath starting from that element e.g.
.//*[@id='answers']/h2[1]/a[1]
You can use firepath (firebug) for generating both types of xpaths
It won't make any difference which xpath you use in selenium, the former may be faster than the later one (but it won't be observable)
Absolute xpaths are prone to more regression as slight change in DOM makes them invalid or refer to a wrong element
I came across this problem and my senior told me about a solution i.e:
Right click on your projectname.xcodeproj
file here projectname
will be the name of your project. Now after right clicked select Show Packages Contents. After that open your projectname.pbxproj
file in a text editor. Now search for the line containing <<<<<<< .mine
, =======
and >>>>>>> .r
. For example in my case it looked liked this
<<<<<<< .mine
9ADAAC6A15DCEF6A0019ACA8 .... in Resources */,
=======
52FD7F3D15DCEAEF009E9322 ... in Resources */,
>>>>>>> .r269
Now remove those <<<<<<< .mine
, =======
and >>>>>>> .r
lines so it would look like this
9ADAAC6A15DCEF6A0019ACA8 /* BuyPriceBtn.png in Resources */,
52FD7F3D15DCEAEF009E9322 /* discussionForm.zip in Resources */,
Now save and open your Xcode project and build it. Everything will be fine.
SHOW VARIABLES LIKE 'validate_password%';
mysql> SET GLOBAL validate_password.length = 6;
mysql> SET GLOBAL validate_password.number_count = 0;
mysql> SET GLOBAL validate_password.policy=LOW;
SHOW VARIABLES LIKE 'validate_password%';
Try converting the entry to a string first. As long as the database column type is a date it will be formated as a date.
self.date || self.exif_date_time_original.to_s
I realise that this article may be outdated but still I would like to ask smithsv to correct his source code, it contains many mistakes, I managed to correct most of them but still don't know what kind of object x509 could be.Here is the source code as I think is should be:
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.util.Enumeration;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
public class Connection2 {
public void connect() {
/*
* This is an example to use ONLY p12 file it's not optimazed but it
* work. The pkcs12 file where generated by OpenSSL by me. Example how
* to load p12 file and build Trust zone from it... It outputs
* certificates from p12 file and add good certs to TrustStore
*/
KeyStore ks = KeyStore.getInstance( "pkcs12" );
ks.load( new FileInputStream( cert.pfx ), "passwrd".toCharArray() );
KeyStore jks = KeyStore.getInstance( "JKS" );
jks.load( null );
for( Enumeration t = ks.aliases(); t.hasMoreElements(); ) {
String alias = (String )t.nextElement();
System.out.println( "@:" + alias );
if( ks.isKeyEntry( alias ) ) {
Certificate[] a = ks.getCertificateChain( alias );
for( int i = 0; i == 0; )
jks.setCertificateEntry( x509Cert.getSubjectDN().toString(), x509 );
System.out.println( ks.getCertificateAlias( x509 ) );
System.out.println( "ok" );
}
}
System.out.println( "init Stores..." );
KeyManagerFactory kmf = KeyManagerFactory.getInstance( "SunX509" );
kmf.init( ks, "c1".toCharArray() );
TrustManagerFactory tmf = TrustManagerFactory.getInstance( "SunX509" );
tmf.init( jks );
SSLContext ctx = SSLContext.getInstance( "TLS" );
ctx.init( kmf.getKeyManagers(), tmf.getTrustManagers(), null );
}
}
list1=['x','y','z','a','b','c','d','e','f','g']
find=raw_input("Enter string to be found")
l=list1.index(find)
list1a=[:l]
list1b=[l:]
Properties are one way to create constants. You can do it by declaring a getter property, but ignoring the setter. For example:
class MyFinalProperty(object):
@property
def name(self):
return "John"
You can have a look at an article I've written to find more ways to use Python properties.
You can convert them to Set
collections, and perform a set difference operation on them.
Like this:
Set<Date> ad = new HashSet<Date>(a);
Set<Date> bd = new HashSet<Date>(b);
ad.removeAll(bd);
GET CURRENT UTC TIME IN REQUIRED FORMAT
// Current UTC time
OffsetDateTime utc = OffsetDateTime.now(ZoneOffset.UTC);
// GET LocalDateTime
LocalDateTime localDateTime = utc.toLocalDateTime();
System.out.println("*************" + localDateTime);
// formated UTC time
DateTimeFormatter dTF = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
System.out.println(" formats as " + dTF.format(localDateTime));
//GET UTC time for current date
Date now= new Date();
LocalDateTime utcDateTimeForCurrentDateTime = Instant.ofEpochMilli(now.getTime()).atZone(ZoneId.of("UTC")).toLocalDateTime();
DateTimeFormatter dTF2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
System.out.println(" formats as " + dTF2.format(utcDateTimeForCurrentDateTime));
The delete
operator allows you to remove a property from an object.
The following examples all do the same thing.
// Example 1
var key = "Cow";
delete thisIsObject[key];
// Example 2
delete thisIsObject["Cow"];
// Example 3
delete thisIsObject.Cow;
If you're interested, read Understanding Delete for an in-depth explanation.
Similar to what has been suggested, you can do:
print(i, end=',')
Output: 0,1,2,3,
I Had the same problem, in my case, was because i was returned a digit:
def __str__(self):
return self.code
str is waiting for a str, not another.
now work good with:
def __str__(self):
return self.name
where name is a STRING.
In your xml file add something like this with width and height as 'match_parent'.
<RelativeLayout
android:id="@+id/bac_dim_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#C0000000"
android:visibility="gone" >
</RelativeLayout>
In your activity oncreate
//setting background dim when showing popup
back_dim_layout = (RelativeLayout) findViewById(R.id.share_bac_dim_layout);
Finally make visible when you show your popupwindow and make its visible gone when you exit popupwindow.
back_dim_layout.setVisibility(View.VISIBLE);
back_dim_layout.setVisibility(View.GONE);
It depends on what database you are using. In MySQL, you would use the "ALTER TABLE" syntax. I don't remember exactly how, but it would go something like this if you wanted to add a column called 'newcol' that was a 200 character varchar:
ALTER TABLE example ADD newCol VARCHAR(200) AFTER otherCol;
You can sum up the values of a BigDecimal
stream using a reusable Collector named summingUp
:
BigDecimal sum = bigDecimalStream.collect(summingUp());
The Collector
can be implemented like this:
public static Collector<BigDecimal, ?, BigDecimal> summingUp() {
return Collectors.reducing(BigDecimal.ZERO, BigDecimal::add);
}
No.. It is not proper way. Refer the steps,
For Classpath reference:
Right click on project in Eclipse -> Buildpath -> Configure Build path -> Java Build Path (left Pane) -> Libraries(Tab) -> Add External Jars -> Select your jar and select OK.
For Deployment Assembly:
Right click on WAR in eclipse-> Buildpath -> Configure Build path -> Deployment Assembly (left Pane) -> Add -> External file system -> Add -> Select your jar -> Add -> Finish.
This is the proper way! Don't forget to remove environment variable. It is not required now.
Try this. Surely it will work. Try to use Maven, it will simplify you task.
I spent quite a bit of time also looking to launch a simple Python program at 01:00. For some reason, I couldn't get cron to launch it and APScheduler seemed rather complex for something that should be simple. Schedule (https://pypi.python.org/pypi/schedule) seemed about right.
You will have to install their Python library:
pip install schedule
This is modified from their sample program:
import schedule
import time
def job(t):
print "I'm working...", t
return
schedule.every().day.at("01:00").do(job,'It is 01:00')
while True:
schedule.run_pending()
time.sleep(60) # wait one minute
You will need to put your own function in place of job and run it with nohup, e.g.:
nohup python2.7 MyScheduledProgram.py &
Don't forget to start it again if you reboot.
if you want to print the value of a size_t as a string you can do this:
char text[] = "Lets go fishing in stead of sitting on our but !!";
size_t line = 2337200120702199116;
/* on windows I64x or I64d others %lld or %llx if it works %zd or %zx */
printf("number: %I64d\n",*(size_t*)&text);
printf("text: %s\n",*(char(*)[])&line);
result is:
number: 2337200120702199116
text: Lets go fishing in stead of sitting on our but !!
Edit: rereading the question because of the down votes i noted his problem is not %llu or %I64d but the size_t type on different machines see this question https://stackoverflow.com/a/918909/1755797
http://www.cplusplus.com/reference/cstdio/printf/
size_t is unsigned int on a 32bit machine and unsigned long long int on 64bit
but %ll always expects a unsigned long long int.
size_t varies in length on different operating systems while %llu is the same
For the original issue, I would request you to apply below logic:
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPostRequest = new HttpPost();
Quoted from http://maven.apache.org/settings.html:
There are two locations where a settings.xml file may live:
The Maven install: $M2_HOME/conf/settings.xml
A user's install: ${user.home}/.m2/settings.xml
So, usually for a specific user you edit
/home/*username*/.m2/settings.xml
To set environment for all local users, you might think about changing the first path.
The solution to the problem for me was found in the XML document for my Main Activity. Originally my toolbar was <android.support.v7.widget.Toolbar
. To resolve this I changed it to <android.widget.Toolbar
.
I do not know why this worked though. Does anyone have any insight as to why?
You can do it by yourself - it's now so difficult. Here is an example from my project: https://github.com/AlShevelev/WizardCamera
Let start from settings (attrs.xml).
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ExpositionBar">
<attr name="button_icon" format="reference" />
<attr name="button_icon_size" format="dimension" />
<attr name="stroke_width" format="dimension" />
<attr name="stroke_color" format="color" />
<attr name="button_color" format="color" />
<attr name="button_color_pressed" format="color" />
<attr name="min_value" format="float" />
<attr name="max_value" format="float" />
</declare-styleable>
</resources>
Here is a couple of utility functions:
fun <T: Comparable<T>>T.fitInRange(range: Range<T>): T =
when {
this < range.lower -> range.lower
this > range.upper -> range.upper
else -> this
}
fun Float.reduceToRange(rangeFrom: Range<Float>, rangeTo: Range<Float>): Float =
when {
this == rangeFrom.lower -> rangeTo.lower
this == rangeFrom.upper -> rangeTo.upper
else -> {
val placeInRange = (this - rangeFrom.lower) / (rangeFrom.upper - rangeFrom.lower)
((rangeTo.upper - rangeTo.lower) * placeInRange) + rangeTo.lower
}
}
And at last, but not least - a class for vertical seek bar:
class ExpositionBar
@JvmOverloads
constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
private val drawingRect = RectF(0f, 0f, 0f, 0f)
private val drawingPaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val strokeWidth: Float
@ColorInt
private val strokeColor: Int
@ColorInt
private val buttonFillColor: Int
@ColorInt
private val buttonFillColorPressed: Int
private val icon: VectorDrawable
private val valuesRange: Range<Float>
private var centerX = 0f
private var minY = 0f
private var maxY = 0f
private var buttonCenterY = 0f
private var buttonRadiusExt = 0f
private var buttonRadiusInt = 0f
private var buttonMinY = 0f
private var buttonMaxY = 0f
private var buttonCenterBoundsRange = Range(0f, 0f)
private var iconTranslationX = 0f
private var iconTranslationY = 0f
private var isInDragMode = false
private var onValueChangeListener: ((Float) -> Unit)? = null
private var oldOutputValue = Float.MIN_VALUE
init {
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ExpositionBar)
icon = typedArray.getDrawable(R.styleable.ExpositionBar_button_icon) as VectorDrawable
val iconSize = typedArray.getDimensionPixelSize(R.styleable.ExpositionBar_button_icon_size, 0)
icon.setBounds(0, 0, iconSize, iconSize)
strokeWidth = typedArray.getDimensionPixelSize(R.styleable.ExpositionBar_stroke_width, 0).toFloat()
drawingPaint.strokeWidth = strokeWidth
strokeColor = typedArray.getColor(R.styleable.ExpositionBar_stroke_color, Color.WHITE)
buttonFillColor = typedArray.getColor(R.styleable.ExpositionBar_button_color, Color.BLACK)
buttonFillColorPressed = typedArray.getColor(R.styleable.ExpositionBar_button_color_pressed, Color.BLUE)
val minValue = typedArray.getFloat(R.styleable.ExpositionBar_min_value, 0f)
val maxValue = typedArray.getFloat(R.styleable.ExpositionBar_max_value, 0f)
valuesRange = Range(minValue, maxValue)
typedArray.recycle()
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
drawingRect.right = width.toFloat()
drawingRect.bottom = height.toFloat()
buttonCenterY = drawingRect.centerY()
recalculateDrawingValues()
}
override fun onDraw(canvas: Canvas) {
drawingPaint.color = strokeColor
drawingPaint.style = Paint.Style.STROKE
// Draw the center line
canvas.drawLine(centerX, minY, centerX, buttonMinY, drawingPaint)
canvas.drawLine(centerX, buttonMaxY, centerX, maxY, drawingPaint)
// Draw the button
canvas.drawCircle(centerX, buttonCenterY, buttonRadiusExt, drawingPaint)
drawingPaint.style = Paint.Style.FILL
drawingPaint.color = if(isInDragMode) buttonFillColorPressed else buttonFillColor
canvas.drawCircle(centerX, buttonCenterY, buttonRadiusInt, drawingPaint)
// Draw button icon
canvas.translate(iconTranslationX, iconTranslationY)
icon.draw(canvas)
canvas.translate(-iconTranslationX, -iconTranslationY)
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
if(!isEnabled) {
return false
}
when(event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
if(isButtonHit(event.y)){
isInDragMode = true
invalidate()
}
}
MotionEvent.ACTION_MOVE -> {
if(isInDragMode) {
buttonCenterY = event.y.fitInRange(buttonCenterBoundsRange)
recalculateDrawingValues()
invalidate()
val outputValue = buttonCenterY.reduceToRange(buttonCenterBoundsRange, valuesRange)
if (outputValue != oldOutputValue) {
onValueChangeListener?.invoke(outputValue)
oldOutputValue = outputValue
}
}
}
MotionEvent.ACTION_UP,
MotionEvent.ACTION_CANCEL -> {
isInDragMode = false
invalidate()
}
}
return true
}
fun setOnValueChangeListener(listener: ((Float) -> Unit)?) {
onValueChangeListener = listener
}
private fun recalculateDrawingValues() {
centerX = drawingRect.left + drawingRect.width()/2
minY = drawingRect.top
maxY = drawingRect.bottom
buttonRadiusExt = drawingRect.width() / 2 - strokeWidth / 2
buttonRadiusInt = buttonRadiusExt - strokeWidth / 2
buttonMinY = buttonCenterY - buttonRadiusExt
buttonMaxY = buttonCenterY + buttonRadiusExt
val buttonCenterMinY = minY + buttonRadiusExt + strokeWidth / 2
val buttonCenterMaxY = maxY - buttonRadiusExt - strokeWidth / 2
buttonCenterBoundsRange = Range(buttonCenterMinY, buttonCenterMaxY)
iconTranslationX = centerX - icon.bounds.width() / 2
iconTranslationY = buttonCenterY - icon.bounds.height() / 2
}
private fun isButtonHit(y: Float): Boolean {
return y >= buttonMinY && y <= buttonMaxY
}
}
You can use it as shown here:
<com.shevelev.wizard_camera.main_activity.view.widgets.ExpositionBar
android:id="@+id/expositionBar"
android:layout_width="@dimen/mainButtonSize"
android:layout_height="300dp"
android:layout_gravity="end|center_vertical"
android:layout_marginEnd="@dimen/marginNormal"
android:layout_marginBottom="26dp"
app:button_icon = "@drawable/ic_brightness"
app:button_icon_size = "@dimen/toolButtonIconSize"
app:stroke_width = "@dimen/strokeWidthNormal"
app:stroke_color = "@color/mainButtonsForeground"
app:button_color = "@color/mainButtonsBackground"
app:button_color_pressed = "@color/mainButtonsBackgroundPressed"
app:min_value="-100"
app:max_value="100"
/>
Voila!
when I send only one object from the client to server all works well.
when I attempt to send several objects one after another on the same stream I get
StreamCorruptedException
.
Actually, your client code is writing one object to the server and reading multiple objects from the server. And there is nothing on the server side that is writing the objects that the client is trying to read.
Just wanted to thank KM for his valuable solution. I implemented it myself to reduce the amount of lines in a shrinkdatabase request on SQLServer. Here is my SQL request if it can help anyone :
-- Declare the variable to be used
DECLARE @Query varchar (1000)
DECLARE @MyDBN varchar(11);
-- Initializing the @MyDBN variable (possible values : db1, db2, db3, ...)
SET @MyDBN = 'db1';
-- Creating the request to execute
SET @Query='use '+ @MyDBN +'; ALTER DATABASE '+ @MyDBN +' SET RECOVERY SIMPLE WITH NO_WAIT; DBCC SHRINKDATABASE ('+ @MyDBN +', 1, TRUNCATEONLY); ALTER DATABASE '+ @MyDBN +' SET RECOVERY FULL WITH NO_WAIT'
--
EXEC (@Query)
Basic counting is done as was stated in other answers, and in the pig documentation:
logs = LOAD 'log';
all_logs_in_a_bag = GROUP logs ALL;
log_count = FOREACH all_logs_in_a_bag GENERATE COUNT(logs);
dump log_count
You are right that counting is inefficient, even when using pig's builtin COUNT because this will use one reducer. However, I had a revelation today that one of the ways to speed it up would be to reduce the RAM utilization of the relation we're counting.
In other words, when counting a relation, we don't actually care about the data itself so let's use as little RAM as possible. You were on the right track with your first iteration of the count script.
logs = LOAD 'log'
ones = FOREACH logs GENERATE 1 AS one:int;
counter_group = GROUP ones ALL;
log_count = FOREACH counter_group GENERATE COUNT(ones);
dump log_count
This will work on much larger relations than the previous script and should be much faster. The main difference between this and your original script is that we don't need to sum anything.
This also doesn't have the same problem as other solutions where null values would impact the count. This will count all the rows, regardless of if the first column is null or not.
Laravel is not actually that slow. 500-1000ms is absurd; I got it down to 20ms in debug mode.
The problem was Vagrant/VirtualBox + shared folders. I didn't realize they incurred such a performance hit. I guess because Laravel has so many dependencies (loads ~280 files) and each of those file reads is slow, it adds up really quick.
kreeves pointed me in the right direction, this blog post describes a new feature in Vagrant 1.5 that lets you rsync your files into the VM rather than using a shared folder.
There's no native rsync client on Windows, so you'll have to use cygwin. Install it, and make sure to check off Net/rsync. Add C:\cygwin64\bin
to your paths. [Or you can install it on Win10/Bash]
Vagrant introduces the new feature. I'm using Puphet, so my Vagrantfile looks a bit funny. I had to tweak it to look like this:
data['vm']['synced_folder'].each do |i, folder|
if folder['source'] != '' && folder['target'] != '' && folder['id'] != ''
config.vm.synced_folder "#{folder['source']}", "#{folder['target']}",
id: "#{folder['id']}",
type: "rsync",
rsync__auto: "true",
rsync__exclude: ".hg/"
end
end
Once you're all set up, try vagrant up
. If everything goes smoothly your machine should boot up and it should copy all the files over. You'll need to run vagrant rsync-auto
in a terminal to keep the files up to date. You'll pay a little bit in latency, but for 30x faster page loads, it's worth it!
If you're using PhpStorm, it's auto-upload feature works even better than rsync. PhpStorm creates a lot of temporary files which can trip up file watchers, but if you let it handle the uploads itself, it works nicely.
One more option is to use lsyncd. I've had great success using this on Ubuntu host -> FreeBSD guest. I haven't tried it on a Windows host yet.
The answer would slightly tilt towards quicksort w.r.t to changes brought with DualPivotQuickSort for primitive values . It is used in JAVA 7 to sort in java.util.Arrays
It is proved that for the Dual-Pivot Quicksort the average number of
comparisons is 2*n*ln(n), the average number of swaps is 0.8*n*ln(n),
whereas classical Quicksort algorithm has 2*n*ln(n) and 1*n*ln(n)
respectively. Full mathematical proof see in attached proof.txt
and proof_add.txt files. Theoretical results are also confirmed
by experimental counting of the operations.
You can find the JAVA7 implmentation here - http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/util/Arrays.java
Further Awesome Reading on DualPivotQuickSort - http://permalink.gmane.org/gmane.comp.java.openjdk.core-libs.devel/2628
range for A-Z but if you want to go for example from A to DU then:
function generateAlphabet($na) {
$sa = "";
while ($na >= 0) {
$sa = chr($na % 26 + 65) . $sa;
$na = floor($na / 26) - 1;
}
return $sa;
}
$alphabet = Array();
for ($na = 0; $na < 125; $na++) {
$alphabet[]=generateAlphabet($na);
}
print_r($alphabet);
your answer will look like:
Array ( [0] => A [1] => B [2] => C [3] => D [4] => E [5] => F [6] => G [7] => H [8] => I [9] => J [10] => K [11] => L [12] => M [13] => N [14] => O [15] => P [16] => Q [17] => R [18] => S [19] => T [20] => U [21] => V [22] => W [23] => X [24] => Y [25] => Z [26] => AA [27] => AB [28] => AC [29] => AD [30] => AE [31] => AF [32] => AG [33] => AH [34] => AI [35] => AJ [36] => AK [37] => AL [38] => AM [39] => AN [40] => AO [41] => AP [42] => AQ [43] => AR [44] => AS [45] => AT [46] => AU [47] => AV [48] => AW [49] => AX [50] => AY [51] => AZ [52] => BA [53] => BB [54] => BC [55] => BD [56] => BE [57] => BF [58] => BG [59] => BH [60] => BI [61] => BJ [62] => BK [63] => BL [64] => BM [65] => BN [66] => BO [67] => BP [68] => BQ [69] => BR [70] => BS [71] => BT [72] => BU [73] => BV [74] => BW [75] => BX [76] => BY [77] => BZ [78] => CA [79] => CB [80] => CC [81] => CD [82] => CE [83] => CF [84] => CG [85] => CH [86] => CI [87] => CJ [88] => CK [89] => CL [90] => CM [91] => CN [92] => CO [93] => CP [94] => CQ [95] => CR [96] => CS [97] => CT [98] => CU [99] => CV [100] => CW [101] => CX [102] => CY [103] => CZ [104] => DA [105] => DB [106] => DC [107] => DD [108] => DE [109] => DF [110] => DG [111] => DH [112] => DI [113] => DJ [114] => DK [115] => DL [116] => DM [117] => DN [118] => DO [119] => DP [120] => DQ [121] => DR [122] => DS [123] => DT [124] => DU )
import UIKit
import SafariServices
let url = URL(string: "https://sprotechs.com")
let vc = SFSafariViewController(url: url!)
present(vc, animated: true, completion: nil)
Lot of very detailed answers here but I don't think you are answering the right questions. As I understand the question, there are two concerns:
You can use most of the scoring functions in scikit-learn with both multiclass problem as with single class problems. Ex.:
from sklearn.metrics import precision_recall_fscore_support as score
predicted = [1,2,3,4,5,1,2,1,1,4,5]
y_test = [1,2,3,4,5,1,2,1,1,4,1]
precision, recall, fscore, support = score(y_test, predicted)
print('precision: {}'.format(precision))
print('recall: {}'.format(recall))
print('fscore: {}'.format(fscore))
print('support: {}'.format(support))
This way you end up with tangible and interpretable numbers for each of the classes.
| Label | Precision | Recall | FScore | Support |
|-------|-----------|--------|--------|---------|
| 1 | 94% | 83% | 0.88 | 204 |
| 2 | 71% | 50% | 0.54 | 127 |
| ... | ... | ... | ... | ... |
| 4 | 80% | 98% | 0.89 | 838 |
| 5 | 93% | 81% | 0.91 | 1190 |
Then...
... you can tell if the unbalanced data is even a problem. If the scoring for the less represented classes (class 1 and 2) are lower than for the classes with more training samples (class 4 and 5) then you know that the unbalanced data is in fact a problem, and you can act accordingly, as described in some of the other answers in this thread. However, if the same class distribution is present in the data you want to predict on, your unbalanced training data is a good representative of the data, and hence, the unbalance is a good thing.
Look for assigning the output to Clipboard (in your first script) and then in second script parse Clipboard value.
Short Code
public class DB {
public static Connection c;
public static Connection getConnection() throws Exception {
if (c == null) {
Class.forName("com.mysql.jdbc.Driver");
c =DriverManager.getConnection("jdbc:mysql://localhost:3306/DATABASE", "USERNAME", "Password");
}
return c;
}
// Send data TO Database
public static void setData(String sql) throws Exception {
DB.getConnection().createStatement().executeUpdate(sql);
}
// Get Data From Database
public static ResultSet getData(String sql) throws Exception {
ResultSet rs = DB.getConnection().createStatement().executeQuery(sql);
return rs;
}
}
This will do it in Delphi. Note the use of the BitBlt function, which is a Windows API call, not something specific to Delphi.
Edit: Added example usage
function TForm1.GetScreenShot(OnlyActiveWindow: boolean) : TBitmap;
var
w,h : integer;
DC : HDC;
hWin : Cardinal;
r : TRect;
begin
//take a screenshot and return it as a TBitmap.
//if they specify "OnlyActiveWindow", then restrict the screenshot to the
//currently focused window (same as alt-prtscrn)
//Otherwise, get a normal screenshot (same as prtscrn)
Result := TBitmap.Create;
if OnlyActiveWindow then begin
hWin := GetForegroundWindow;
dc := GetWindowDC(hWin);
GetWindowRect(hWin,r);
w := r.Right - r.Left;
h := r.Bottom - r.Top;
end //if active window only
else begin
hWin := GetDesktopWindow;
dc := GetDC(hWin);
w := GetDeviceCaps(DC,HORZRES);
h := GetDeviceCaps(DC,VERTRES);
end; //else entire desktop
try
Result.Width := w;
Result.Height := h;
BitBlt(Result.Canvas.Handle,0,0,Result.Width,Result.Height,DC,0,0,SRCCOPY);
finally
ReleaseDC(hWin, DC) ;
end; //try-finally
end;
procedure TForm1.btnSaveScreenshotClick(Sender: TObject);
var
bmp : TBitmap;
savdlg : TSaveDialog;
begin
//take a screenshot, prompt for where to save it
savdlg := TSaveDialog.Create(Self);
bmp := GetScreenshot(False);
try
if savdlg.Execute then begin
bmp.SaveToFile(savdlg.FileName);
end;
finally
FreeAndNil(bmp);
FreeAndNil(savdlg);
end; //try-finally
end;