From what I understand you want to make a navigation bar or something similar to it. What I recommend doing is making a list and editing the items from there. Just try this;
<ul>
<li class='item col-md-12 panel' id='gameplay-title'>Title</li>
<li class='item col-md-6 col-md-offset-3 panel' id='gameplay-scoreboard'>Scoreboard</li>
</ul>
And so on... To add more categories add another ul in there. Now, for the CSS you just need this;
ul {
list-style: none;
}
.item {
display: inline;
padding-right: 20px;
}
A subtle alternative to MaxNoe's answer where you aren't explicitly setting the ticks but instead setting the cadence.
import matplotlib.pyplot as plt
from matplotlib.ticker import (AutoMinorLocator, MultipleLocator)
fig, ax = plt.subplots(figsize=(10, 8))
# Set axis ranges; by default this will put major ticks every 25.
ax.set_xlim(0, 200)
ax.set_ylim(0, 200)
# Change major ticks to show every 20.
ax.xaxis.set_major_locator(MultipleLocator(20))
ax.yaxis.set_major_locator(MultipleLocator(20))
# Change minor ticks to show every 5. (20/4 = 5)
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))
# Turn grid on for both major and minor ticks and style minor slightly
# differently.
ax.grid(which='major', color='#CCCCCC', linestyle='--')
ax.grid(which='minor', color='#CCCCCC', linestyle=':')
Sometimes the simple method is the best. Just pad your strings with spaces. If it is only a few textboxes etc this is by far the simplest method.
You can also simply insert blank columns/rows with a fixed size. Extremely simple and you can easily change it.
I suggest Freewall
. It is a cross-browser and responsive jQuery plugin to help you create many types of grid layouts: flexible layouts, images layouts, nested grid layouts, metro style layouts, pinterest like layouts ... with nice CSS3 animation effects and call back events. Freewall is all-in-one solution for creating dynamic grid layouts for desktop, mobile, and tablet.
Home page and document: also found here
.
you can try http://datatables.net/
DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table. Key features:
Yes, it is possible to do with out rebinding by implementing INotifyPropertyChanged Interface.
Pretty Simple example is available here,
http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx
Since column-ordering doesn't work in Bootstrap 4 beta as described in the code provided in the revisited answer above, you would need to use the following (as indicated in the codeply 4 Flexbox order demo - alpha/beta links that were provided in the answer).
<div class="container">
<div class="row">
<div class="col-3 col-md-6">
<div class="card card-block">1</div>
</div>
<div class="col-6 col-md-12 flex-md-last">
<div class="card card-block">3</div>
</div>
<div class="col-3 col-md-6 ">
<div class="card card-block">2</div>
</div>
</div>
Note however that the "Flexbox order demo - beta" goes to an alpha codebase, and changing the codebase to Beta (and running it) results in the divs incorrectly displaying in a single column -- but that looks like a codeply issue since cutting and pasting the code out of codeply works as described.
We have been using jqGrid on a project and have had some good luck with it. Lots of options for inline editing, etc. If that stuff isn't necessary, then we've just used a plain foreach loop like @Hrvoje.
Been using this in production for some time now without any complaints (May take some tweaking to look right on your site.. for instance, subtracting the width of a sidebar, etc)
$(window).bind('resize', function() {
$("#jqgrid").setGridWidth($(window).width());
}).trigger('resize');
You should give the container an id and use that in your custom css file (which should be linked after the bootstrap css):
#container {
box-shadow: values
}
A GridView is a ViewGroup that displays items in two-dimensional scrolling grid. The items in the grid come from the ListAdapter associated with this view.
This is what you'd want to use (keep using). Because a GridView gets its data from a ListAdapter, the only data loaded in memory will be the one displayed on screen. GridViews, much like ListViews reuse and recycle their views for better performance.
Whereas a GridLayout is a layout that places its children in a rectangular grid.
It was introduced in API level 14, and was recently backported in the Support Library. Its main purpose is to solve alignment and performance problems in other layouts. Check out this tutorial if you want to learn more about GridLayout.
Applies to Bootstrap 3 only.
Ignoring the letters (xs, sm, md, lg) for now, I'll start with just the numbers...
col-*-6
spans 6 of 12 columns (half the width), col-*-12
spans 12 of 12 columns (the entire width), etcSo, if you want two equal columns to span a div, write
<div class="col-xs-6">Column 1</div>
<div class="col-xs-6">Column 2</div>
Or, if you want three unequal columns to span that same width, you could write:
<div class="col-xs-2">Column 1</div>
<div class="col-xs-6">Column 2</div>
<div class="col-xs-4">Column 3</div>
You'll notice the # of columns always add up to 12. It can be less than twelve, but beware if more than 12, as your offending divs will bump down to the next row (not .row
, which is another story altogether).
You can also nest columns within columns, (best with a .row
wrapper around them) such as:
<div class="col-xs-6">
<div class="row">
<div class="col-xs-4">Column 1-a</div>
<div class="col-xs-8">Column 1-b</div>
</div>
</div>
<div class="col-xs-6">
<div class="row">
<div class="col-xs-2">Column 2-a</div>
<div class="col-xs-10">Column 2-b</div>
</div>
</div>
Each set of nested divs also span up to 12 columns of their parent div. NOTE: Since each .col
class has 15px padding on either side, you should usually wrap nested columns in a .row
, which has -15px margins. This avoids duplicating the padding and keeps the content lined up between nested and non-nested col classes.
-- You didn't specifically ask about the xs, sm, md, lg
usage, but they go hand-in-hand so I can't help but touch on it...
In short, they are used to define at which screen size that class should apply:
Read the "Grid Options" chapter from the official Bootstrap documentation for more details.
You should usually classify a div using multiple column classes so it behaves differently depending on the screen size (this is the heart of what makes bootstrap responsive). eg: a div with classes col-xs-6
and col-sm-4
will span half the screen on the mobile phone (xs) and 1/3 of the screen on tablets(sm).
<div class="col-xs-6 col-sm-4">Column 1</div> <!-- 1/2 width on mobile, 1/3 screen on tablet) -->
<div class="col-xs-6 col-sm-8">Column 2</div> <!-- 1/2 width on mobile, 2/3 width on tablet -->
NOTE: as per comment below, grid classes for a given screen size apply to that screen size and larger unless another declaration overrides it (i.e. col-xs-6 col-md-4
spans 6 columns on xs
and sm
, and 4 columns on md
and lg
, even though sm
and lg
were never explicitly declared)
NOTE: if you don't define xs
, it will default to col-xs-12
(i.e. col-sm-6
is half the width on sm
, md
and lg
screens, but full-width on xs
screens).
NOTE: it's actually totally fine if your .row
includes more than 12 cols, as long as you are aware of how they will react. --This is a contentious issue, and not everyone agrees.
Apart from the options already given in other answers, there's a current more active, recent and open-source project called pygubu
.
This is the first description by the author taken from the github repository:
Pygubu is a RAD tool to enable quick & easy development of user interfaces for the python tkinter module.
The user interfaces designed are saved as XML, and by using the pygubu builder these can be loaded by applications dynamically as needed. Pygubu is inspired by Glade.
Pygubu hello world program is an introductory video explaining how to create a first project using Pygubu
.
The following in an image of interface of the last version of pygubu
designer on a OS X Yosemite 10.10.2:
I would definitely give it a try, and contribute to its development.
One way is to use the Grid's select()
and dataItem()
methods.
In single selection case, select()
will return a single row which can be passed to dataItem()
var entityGrid = $("#EntitesGrid").data("kendoGrid");
var selectedItem = entityGrid.dataItem(entityGrid.select());
// selectedItem has EntityVersionId and the rest of your model
For multiple row selection select()
will return an array of rows. You can then iterate through the array and the individual rows can be passed into the grid's dataItem()
.
var entityGrid = $("#EntitesGrid").data("kendoGrid");
var rows = entityGrid.select();
rows.each(function(index, row) {
var selectedItem = entityGrid.dataItem(row);
// selectedItem has EntityVersionId and the rest of your model
});
This will get the name in the ng-repeat to come up seperate in the form validation.
<td>
<input ng-model="r.QTY" class="span1" name="{{'QTY' + $index}}" ng-pattern="/^[\d]*\.?[\d]*$/" required/>
</td>
But I had trouble getting it to look up in its validation message so I had to use an ng-init to get it to resolve a variable as the object key.
<td>
<input ng-model="r.QTY" class="span1" ng-init="name = 'QTY' + $index" name="{{name}}" ng-pattern="/^[\d]*\.?[\d]*$/" required/>
<span class="alert-error" ng-show="form[name].$error.pattern"><strong>Requires a number.</strong></span>
<span class="alert-error" ng-show="form[name].$error.required"><strong>*Required</strong></span>
The best way to do this is to sort the list before binding data source.
cars = cars.OrderBy(o => o.year).ThenBy(o => o.color).ToList();
adgCars.DataSource = cars;
Sorry for my bad english.
As always, read Bootstrap's great documentation:
3.x Docs: https://getbootstrap.com/docs/3.3/css/#grid-nesting
Make sure the parent level row is inside of a .container
element. Whenever you'd like to nest rows, just open up a new .row
inside of your column.
Here's a simple layout to work from:
<div class="container">
<div class="row">
<div class="col-xs-6">
<div class="big-box">image</div>
</div>
<div class="col-xs-6">
<div class="row">
<div class="col-xs-6"><div class="mini-box">1</div></div>
<div class="col-xs-6"><div class="mini-box">2</div></div>
<div class="col-xs-6"><div class="mini-box">3</div></div>
<div class="col-xs-6"><div class="mini-box">4</div></div>
</div>
</div>
</div>
</div>
4.0 Docs: http://getbootstrap.com/docs/4.0/layout/grid/#nesting
Here's an updated version for 4.0, but you should really read the entire docs section on the grid so you understand how to leverage this powerful feature
<div class="container">
<div class="row">
<div class="col big-box">
image
</div>
<div class="col">
<div class="row">
<div class="col mini-box">1</div>
<div class="col mini-box">2</div>
</div>
<div class="row">
<div class="col mini-box">3</div>
<div class="col mini-box">4</div>
</div>
</div>
</div>
</div>
Which will look like this (with a little bit of added styling):
You could assign both the width and height of the element using either vw
or vh
. For example:
#anyElement {
width: 20vh;
height: 20vh;
}
This would set both the width and height to 20% of the browser's current height, retaining the aspect ratio. However, this only works if you want to scale proportionate to the viewport dimensions.
You can use jQuery
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#divId").load("b.html");
});
</script>
</head>
<body>
<div id="divId" style="display:none;"></div>
</body>
</html>
on click event you can make it display block .
Change the content-type to "application/x-www-form-urlencoded", i solved the problem.
Visual Studio 2015 doesn't install C++ by default. You have to rerun the setup, select Modify and then check Programming Language -> C++
I added a modal dialog in jsp and tried to open it with javascript in jsx and hit the same error: "...modal is not a function"
In my case, simply by adding the missing import to the jsx solved the problem.
`import "./../bower/bootstrap/js/modal.js"; // or import ".../bootstrap.min.js"`
! is a logical NOT operator, it's a boolean operator that will invert something to its opposite.
Although you can bypass the parentheses of the invoked function by using the BANG (!) before the function, it will still invert the return, which might not be what you wanted. As in the case of an IEFE, it would return undefined, which when inverted becomes the boolean true.
Instead, use the closing parenthesis and the BANG (!) if needed.
// I'm going to leave the closing () in all examples as invoking the function with just ! and () takes away from what's happening.
(function(){ return false; }());
=> false
!(function(){ return false; }());
=> true
!!(function(){ return false; }());
=> false
!!!(function(){ return false; }());
=> true
Other Operators that work...
+(function(){ return false; }());
=> 0
-(function(){ return false; }());
=> -0
~(function(){ return false; }());
=> -1
Combined Operators...
+!(function(){ return false; }());
=> 1
-!(function(){ return false; }());
=> -1
!+(function(){ return false; }());
=> true
!-(function(){ return false; }());
=> true
~!(function(){ return false; }());
=> -2
~!!(function(){ return false; }());
=> -1
+~(function(){ return false; }());
+> -1
Use org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider
API
A component provider that scans the classpath from a base package. It then applies exclude and include filters to the resulting classes to find candidates.
ClassPathScanningCandidateComponentProvider scanner =
new ClassPathScanningCandidateComponentProvider(<DO_YOU_WANT_TO_USE_DEFALT_FILTER>);
scanner.addIncludeFilter(new AnnotationTypeFilter(<TYPE_YOUR_ANNOTATION_HERE>.class));
for (BeanDefinition bd : scanner.findCandidateComponents(<TYPE_YOUR_BASE_PACKAGE_HERE>))
System.out.println(bd.getBeanClassName());
While performance issues are valid the real reasons in practice that you should avoid storing images in a database are for database management reasons. Your database will grow very rapidly and databases cost much more than simple file storage. Database backups and restores are much more expensive and time-consuming than file backup restores. In a pinch, you can restore a smaller database much more quickly than one bloated with images. Compare 1 TB of file storage on Azure to a 1 TB database and you'll see the vast difference in cost.
http://php.net/manual/en/function.strpos.php I think you are wondiner if 'some text' exists in the string right?
if(strpos( $a , 'some text' ) !== false)
You want to do something like this instead:
<Button>
<StackPanel>
<Image Source="Pictures/apple.jpg" />
<TextBlock>Disconnect from Server</TextBlock>
</StackPanel>
</Button>
You can also use plt.setp
as follows:
import matplotlib.pyplot as plt
import seaborn as sns
plot=sns.barplot(data=df, x=" ", y=" ")
plt.setp(plot.get_xticklabels(), rotation=90)
to rotate the labels 90 degrees.
tmux
instead of screen
as suggested in the original answer below, if you choose to use that solution.:term
command. This provides much more complete integration with the rest of the Vim features.I would definitely recommend screen
for something like this. Vim is a text editor, not a shell.
I would use Ctrl+AS to split the current window horizontally, or in Ubuntu's screen and other patched versions, you can use Ctrl+A|(pipe) to split vertically. Then use Ctrl+ATab (or equivalently on some systems, Ctrl+ACtrl+I which may be easier to type) to switch between the windows. There are other commands to change the size and arrangement of the windows.
Or a less advanced use of screen
is just to open multiple full-screen windows and toggle between them. This is what I normally do, I only use the split screen feature occasionally.
The GNU Screen Survival Guide question has a number of good tips if you're unfamiliar with its use.
You can also use the constant service as such. Defining the function outside of the constant call allows it to be recursive as well.
function doSomething( a, b ) {
return a + b;
};
angular.module('moduleName',[])
// Define
.constant('$doSomething', doSomething)
// Usage
.controller( 'SomeController', function( $doSomething ) {
$scope.added = $doSomething( 100, 200 );
})
;
To make the transform work in development (using F5 or CTRL + F5) I drop ctt.exe (https://ctt.codeplex.com/) in the packages folder (packages\ConfigTransform\ctt.exe).
Then I register a pre- or post-build event in Visual Studio...
$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)connectionStrings.config" transform:"$(ProjectDir)connectionStrings.$(ConfigurationName).config" destination:"$(ProjectDir)connectionStrings.config"
$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)web.config" transform:"$(ProjectDir)web.$(ConfigurationName).config" destination:"$(ProjectDir)web.config"
For the transforms I use SlowCheeta VS extension (https://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5).
You could create a helper function to take care of that:
/**
* Return string before needle if it exists.
*
* @param string $str
* @param mixed $needle
* @return string
*/
function str_before($str, $needle)
{
$pos = strpos($str, $needle);
return ($pos !== false) ? substr($str, 0, $pos) : $str;
}
Here's a use case:
$sing = 'My name is Luka. I live on the second floor.';
echo str_before($sing, '.'); // My name is Luka
WebDriver driver=new FirefoxDriver();
driver.get("http://www.java-examples.com/java-string-examples");
Thread.sleep(3000);
//Switch to nested frame
driver.switchTo().frame("aswift_2").switchTo().frame("google_ads_frame3");
Unless you enabled innodb_file_per_table
option, InnoDB
keeps all data in one file, usually called ibdata1
.
Check the size of that file and check you have enough disk space in the drive it resides on.
Seems like only real solutions today revolve around scaling out or sharding. All modern databases (NoSQLs as well as NewSQLs) support horizontal scaling right out of the box, at the database layer, without the need for the application to have sharding code or something.
Unfortunately enough, for the trusted good-old MySQL, sharding is not provided "out of the box". ScaleBase (disclaimer: I work there) is a maker of a complete scale-out solution an "automatic sharding machine" if you like. ScaleBae analyzes your data and SQL stream, splits the data across DB nodes, and aggregates in runtime – so you won’t have to! And it's free download.
Don't get me wrong, NoSQLs are great, they're new, new is more choice and choice is always good!! But choosing NoSQL comes with a price, make sure you can pay it...
You can see here some more data about MySQL, NoSQL...: http://www.scalebase.com/extreme-scalability-with-mongodb-and-mysql-part-1-auto-sharding
Hope that helped.
None of the solutions mentioned above worked for a hostname that is different from localhost
!
I had to add notify: false
to the list of options that I pass to $state.go
, to avoid calling Angular change listeners, before $window.location.reload
call gets called. Final code looks like:
$state.go('home', {}, {reload: true, notify: false});
>>> EDIT - $timeout might be necessary depending on your browser >>>
$timeout(function () {
$window.location.reload(true);
}, 100);
<<< END OF EDIT <<<
More about this on ui-router reference.
if(x==null)
is a bad idea in JavaScript. Judge with "=="
- it may cause an unexpected type coercion, and it can't be read by CoffeeScript,
never use "==" or "!=" in condition judgment!
if(x)
will be better, but be careful with 0 and "". It will be treated as false, not the equal method with "!= null"
is true.
celery 4+ celery purge command to purge all configured task queues
celery -A *APPNAME* purge
programmatically:
from proj.celery import app
app.control.purge()
all pending task will be purged. Reference: celerydoc
This is v. easy, have been doing work on this for the past few weeks.
You need the Batik SVG Toolkit. Download, and place the files in the same directory as the SVG you want to convert to a JPEG, also make sure you unzip it first.
Open the terminal, and run this command:
java -jar batik-rasterizer.jar -m image/jpeg -q 0.8 NAME_OF_SVG_FILE.svg
That should output a JPEG of the SVG file. Really easy. You can even just place it in a loop and convert loads of SVGs,
import os
svgs = ('test1.svg', 'test2.svg', 'etc.svg')
for svg in svgs:
os.system('java -jar batik-rasterizer.jar -m image/jpeg -q 0.8 '+str(svg)+'.svg')
I had from a totaly different reason the same notice "Value does not fall within the expected range" from the Visual studio 2008 while trying to use the: Tools -> Windows Embedded Silverlight Tools -> Update Silverlight For Windows Embedded Project.
After spending many ohurs I found out that the problem was that there wasn't a resource file and the update tool looks for the .RC file
Therefor the solution is to add to the resource folder a .RC file and than it works perfectly. I hope it will help someone out there
ValueErrors :In Python, a value is the information that is stored within a certain object. To encounter a ValueError in Python means that is a problem with the content of the object you tried to assign the value to.
in your case name,lastname and email 3 parameters are there but unpaidmembers only contain 2 of them.
name, lastname, email in unpaidMembers.items() so you should refer data or your code might be
lastname, email in unpaidMembers.items() or name, email in unpaidMembers.items()
Try dragging a UIView
onto the screen in IB. From there you can drag a UIImageView
and UILabel
into the view you just created. Set the image of the UIImageView
in the properties inspector as the custom bullet image (which you will have to add to your project by dragging it into the navigation pane) and you can write some text in the label.
I think the solution is just as simple as this:
Card temp = deck[cardAindex];
deck[cardAIndex]=deck[cardBIndex];
deck[cardBIndex]=temp;
Number of a columns in the result set you can get with code (as DB is used PostgreSQL):
//load the driver for PostgreSQL Class.forName("org.postgresql.Driver"); String url = "jdbc:postgresql://localhost/test"; Properties props = new Properties(); props.setProperty("user","mydbuser"); props.setProperty("password","mydbpass"); Connection conn = DriverManager.getConnection(url, props); //create statement Statement stat = conn.createStatement(); //obtain a result set ResultSet rs = stat.executeQuery("SELECT c1, c2, c3, c4, c5 FROM MY_TABLE"); //from result set give metadata ResultSetMetaData rsmd = rs.getMetaData(); //columns count from metadata object int numOfCols = rsmd.getColumnCount();
But you can get more meta-informations about columns:
for(int i = 1; i <= numOfCols; i++)
{
System.out.println(rsmd.getColumnName(i));
}
And at least but not least, you can get some info not just about table but about DB too, how to do it you can find here and here.
Some of these above answers didn't work for me but this did. Just in case someone else has the same issue.
ng-show="column != 'vendorid' && column !='billingMonth'"
Layout
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="300dp"
android:gravity="center"
android:layout_height="300dp"
android:layout_centerInParent="true"
android:background="@drawable/rounded_edge">
</LinearLayout>
Drawable folder rounded_edge.xml
<shape
xmlns:android="http://schemas.android.com/apk/res/android">
<solid
android:color="@android:color/darker_gray">
</solid>
<stroke
android:width="0dp"
android:color="#424242">
</stroke>
<corners
android:topLeftRadius="100dip"
android:topRightRadius="100dip"
android:bottomLeftRadius="100dip"
android:bottomRightRadius="100dip">
</corners>
</shape>
If HTML and use bootstrap they have a helper class.
<span class="text-nowrap">1-866-566-7233</span>
When none of the if
test in number_translator()
evaluate to true, the function returns None
. The error message is the consequence of that.
Whenever you see an error that include 'NoneType'
that means that you have an operand or an object that is None
when you were expecting something else.
let pattern = /^(?=.*[0-9])(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9!@#$%^&*]{6,16}$/;
//following will give you the result as true(if the password contains Capital, small letter, number and special character) or false based on the string format
let reee =pattern .test("helLo123@"); //true as it contains all the above
Destructing assignment is the best way to solve your problem.
var a = 1;
var b = 2;
[a, b] = [b, a];
console.log("After swap a =", a, " and b =", b);
_x000D_
You could try a formatter like this
They will always be limited because they don't (and can't) know what user defined functions you may have defined in your database (or which built-in functions you have or don't have access to).
You could also look at ANTLR (but that would be an offline solution)
Simply enter these into Windows command prompt.
cd C:\Program Files\Java\jdk1.7.0_09\bin
keytool -exportcert -alias androiddebugkey -keystore "C:\Users\userName\.android\debug.keystore" -list -v
The base password is android
You will be presented with the MD5
, SHA1
, and SHA256
keys; Choose the one you need.
At the end you will get your Public dns.
I don't know if it has an official name, but I call it the Right-Left Thingy(TM).
Start at the variable, then go right, and left, and right...and so on.
int* arr1[8];
arr1
is an array of 8 pointers to integers.
int (*arr2)[8];
arr2
is a pointer (the parenthesis block the right-left) to an array of 8 integers.
int *(arr3[8]);
arr3
is an array of 8 pointers to integers.
This should help you out with complex declarations.
I may sound quite naive, and may attract quite a criticism, but here's how I did it,
(It doesn't involve ajax
for export, but it doesn't do a full postback either )
Thanks for this post and this answer.
Create a simple controller
public class HomeController : Controller
{
/* A demo action
public ActionResult Index()
{
return View(model);
}
*/
[HttpPost]
public FileResult ExportData()
{
/* An example filter
var filter = TempData["filterKeys"] as MyFilter;
TempData.Keep(); */
var someList = db.GetDataFromDb(/*filter*/) // filter as an example
/*May be here's the trick, I'm setting my filter in TempData["filterKeys"]
in an action,(GetFilteredPartial() illustrated below) when 'searching' for the data,
so do not really need ajax here..to pass my filters.. */
//Some utility to convert list to Datatable
var dt = Utility.ConvertToDataTable(someList);
// I am using EPPlus nuget package
using (ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet1");
ws.Cells["A1"].LoadFromDataTable(dt, true);
using (var memoryStream = new MemoryStream())
{
pck.SaveAs(memoryStream);
return File(memoryStream.ToArray(),
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"ExportFileName.xlsx");
}
}
}
//This is just a supporting example to illustrate setting up filters ..
/* [HttpPost]
public PartialViewResult GetFilteredPartial(MyFilter filter)
{
TempData["filterKeys"] = filter;
var filteredData = db.GetConcernedData(filter);
var model = new MainViewModel();
model.PartialViewModel = filteredData;
return PartialView("_SomePartialView", model);
} */
}
And here are the Views..
/*Commenting out the View code, in order to focus on the imp. code
@model Models.MainViewModel
@{Layout...}
Some code for, say, a partial View
<div id="tblSampleBody">
@Html.Partial("_SomePartialView", Model.PartialViewModel)
</div>
*/
//The actual part.. Just **posting** this bit of data from the complete View...
//Here, you are not posting the full Form..or the complete View
@using (Html.BeginForm("ExportData", "Home", FormMethod.Post))
{
<input type="submit" value="Export Data" />
}
//...
//</div>
/*And you may require to pass search/filter values.. as said in the accepted answer..
That can be done while 'searching' the data.. and not while
we need an export..for instance:-
<script>
var filterData = {
SkipCount: someValue,
TakeCount: 20,
UserName: $("#UserName").val(),
DepartmentId: $("#DepartmentId").val(),
}
function GetFilteredData() {
$("#loader").show();
filterData.SkipCount = 0;
$.ajax({
url: '@Url.Action("GetFilteredPartial","Home")',
type: 'POST',
dataType: "html",
data: filterData,
success: function (dataHTML) {
if ((dataHTML === null) || (dataHTML == "")) {
$("#tblSampleBody").html('<tr><td>No Data Returned</td></tr>');
$("#loader").hide();
} else {
$("#tblSampleBody").html(dataHTML);
$("#loader").hide();
}
}
});
}
</script>*/
The whole point of the trick seems that, we are posting a form (a part of the Razor View ) upon which we are calling an Action method
, which returns: a FileResult
, and this FileResult
returns the Excel File
..
And for posting the filter values, as said, ( and if you require to), I am making a post request to another action, as has been attempted to describe..
It is not always so simple and sometimes the alignment must be defined in the container and not in the Button element itself !
For your case, the solution would be
<div style="text-align:right; width:100%; padding:0;">
<input type="button" value="Click Me"/>
</div>
I have taken care to specify width=100%
to be sure that <div>
take full width of his container.
I have also added padding:0
to avoid before and after space as with <p>
element.
I can say that if <div>
is defined in a FSF/Primefaces table's footer, the float:right
don't work correctly because the Button height will become higher than the footer height !
In this Primefaces situation, the only acceptable solution is to use text-align:right
in container.
With this solution, if you have 6 Buttons to align at right, you must only specify this alignment in container :-)
<div style="text-align:right; width:100%; padding:0;">
<input type="button" value="Click Me 1"/>
<input type="button" value="Click Me 2"/>
<input type="button" value="Click Me 3"/>
<input type="button" value="Click Me 4"/>
<input type="button" value="Click Me 5"/>
<input type="button" value="Click Me 6"/>
</div>
You may want to look at IBExpert Personal Edition. While not open source, this is a very good tool for designing, building, and administering Firebird and InterBase databases.
The Personal Edition is free, but some of the more advanced features are not available. Still, even without the slick extras, the free version is very powerful.
I use SQLite Database Browser for SQLite3 currently and it's pretty useful. Works across Windows/OS X/Linux and is lightweight and fast. Slightly unstable with executing SQL on the DB if it's incorrectly formatted.
Edit: I have recently discovered SQLite Manager, a plugin for Firefox. Obviously you need to run Firefox, but you can close all windows and just run it "standalone". It's very feature complete, amazingly stable and it remembers your databases! It has tonnes of features so I've moved away from SQLite Database Browser as the instability and lack of features is too much to bear.
I use Object.keys
which is built into JavaScript Object, it will return an array of keys from given object MDN Reference
var obj = {name: "Jeeva", age: "22", gender: "Male"}
console.log(Object.keys(obj))
When you download the connector/NET choose Select Platform = .NET & Mono (not windows!)
The following gives you list of operating system users sorted by number of connections, which is useful when looking for excessive resource usage.
select osuser, count(*) as active_conn_count
from v$session
group by osuser
order by active_conn_count desc
Well if you are new to C# with cmd-line exp. you can use online sites like "https://curl.olsh.me/" or search curl to C# converter will returns site that could do that for you.
or if you are using postman you can use Generate Code Snippet only problem with Postman code generator is the dependency on RestSharp library.
Programmatically it can be done by :
image_button.setAlpha(0f) // to make it full transparent
image_button.setAlpha(0.5f) // to make it half transparent
image_button.setAlpha(0.6f) // to make it (40%) transparent
image_button.setAlpha(1f) // to make it opaque
In my case, I deleted out the caniuse-lite
, browserslist
folders from node_modules
.
Then I type the following command to install the packages.
npm i -g browserslist caniuse-lite --save
worked fine.
Just use Hash.[]
with the values in the array. For example:
arr = [1,2,3,4]
Hash[*arr] #=> gives {1 => 2, 3 => 4}
textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)),
for: .editingChanged)
and handle method:
@objc func textFieldDidChange(_ textField: UITextField) {
}
textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)),
for: UIControlEvents.editingChanged)
and handle method:
@objc func textFieldDidChange(_ textField: UITextField) {
}
textField.addTarget(self, action: #selector(textFieldDidChange(textField:)), for: .editingChanged)
and handle method:
func textFieldDidChange(textField: UITextField) {
}
In javascript almost everything is an object, null
and undefined
are exception.
Instances of Array
is an object. so you can set property of an array, for the same reason,you can't set property of a undefined, because its NOT an object
Another single-line Python 3 option but with explicit separator:
print(*range(1,11), sep=' ')
This is a slight variation that worked better for me.
$csv = Join-Path $env:TEMP "input.csv"
$xls = Join-Path $env:TEMP "output.xlsx"
$xl = new-object -comobject excel.application
$xl.visible = $false
$Workbook = $xl.workbooks.open($CSV)
$Worksheets = $Workbooks.worksheets
$Workbook.SaveAs($XLS,1)
$Workbook.Saved = $True
$xl.Quit()
Here is the code snippet I found:
var audio = new Audio();
audio.src ='http://translate.google.com/translate_tts?ie=utf-8&tl=en&q=Hello%20World.';
audio.play();
For python2 you can also do this
'%(author)s in %(publication)s'%{'author':unicode(self.author),
'publication':unicode(self.publication)}
which is handy if you have a lot of arguments to substitute (particularly if you are doing internationalisation)
Python2.6 onwards supports .format()
'{author} in {publication}'.format(author=self.author,
publication=self.publication)
Those variables are shell variables. To expand them as parameters to another program (ie expr
), you need to use the $
prefix:
expr $x / $y
The reason it complained is because it thought you were trying to operate on alphabetic characters (ie non-integer)
If you are using the Bash shell, you can achieve the same result using expression syntax:
echo $((x / y))
Or:
z=$((x / y))
echo $z
Inside the input tag you can add autoFocus={true} for anyone using jsx/react.
<input
type="email"
name="email"
onChange={e => setEmail(e.target.value)}
value={email}
placeholder={"Email..."}
autoFocus={true}
/>
Yes, once the return
statement is executed, the entire function is exited at that very point.
Just imagine what would happen if it did not and continued looping, and executing that return
statement each time? It would invalidate it's meaning of returning a value when you think about it.
First Way:
In Kotlin we can create a simple extension for view:
fun View.getLocationOnScreen(): Point
{
val location = IntArray(2)
this.getLocationOnScreen(location)
return Point(location[0],location[1])
}
And simply get coordinates:
val location = yourView.getLocationOnScreen()
val absX = location.x
val absY = location.y
Second Way:
The Second way is more simple :
fun View.absX(): Int
{
val location = IntArray(2)
this.getLocationOnScreen(location)
return location[0]
}
fun View.absY(): Int
{
val location = IntArray(2)
this.getLocationOnScreen(location)
return location[1]
}
and simply get absolute X by view.absX()
and Y by view.absY()
I use this code, it works nice
html, body {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
background: black url(back2.png) center center no-repeat;;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
This:
https://github.com/jbtule/cdto#cd-to
It's a small app that you drag into the Finder toolbar, the icon fits in very nicely. It works with Terminal, xterm (under X11), iterm.
This one worked for me:
df=df.sort_values(by=[2])
Whereas:
df=df.sort_values(by=['2'])
is not working.
Yet another solution is to use csvsql tool from amazing csvkit suite.
Usage example:
csvsql --db mysql://$user:$password@localhost/$database --insert --tables $tablename $file
This tool can automatically infer the data types (default behavior), create table and insert the data into the created table. --overwrite
option can be used to drop table if it already exists. --insert
option — to populate the table from the file.
pip install csvkit
Prerequisites: python-dev
, libmysqlclient-dev
, MySQL-python
apt-get install python-dev libmysqlclient-dev
pip install MySQL-python
Same problem. List contained numbers of type numpy.int64 which throws a TypeError
. Quick workaround for me was to
mylist = eval(str(mylist_of_integers))
json.dumps({'mylist': mylist})
which converts list
to str()
and eval()
function evaluates the String like a Python expression and returns the result as a list of integers
in my case.
git checkout branch_name file_name
Example:
git checkout master App.java
This will not work if your branch name has a period in it.
git checkout "fix.june" alive.html
error: pathspec 'fix.june' did not match any file(s) known to git.
Sorry for the necro on this post, but I feel compelled to weigh in on a couple of things that do not seem to have been touched on.
First a foremost - when we find ourselves needing access to private members on a class during unit testing, it is generally a big, fat red flag that we've goofed in our strategic or tactical approach and have inadvertently violated the single responsibility principal by pushing behavior where it does not belong. Feeling the need to access methods that are really nothing more than an isolated subroutine of a construction procedure is one of the most common occurrences of this; however, it's kind of like your boss expecting you to show up for work ready-to-go and also having some perverse need to know what morning routine you went through to get you into that state...
The other most common instance of this happening is when you find yourself trying to test the proverbial "god class." It is a special kind of problem in and of itself, but suffers from the same basic issue with needing to know intimate details of a procedure - but that's getting off topic.
In this specific example, we've effectively assigned the responsibility of fully initializing the Bar object to the FooBar class's constructor. In object oriented programming, one of the core tenents is that the constructor is "sacred" and should be guarded against invalid data that would invalidate its' own internal state and leave it primed to fail somewhere else downstream (in what could be a very deep pipeline.)
We've failed to do that here by allowing the FooBar object to accept a Bar that is not ready at the time that the FooBar is constructed, and have compensated by sort-of "hacking" the FooBar object to take matters into its' own hands.
This is the result of a failure to adhere to another tenent of object oriented programming (in the case of Bar,) which is that an object's state should be fully initialized and ready to handle any incoming calls to its' public members immediately after creation. Now, this does not mean immediately after the constructor is called in all instances. When you have an object that has many complex construction scenarios, then it is better to expose setters to its optional members to an object that is implemented in accordance with a creation design-pattern (Factory, Builder, etc...) In any of the latter cases, you would be pushing the initialization of the target object off into another object graph whose sole purpose is directing traffic to get you to a point where you have a valid instance of that which you are requesting - and the product should not be considered "ready" until after this creation object has served it up.
In your example, the Bar's "status" property does not seem to be in a valid state in which a FooBar can accept it - so the FooBar does something to it to correct that issue.
The second issue I am seeing is that it appears that you are trying to test your code rather than practice test-driven development. This is definitely my own opinion at this point in time; but, this type of testing is really an anti-pattern. What you end up doing is falling into the trap of realizing that you have core design problems that prevent your code from being testable after the fact, rather than writing the tests you need and subsequently programming to the tests. Either way you come at the problem, you should still end up with the same number of tests and lines of code had you truly achieved a SOLID implementation. So - why try and reverse engineer your way into testable code when you can just address the matter at the onset of your development efforts?
Had you done that, then you would have realized much earlier on that you were going to have to write some rather icky code in order to test against your design and would have had the opportunity early on to realign your approach by shifting behavior to implementations that are easily testable.
The error shows that com.bd.service.ArticleService
is not a registered bean. Add the packages in which you have beans that will be autowired in your application context:
<context:component-scan base-package="com.bd.service"/>
<context:component-scan base-package="com.bd.controleur"/>
Alternatively, if you want to include all subpackages in com.bd
:
<context:component-scan base-package="com.bd">
<context:include-filter type="aspectj" expression="com.bd.*" />
</context:component-scan>
As a side note, if you're using Spring 3.1 or later, you can take advantage of the @ComponentScan
annotation, so that you don't have to use any xml configuration regarding component-scan. Use it in conjunction with @Configuration
.
@Controller
@RequestMapping("/Article/GererArticle")
@Configuration
@ComponentScan("com.bd.service") // No need to include component-scan in xml
public class ArticleControleur {
@Autowired
ArticleService articleService;
...
}
You might find this Spring in depth section on Autowiring useful.
You could use strcmp()
:
/* strcmp example */
#include <stdio.h>
#include <string.h>
int main ()
{
char szKey[] = "apple";
char szInput[80];
do {
printf ("Guess my favourite fruit? ");
gets (szInput);
} while (strcmp (szKey,szInput) != 0);
puts ("Correct answer!");
return 0;
}
The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct
approach is executed like:
business_key
values to a temporary tableThe group by
could be executed like:
business key
in a hashtableThe first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.
Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.
You can also lean on the IDE a little. If you run the program using the "Start without debugging" command (Ctrl+F5 for me), the console window will stay open even after the program ends with a "Press any key to continue . . ." message.
Of course, if want to use the "Hit any key" to keep your program running (i.e. keep a thread alive), this won't work. And it does not work when you run "with debugging". But then you can use break points to hold the window open.
You could just use index
on the list to find where somevalue
is and then get the previous and next as needed:
def find_prev_next(elem, elements):
previous, next = None, None
index = elements.index(elem)
if index > 0:
previous = elements[index -1]
if index < (len(elements)-1):
next = elements[index +1]
return previous, next
foo = 'three'
list = ['one','two','three', 'four', 'five']
previous, next = find_prev_next(foo, list)
print previous # should print 'two'
print next # should print 'four'
Please use count function, Here is a example how to count array in a element
$cars = array("Volvo","BMW","Toyota");
echo count($cars);
The count()
function returns the number of elements in an array.
The sizeof()
function returns the number of elements in an array.
The sizeof()
function is an alias of the count()
function.
I realize this is an old post but I find myself coming back to this thread a lot as it is one of the top search results when searching for this topic. However, I always leave more confused then when I came due to the conflicting information. Ultimately I always have to perform my own tests to figure it out. So this time I will post my findings.
TL;DR Most people will want to use Exit
to terminate a running scripts. However, if your script is merely declaring functions to later be used in a shell, then you will want to use Return
in the definitions of said functions.
Exit: This will "exit" the currently running context. If you call this command from a script it will exit the script. If you call this command from the shell it will exit the shell.
If a function calls the Exit command it will exit what ever context it is running in. So if that function is only called from within a running script it will exit that script. However, if your script merely declares the function so that it can be used from the current shell and you run that function from the shell, it will exit the shell because the shell is the context in which the function contianing the Exit
command is running.
Note: By default if you right click on a script to run it in PowerShell, once the script is done running, PowerShell will close automatically. This has nothing to do with the Exit
command or anything else in your script. It is just a default PowerShell behavior for scripts being ran using this specific method of running a script. The same is true for batch files and the Command Line window.
Return: This will return to the previous call point. If you call this command from a script (outside any functions) it will return to the shell. If you call this command from the shell it will return to the shell (which is the previous call point for a single command ran from the shell). If you call this command from a function it will return to where ever the function was called from.
Execution of any commands after the call point that it is returned to will continue from that point. If a script is called from the shell and it contains the Return
command outside any functions then when it returns to the shell there are no more commands to run thus making a Return
used in this way essentially the same as Exit
.
Break: This will break out of loops and switch cases. If you call this command while not in a loop or switch case it will break out of the script. If you call Break
inside a loop that is nested inside a loop it will only break out of the loop it was called in.
There is also an interesting feature of Break
where you can prefix a loop with a label and then you can break out of that labeled loop even if the Break
command is called within several nested groups within that labeled loop.
While ($true) {
# Code here will run
:myLabel While ($true) {
# Code here will run
While ($true) {
# Code here will run
While ($true) {
# Code here will run
Break myLabel
# Code here will not run
}
# Code here will not run
}
# Code here will not run
}
# Code here will run
}
This is an old post, but if IE is giving you trouble. Change your GET requests to POST and IE will no longer cache them.
I spent way too much time figuring this out the hard way. Hope it helps.
The behavior of applets changes significantly with update 51. It's going to be a confusing couple of weeks for RIA developers. Recommended reading: https://blogs.oracle.com/java-platform-group/entry/new_security_requirements_for_rias
I searched for a long time to find alternative code to the accepted solution in the hopes of not using an external assembly/project. I came up with the following thanks to the source code of the DynamicJson project:
public XmlDocument JsonToXML(string json)
{
XmlDocument doc = new XmlDocument();
using (var reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(json), XmlDictionaryReaderQuotas.Max))
{
XElement xml = XElement.Load(reader);
doc.LoadXml(xml.ToString());
}
return doc;
}
Note: I wanted an XmlDocument rather than an XElement for xPath purposes. Also, this code obviously only goes from JSON to XML, there are various ways to do the opposite.
You should consider svcutil (svcutil question)
Both xsd.exe and svcutil operate on the XML schema file (.xsd). Your XML must conform to a schema file to be used by either of these two tools.
Note that various 3rd party tools also exist for this.
Perhaps you don't have to include the single quotes:
curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/&fileName=1.doc"
Update: Reading curl's manual, you could actually separate both fields with two --data:
curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/" --data "fileName=1.doc"
You could also try --data-binary:
curl --request POST 'http://localhost/Service' --data-binary "path=/xyz/pqr/test/" --data-binary "fileName=1.doc"
And --data-urlencode:
curl --request POST 'http://localhost/Service' --data-urlencode "path=/xyz/pqr/test/" --data-urlencode "fileName=1.doc"
CASE
is an expression - it returns a single scalar value (per row). It can't return a complex part of the parse tree of something else, like an ORDER BY
clause of a SELECT
statement.
It looks like you just need:
ORDER BY
CASE WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount END desc,
CASE WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount END desc,
Case WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount END DESC,
CASE WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount END DESC,
Case WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount END DESC,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC
Or possibly:
ORDER BY
CASE
WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount
WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount
WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount
WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount
WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount
END desc,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC
It's a little tricky to tell which of the above (or something else) is what you're looking for because you've a) not explained what actual sort order you're trying to achieve, and b) not supplied any sample data and expected results, from which we could attempt to deduce the actual sort order you're trying to achieve.
This may be the answer we're looking for:
ORDER BY
CASE
WHEN TblList.PinRequestCount <> 0 THEN 5
WHEN TblList.HighCallAlertCount <> 0 THEN 4
WHEN TblList.HighAlertCount <> 0 THEN 3
WHEN TblList.MediumCallAlertCount <> 0 THEN 2
WHEN TblList.MediumAlertCount <> 0 THEN 1
END desc,
CASE
WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount
WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount
WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount
WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount
WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount
END desc,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC
As per this example:
import numpy as np
import matplotlib.pyplot as plt
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
plt.scatter(x, y)
plt.show()
will produce:
To unpack your data from pairs into lists use zip
:
x, y = zip(*li)
So, the one-liner:
plt.scatter(*zip(*li))
Wow, ya'll are overthinking it. It's as simple as the following. Besides, many of those answers aren't understood by the RE2 dialect used by C and golang.
^$
Add a single line AddKeysToAgent yes
on the top of the .ssh/config file. Ofcourse ssh-agent must be running beforehand. If its not running ( check by prep ssh-agent
) , then simply run it eval $(ssh-agent)
Now, the key is loaded systemwide into the memory and you dont have to type in the passphrase again.
The source of the solution is https://askubuntu.com/questions/362280/enter-ssh-passphrase-once/853578#853578
You may need to handle javax.persistence.RollbackException
this will make the powershell window to wait until you press any key:
pause
Update One
Thanks to Stein. it is the Enter key not any key.
I fixed the issue by creating my own .ico file and created a assets folder and put the file over there. Then changed the link href in Index.html
Yes! You can create a shortcut to cmd.exe with a command specified after it. Alternatively you could create a batch script, if your goal is just to have a clickable way to run commands.
Steps:
Right click on some empty space in Explorer, and in the context menu go to "New/Shortcut".
When prompted to enter a location put either:
"C:\Windows\System32\cmd.exe /k your-command
" This will run the command and keep (/k) the command prompt open after.
or
"C:\Windows\System32\cmd.exe /c your-command
" This will run the command and the close (/c) the command prompt.
Notes:
Tested, and working on Windows 8 - Core X86-64 September 12 2014
If you want to have more than one command, place an "&" symbol in between them. For example: "C:\Windows\System32\cmd.exe /k command1 & command2
".
On SmtpClient there is an EnableSsl property that you would set.
i.e.
SmtpClient client = new SmtpClient(exchangeServer);
client.EnableSsl = true;
client.Send(msg);
Three years late, but my Googling brought me here so hopefully my answer will be useful for someone else.
I just created a second option (which I hid with CSS) and used Javascript to move the s backwards and forwards between them.
<select multiple id="sel1">
<option class="set1">Blah</option>
</select>
<select multiple id="sel2" style="display:none">
<option class="set2">Bleh</option>
</select>
Something like that, and then something like this will move an item onto the list (i.e., make it visible). Obviously adapt the code as needed for your purpose.
$('#sel2 .set2').appendTo($('#sel1'))
You could create a class to represent this
public class Range
{
private int low;
private int high;
public Range(int low, int high){
this.low = low;
this.high = high;
}
public boolean contains(int number){
return (number >= low && number <= high);
}
}
Sample usage:
Range range = new Range(0, 2147483647);
if (range.contains(foo)) {
//do something
}
If statement is used for checking just one condition quickly.
When you have multiple options, use <xsl:choose>
as illustrated below:
<xsl:choose>
<xsl:when test="$CreatedDate > $IDAppendedDate">
<h2>mooooooooooooo</h2>
</xsl:when>
<xsl:otherwise>
<h2>dooooooooooooo</h2>
</xsl:otherwise>
</xsl:choose>
Also, you can use multiple <xsl:when>
tags to express If .. Else If
or Switch
patterns as illustrated below:
<xsl:choose>
<xsl:when test="$CreatedDate > $IDAppendedDate">
<h2>mooooooooooooo</h2>
</xsl:when>
<xsl:when test="$CreatedDate = $IDAppendedDate">
<h2>booooooooooooo</h2>
</xsl:when>
<xsl:otherwise>
<h2>dooooooooooooo</h2>
</xsl:otherwise>
</xsl:choose>
The previous example would be equivalent to the pseudocode below:
if ($CreatedDate > $IDAppendedDate)
{
output: <h2>mooooooooooooo</h2>
}
else if ($CreatedDate = $IDAppendedDate)
{
output: <h2>booooooooooooo</h2>
}
else
{
output: <h2>dooooooooooooo</h2>
}
The recommended approach in this case is to sort the data in the database, adding an ORDER BY
at the end of the query that fetches the results, something like this:
SELECT temperature FROM temperatures ORDER BY temperature ASC; -- ascending order
SELECT temperature FROM temperatures ORDER BY temperature DESC; -- descending order
If for some reason that is not an option, you can change the sorting order like this in Python:
templist = [25, 50, 100, 150, 200, 250, 300, 33]
sorted(templist, key=int) # ascending order
> [25, 33, 50, 100, 150, 200, 250, 300]
sorted(templist, key=int, reverse=True) # descending order
> [300, 250, 200, 150, 100, 50, 33, 25]
As has been pointed in the comments, the int
key (or float
if values with decimals are being stored) is required for correctly sorting the data if the data received is of type string
, but it'd be very strange to store temperature values as strings, if that is the case, go back and fix the problem at the root, and make sure that the temperatures being stored are numbers.
Here is a cleaned up version for current Android devices, functional method design so that you can copy it to an AssetsHelper class e.g ;)
/**
*
* Info: prior to Android 2.3, any compressed asset file with an
* uncompressed size of over 1 MB cannot be read from the APK. So this
* should only be used if the device has android 2.3 or later running!
*
* @param c
* @param targetFolder
* e.g. {@link Environment#getExternalStorageDirectory()}
* @throws Exception
*/
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static boolean copyAssets(AssetManager assetManager,
File targetFolder) throws Exception {
Log.i(LOG_TAG, "Copying files from assets to folder " + targetFolder);
return copyAssets(assetManager, "", targetFolder);
}
/**
* The files will be copied at the location targetFolder+path so if you
* enter path="abc" and targetfolder="sdcard" the files will be located in
* "sdcard/abc"
*
* @param assetManager
* @param path
* @param targetFolder
* @return
* @throws Exception
*/
public static boolean copyAssets(AssetManager assetManager, String path,
File targetFolder) throws Exception {
Log.i(LOG_TAG, "Copying " + path + " to " + targetFolder);
String sources[] = assetManager.list(path);
if (sources.length == 0) { // its not a folder, so its a file:
copyAssetFileToFolder(assetManager, path, targetFolder);
} else { // its a folder:
if (path.startsWith("images") || path.startsWith("sounds")
|| path.startsWith("webkit")) {
Log.i(LOG_TAG, " > Skipping " + path);
return false;
}
File targetDir = new File(targetFolder, path);
targetDir.mkdirs();
for (String source : sources) {
String fullSourcePath = path.equals("") ? source : (path
+ File.separator + source);
copyAssets(assetManager, fullSourcePath, targetFolder);
}
}
return true;
}
private static void copyAssetFileToFolder(AssetManager assetManager,
String fullAssetPath, File targetBasePath) throws IOException {
InputStream in = assetManager.open(fullAssetPath);
OutputStream out = new FileOutputStream(new File(targetBasePath,
fullAssetPath));
byte[] buffer = new byte[16 * 1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
out.flush();
out.close();
}
Unfortunately, the string.encode() method is not always reliable. Check out this thread for more information: What is the fool proof way to convert some string (utf-8 or else) to a simple ASCII string in python
I do it as below
$("a[rel=popover]").click(function(event){
if(event.which == 1)
{
$thisPopOver = $(this);
$thisPopOver.popover('toggle');
$thisPopOver.parent("li").click(function(event){
event.stopPropagation();
$("html").click(function(){
$thisPopOver.popover('hide');
});
});
}
});
Hope this helps!
Use mysql_fetch_assoc instead of mysql_fetch_array
You can use always stream writer.It will erase old data and append new one each time.
using (StreamWriter sw = new StreamWriter(filePath))
{
getNumberOfControls(frm1,sw);
}
The URLRewrite is sort of a "hack" if you want to call it that. What it comes down to is, you're re-inventing the wheel; as there are already existing solutions. Another thing to remember is Http Server = Static content & App server = dynamic content (this is how they were designed). By delegating the appropriate responsibilities to each server you maximize efficiency... but now-a-days this is probably only a concern in a performance critical environments and something like Tomcat would most likely work well in both roles most of the time; but it is still something to keep in mind none the less.
The error states that the psql utility can't find the socket to connect to your database server. Either you don't have the database service running in the background, or the socket is located elsewhere, or perhaps the pg_hba.conf
needs to be fixed.
The command may vary depending on your operating system. But on most *ix systems the following would work, it will search for postgres among all running processes
ps -ef | grep postgres
On my system, mac osx, this spits out
501 408 1 0 2Jul15 ?? 0:21.63 /usr/local/opt/postgresql/bin/postgres -D /usr/local/var/postgres -r /usr/local/var/postgres/server.log
The last column shows the command used to start the server, and the options.
You can look at all the options available to start the postgres server using the following.
man postgres
From there, you'd see that the options -D
and -r
are respectively the datadir
& the logfilename
.
Use find
to search for the location of the socket, which should be somewhere in the /tmp
sudo find /tmp/ -name .s.PGSQL.5432
If postgres is running and accepting socket connections, the above should tell you the location of the socket. On my machine, it turned out to be:
/tmp/.s.PGSQL.5432
Then, try connecting via psql using this file's location explicitly, eg.
psql -h /tmp/ dbname
If you can't find the socket, but see that the service is running, Verify that the pg_hba.conf file allows local sockets.
Browse to the datadir
and you should find the pg_hba.conf
file.
By default, near the bottom of the file you should see the following lines:
# "local" is for Unix domain socket connections only
local all all trust
If you don't see it, you can modify the file, and restart the postgres service.
This one may be better and shorter:
function stringIncludes(a, b) {
return a.indexOf(b) >= 0;
}
You can call a function on click event of button.
<input type="button" class="btn btn-info" value="Input Button" onclick=" relocate_home()">
<script>
function relocate_home()
{
location.href = "www.yoursite.com";
}
</script>
OR Use this Code
<a href="#link" class="btn btn-info" role="button">Link Button</a>
How to install PyQt4 on anaconda python 2 on Windows:
At first I have tried to isntall pyqt4 via pip install
:
C:\Users\myuser\Anaconda2\Scripts\pip.exe search pyqt4 > pyqt4.txt
It shows:
PyQt4 (4.11.4) - Python bindings for the Qt cross platform GUI toolkit
But when I tried to install, it gives an error:
C:\Users\myuser\Anaconda2\Scripts\pip.exe install PyQt4
Collecting PyQt4
Could not find a version that satisfies the requirement PyQt4 (from versions:
)
No matching distribution found for PyQt4
Seems this answer is realated to this problem: https://superuser.com/a/725869/213959
Then I have tried to install it via conda install
( How to install PyQt4 in anaconda? ) :
C:\Users\myuser\Anaconda2\Scripts\conda.exe search pyqt
It shows:
pyqt 4.10.4 py26_0 defaults
4.10.4 py27_0 defaults
4.10.4 py33_0 defaults
4.10.4 py34_0 defaults
4.10.4 py26_1 defaults
4.10.4 py27_1 defaults
4.10.4 py33_1 defaults
4.10.4 py34_1 defaults
4.11.4 py27_0 defaults
4.11.4 py35_0 defaults
4.11.4 py27_2 defaults
4.11.4 py34_2 defaults
4.11.4 py35_2 defaults
4.11.4 py27_3 defaults
4.11.4 py34_3 defaults
4.11.4 py35_3 defaults
4.11.4 py27_4 defaults
4.11.4 py34_4 defaults
4.11.4 py35_4 defaults
4.11.4 py27_5 defaults
4.11.4 py34_5 defaults
4.11.4 py35_5 defaults
4.11.4 py27_6 defaults
4.11.4 py34_6 defaults
4.11.4 py35_6 defaults
4.11.4 py27_7 defaults
4.11.4 py34_7 defaults
4.11.4 py35_7 defaults
5.6.0 py27_0 defaults
5.6.0 py34_0 defaults
5.6.0 py35_0 defaults
5.6.0 py27_1 defaults
5.6.0 py34_1 defaults
5.6.0 py35_1 defaults
5.6.0 py27_2 defaults
5.6.0 py34_2 defaults
5.6.0 py35_2 defaults
5.6.0 py36_2 defaults
5.6.0 py27h224ed30_5 defaults
5.6.0 py35hd46907b_5 defaults
5.6.0 py36hb5ed885_5 defaults
But it gives error:
C:\Users\myuser\Anaconda2\Scripts\conda.exe install pyqt=4.11.4
Fetching package metadata .............
Solving package specifications: .
UnsatisfiableError: The following specifications were found to be in conflict:
- navigator-updater -> pyqt >=5.6 -> qt 5.6.*
- pyqt 4.11.4* -> qt >=4.8.6,<5.0
- pyqt 4.11.4* -> sip >=4.16.4,<4.18
Use "conda info <package>" to see the dependencies for each package.
Same with -c
parameter:
C:\Users\myuser\Anaconda2\Scripts\conda.exe install -c anaconda pyqt=4.11.4
Fetching package metadata ...............
Solving package specifications: .
UnsatisfiableError: The following specifications were found to be in conflict:
- navigator-updater -> pyqt >=5.6 -> qt 5.6.*
- pyqt 4.11.4* -> qt >=4.8.6,<5.0
- pyqt 4.11.4* -> sip >=4.16.4,<4.18
Use "conda info <package>" to see the dependencies for each package.
Then I tried to uninstall pyqt
:
C:\Users\myuser\Anaconda2\Scripts\conda.exe uninstall pyqt
And installed it again:
C:\Users\myuser\Anaconda2\Scripts\conda.exe install -c anaconda pyqt=4.11.4
And finnaly it works!
You should write your own stream manipulator
cout << multi(5) << "whatever" << "lolcat";
In Jenkins 2.60.3 there is a way to delete build artifacts (not the archived artifacts) in order to save hard drive space on the build machine. In the General section, check "Discard old builds" with strategy "Log Rotation" and then go into its Advanced options. Two more options will appear related to keeping build artifacts for the job based on number of days or builds.
The settings that work for me are to enter 1 for "Max # of builds to keep with artifacts" and then to have a post-build action to archive the artifacts. This way, all artifacts from all builds will be archived, all information from builds will be saved, but only the last build will keep its own artifacts.
You should use "merge a range of revision".
To merge changes from the trunk to a branch, inside the branch working copy choose "merge range of revisions" and enter the trunk URL and the start and end revisions to merge.
The same in the opposite way to merge a branch in the trunk.
About the --reintegrate flag, check the manual here: http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-merge.html#tsvn-dug-merge-reintegrate
The data series names are defined by the column headers. Add the names to the column headers that you would like to use as titles for each of your data series, select all of the data (including the headers), then re-generate your graph. The names in the headers should then appear as the names in the legend for each series.
String[] command = {"cmd.exe" , "/c", "start" , "cmd.exe" , "/k" , "\" dir && ipconfig
\"" };
ProcessBuilder probuilder = new ProcessBuilder( command );
probuilder.directory(new File("D:\\Folder1"));
Process process = probuilder.start();
The solution I present is safe, simple and compatible with Internet Explorer, FireFox and Chrome.
This approach is new and complete. I not found nothing equal to that solution on the internet. Is simple, cross-browser (Internet Explorer, Chrome and Firefox), preserves the layout, use the select itself and is easy to use.
Note: JQuery is required.
HTML CODE
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CustonSelect</title>
<script type="text/javascript" src="./jquery-1.3.2.js"></script>
<script type="text/javascript" src="./CustomSelect.js"></script>
</head>
<div id="testDiv"></div>
<body>
<table>
<tr>
<td>
<select id="Select0" >
<option value="0000">0000</option>
<option value="0001">0001</option>
<option value="0002">0002</option>
<option value="0003">0003</option>
<option value="0004">0004</option>
<option value="0005">0005</option>
<option value="0006">0006</option>
<option value="0007">0007</option>
<option value="0008">0008</option>
<option value="0009">0009</option>
<option value="0010">0010</option>
<option value="0011">0011</option>
<option value="0012">0012</option>
<option value="0013">0013</option>
<option value="0014">0014</option>
<option value="0015">0015</option>
<option value="0016">0016</option>
<option value="0017">0017</option>
<option value="0018">0018</option>
<option value="0019">0019</option>
<option value="0020">0020</option>
<option value="0021">0021</option>
<option value="0022">0022</option>
<option value="0023">0023</option>
<option value="0024">0024</option>
<option value="0025">0025</option>
<option value="0026">0026</option>
<option value="0027">0027</option>
<option value="0028">0028</option>
<option value="0029">0029</option>
<option value="0030">0030</option>
<option value="0031">0031</option>
<option value="0032">0032</option>
<option value="0033">0033</option>
<option value="0034">0034</option>
<option value="0035">0035</option>
<option value="0036">0036</option>
<option value="0037">0037</option>
<option value="0038">0038</option>
<option value="0039">0039</option>
<option value="0040">0040</option>
</select>
</td>
</tr>
<tr>
<td>
<select id="Select1" >
<option value="0000">0000</option>
<option value="0001">0001</option>
<option value="0002">0002</option>
<option value="0003">0003</option>
<option value="0004">0004</option>
<option value="0005">0005</option>
<option value="0006">0006</option>
<option value="0007">0007</option>
<option value="0008">0008</option>
<option value="0009">0009</option>
<option value="0010">0010</option>
<option value="0011">0011</option>
<option value="0012">0012</option>
<option value="0013">0013</option>
<option value="0014">0014</option>
<option value="0015">0015</option>
<option value="0016">0016</option>
<option value="0017">0017</option>
<option value="0018">0018</option>
<option value="0019">0019</option>
<option value="0020">0020</option>
<option value="0021">0021</option>
<option value="0022">0022</option>
<option value="0023">0023</option>
<option value="0024">0024</option>
<option value="0025">0025</option>
<option value="0026">0026</option>
<option value="0027">0027</option>
<option value="0028">0028</option>
<option value="0029">0029</option>
<option value="0030">0030</option>
<option value="0031">0031</option>
<option value="0032">0032</option>
<option value="0033">0033</option>
<option value="0034">0034</option>
<option value="0035">0035</option>
<option value="0036">0036</option>
<option value="0037">0037</option>
<option value="0038">0038</option>
<option value="0039">0039</option>
<option value="0040">0040</option>
</select>
</td>
</tr>
<tr>
<td>
<select id="Select2" >
<option value="0000">0000</option>
<option value="0001">0001</option>
<option value="0002">0002</option>
<option value="0003">0003</option>
<option value="0004">0004</option>
<option value="0005">0005</option>
<option value="0006">0006</option>
<option value="0007">0007</option>
<option value="0008">0008</option>
<option value="0009">0009</option>
<option value="0010">0010</option>
<option value="0011">0011</option>
<option value="0012">0012</option>
<option value="0013">0013</option>
<option value="0014">0014</option>
<option value="0015">0015</option>
<option value="0016">0016</option>
<option value="0017">0017</option>
<option value="0018">0018</option>
<option value="0019">0019</option>
<option value="0020">0020</option>
<option value="0021">0021</option>
<option value="0022">0022</option>
<option value="0023">0023</option>
<option value="0024">0024</option>
<option value="0025">0025</option>
<option value="0026">0026</option>
<option value="0027">0027</option>
<option value="0028">0028</option>
<option value="0029">0029</option>
<option value="0030">0030</option>
<option value="0031">0031</option>
<option value="0032">0032</option>
<option value="0033">0033</option>
<option value="0034">0034</option>
<option value="0035">0035</option>
<option value="0036">0036</option>
<option value="0037">0037</option>
<option value="0038">0038</option>
<option value="0039">0039</option>
<option value="0040">0040</option>
</select>
</td>
</tr>
<tr>
<td>
<select id="Select3" >
<option value="0000">0000</option>
<option value="0001">0001</option>
<option value="0002">0002</option>
<option value="0003">0003</option>
<option value="0004">0004</option>
<option value="0005">0005</option>
<option value="0006">0006</option>
<option value="0007">0007</option>
<option value="0008">0008</option>
<option value="0009">0009</option>
<option value="0010">0010</option>
<option value="0011">0011</option>
<option value="0012">0012</option>
<option value="0013">0013</option>
<option value="0014">0014</option>
<option value="0015">0015</option>
<option value="0016">0016</option>
<option value="0017">0017</option>
<option value="0018">0018</option>
<option value="0019">0019</option>
<option value="0020">0020</option>
<option value="0021">0021</option>
<option value="0022">0022</option>
<option value="0023">0023</option>
<option value="0024">0024</option>
<option value="0025">0025</option>
<option value="0026">0026</option>
<option value="0027">0027</option>
<option value="0028">0028</option>
<option value="0029">0029</option>
<option value="0030">0030</option>
<option value="0031">0031</option>
<option value="0032">0032</option>
<option value="0033">0033</option>
<option value="0034">0034</option>
<option value="0035">0035</option>
<option value="0036">0036</option>
<option value="0037">0037</option>
<option value="0038">0038</option>
<option value="0039">0039</option>
<option value="0040">0040</option>
</select>
</td>
</tr>
<tr>
<td>
<select id="Select4" >
<option value="0000">0000</option>
<option value="0001">0001</option>
<option value="0002">0002</option>
<option value="0003">0003</option>
<option value="0004">0004</option>
<option value="0005">0005</option>
<option value="0006">0006</option>
<option value="0007">0007</option>
<option value="0008">0008</option>
<option value="0009">0009</option>
<option value="0010">0010</option>
<option value="0011">0011</option>
<option value="0012">0012</option>
<option value="0013">0013</option>
<option value="0014">0014</option>
<option value="0015">0015</option>
<option value="0016">0016</option>
<option value="0017">0017</option>
<option value="0018">0018</option>
<option value="0019">0019</option>
<option value="0020">0020</option>
<option value="0021">0021</option>
<option value="0022">0022</option>
<option value="0023">0023</option>
<option value="0024">0024</option>
<option value="0025">0025</option>
<option value="0026">0026</option>
<option value="0027">0027</option>
<option value="0028">0028</option>
<option value="0029">0029</option>
<option value="0030">0030</option>
<option value="0031">0031</option>
<option value="0032">0032</option>
<option value="0033">0033</option>
<option value="0034">0034</option>
<option value="0035">0035</option>
<option value="0036">0036</option>
<option value="0037">0037</option>
<option value="0038">0038</option>
<option value="0039">0039</option>
<option value="0040">0040</option>
</select>
</td>
</tr>
</table>
<input type="button" id="Button0" value="MoveLayout!"/>
</body>
</html>
JAVASCRIPT CODE
var customSelectFields = new Array();
// Note: The list of selects to be modified! By Questor
customSelectFields[0] = "Select0";
customSelectFields[1] = "Select1";
customSelectFields[2] = "Select2";
customSelectFields[3] = "Select3";
customSelectFields[4] = "Select4";
$(document).ready(function()
{
//Note: To debug! By Questor
$("#Button0").click(function(event){ AddTestDiv(); });
StartUpCustomSelect(null);
});
//Note: To test! By Questor
function AddTestDiv()
{
$("#testDiv").append("<div style=\"width:100px;height:100px;\"></div>");
}
//Note: Startup selects customization scheme! By Questor
function StartUpCustomSelect(what)
{
for (i = 0; i < customSelectFields.length; i++)
{
$("#" + customSelectFields[i] + "").click(function(event){ UpCustomSelect(this); });
$("#" + customSelectFields[i] + "").wrap("<div id=\"selectDiv_" + customSelectFields[i] + "\" onmouseover=\"BlockCustomSelectAgain();\" status=\"CLOSED\"></div>").parent().after("<div id=\"coverSelectDiv_" + customSelectFields[i] + "\" onclick=\"UpOrDownCustomSelect(this);\" onmouseover=\"BlockCustomSelectAgain();\"></div>");
//Note: Avoid breaking the layout when the CSS is modified from "position" to "absolute" on the select! By Questor
$("#" + customSelectFields[i] + "").parent().css({'width': $("#" + customSelectFields[i] + "")[0].offsetWidth + 'px', 'height': $("#" + customSelectFields[i] + "")[0].offsetHeight + 'px'});
BlockCustomSelect($("#" + customSelectFields[i] + ""));
}
}
//Note: Repositions the div that covers the select using the "onmouseover" event so
//Note: if element on the screen move the div always stand over it (recalculate! By Questor
function BlockCustomSelectAgain(what)
{
for (i = 0; i < customSelectFields.length; i++)
{
if($("#" + customSelectFields[i] + "").parent().attr("status") == "CLOSED")
{
BlockCustomSelect($("#" + customSelectFields[i] + ""));
}
}
}
//Note: Does not allow the select to be clicked or clickable! By Questor
function BlockCustomSelect(what)
{
var coverSelectDiv = $(what).parent().next();
//Note: Ensures the integrity of the div style! By Questor
$(coverSelectDiv).removeAttr('style');
//Note: To resolve compatibility issues! By Questor
var backgroundValue = "";
var filerValue = "";
if(navigator.appName == "Microsoft Internet Explorer")
{
backgroundValue = 'url(fakeimage)';
filerValue = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=\'scale\', src=\'fakeimage\' )';
}
//Note: To debug! By Questor
//'border': '5px #000 solid',
$(coverSelectDiv).css({
'position': 'absolute',
'top': $(what).offset().top + 'px',
'left': $(what).offset().left + 'px',
'width': $(what)[0].offsetWidth + 'px',
'height': $(what)[0].offsetHeight + 'px',
'background': backgroundValue,
'-moz-background-size':'cover',
'-webkit-background-size':'cover',
'background-size':'cover',
'filer': filerValue
});
}
//Note: Allow the select to be clicked or clickable! By Questor
function ReleaseCustomSelect(what)
{
var coverSelectDiv = $(what).parent().next();
$(coverSelectDiv).removeAttr('style');
$(coverSelectDiv).css({'display': 'none'});
}
//Note: Open the select! By Questor
function DownCustomSelect(what)
{
//Note: Avoid breaking the layout. Avoid that select events be overwritten by the others! By Questor
$(what).css({
'position': 'absolute',
'z-index': '100'
});
//Note: Open dropdown! By Questor
$(what).attr("size","10");
ReleaseCustomSelect(what);
//Note: Avoids the side-effect of the select loses focus.! By Questor
$(what).focus();
//Note: Allows you to select elements using the enter key when the select is on focus! By Questor
$(what).keyup(function(e){
if(e.keyCode == 13)
{
UpCustomSelect(what);
}
});
//Note: Closes the select when loses focus! By Questor
$(what).blur(function(e){
UpCustomSelect(what);
});
$(what).parent().attr("status", "OPENED");
}
//Note: Close the select! By Questor
function UpCustomSelect(what)
{
$(what).css("position","static");
//Note: Close dropdown! By Questor
$(what).attr("size","1");
BlockCustomSelect(what);
$(what).parent().attr("status", "CLOSED");
}
//Note: Closes or opens the select depending on the current status! By Questor
function UpOrDownCustomSelect(what)
{
var customizedSelect = $($(what).prev().children()[0]);
if($(what).prev().attr("status") == "CLOSED")
{
DownCustomSelect(customizedSelect);
}
else if($(what).prev().attr("status") == "OPENED")
{
UpCustomSelect(customizedSelect);
}
}
You have 3 options:
1) Get default value
dt = datetime??DateTime.Now;
it will assign DateTime.Now
(or any other value which you want) if datetime
is null
2) Check if datetime contains value and if not return empty string
if(!datetime.HasValue) return "";
dt = datetime.Value;
3) Change signature of method to
public string ConvertToPersianToShow(DateTime datetime)
It's all because DateTime?
means it's nullable DateTime
so before assigning it to DateTime
you need to check if it contains value and only then assign.
This query run for me ( for MySQL). mytable_backup must be present before this query run.
insert into mytable_backup select * from mytable
Rather than using JavaScript perhaps try something like
<a href="#">
<input type="submit" value="save" style="background: transparent none; border: 0px none; text-decoration: inherit; color: inherit; cursor: inherit" />
</a>
>>> import random
>>> random.randrange(5,60,5)
should work in any Python >= 2.
Just cast one of the two operands to a float first.
v = (float)s / t;
The cast has higher precedence than the division, so happens before the division.
The other operand will be effectively automatically cast to a float by the compiler because the rules say that if either operand is of floating point type then the operation will be a floating point operation, even if the other operand is integral. Java Language Specification, §4.2.4 and §15.17
The function you need is CInt
.
ie CInt(PrinterLabel)
See Type Conversion Functions (Visual Basic) on MSDN
Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!
First Install This Package:
Install-Package SixLabors.ImageSharp -Version 1.0.0-beta0007
[SixLabors.ImageSharp][1] [1]: https://www.nuget.org/packages/SixLabors.ImageSharp
Then use Below Code For Cast Byte Array To Image :
Image<Rgba32> image = Image.Load(byteArray);
For Get ImageFormat Use Below Code:
IImageFormat format = Image.DetectFormat(byteArray);
For Mutate Image Use Below Code:
image.Mutate(x => x.Resize(new Size(1280, 960)));
Actually you can also make the Junit test a runnable Jar and call the runnable jar as java -jar
window.location.href = 'newPage.html';
window
is Global)location.href = 'newPage.html';
If you are here because you are losing HTTP_REFERER when redirecting, keep reading:
(Otherwise ignore this last part)
The following section is for those using HTTP_REFERER
as one of many security measures (although it isn't a great protective measure). If you're using Internet Explorer 8 or lower, these variables get lost when using any form of JavaScript page redirection (location.href, etc.).
Below we are going to implement an alternative for IE8 & lower so that we don't lose HTTP_REFERER. Otherwise, you can almost always simply use window.location.href
.
Testing against HTTP_REFERER
(URL pasting, session, etc.) can help tell whether a request is legitimate.
(Note: there are also ways to work-around / spoof these referrers, as noted by droop's link in the comments)
Simple cross-browser testing solution (fallback to window.location.href for Internet Explorer 9+ and all other browsers)
Usage: redirect('anotherpage.aspx');
function redirect (url) {
var ua = navigator.userAgent.toLowerCase(),
isIE = ua.indexOf('msie') !== -1,
version = parseInt(ua.substr(4, 2), 10);
// Internet Explorer 8 and lower
if (isIE && version < 9) {
var link = document.createElement('a');
link.href = url;
document.body.appendChild(link);
link.click();
}
// All other browsers can use the standard window.location.href (they don't lose HTTP_REFERER like Internet Explorer 8 & lower does)
else {
window.location.href = url;
}
}
Return a generic 400 status code, and then process that client-side.
Or you can keep the 401, and not return the WWW-Authenticate header, which is really what the browser is responding to with the authentication popup. If the WWW-Authenticate header is missing, then the browser won't prompt for credentials.
If you're doing this with more than one module and want to have more control over versions, you should look into having your own private npm registry.
This way you can npm publish your modules to your private npm registry and use package.json entries the same way you would for public modules.
The only way that a Class can be unloaded is if the Classloader used is garbage collected. This means, references to every single class and to the classloader itself need to go the way of the dodo.
One possible solution to your problem is to have a Classloader for every jar file, and a Classloader for each of the AppServers that delegates the actual loading of classes to specific Jar classloaders. That way, you can point to different versions of the jar file for every App server.
This is not trivial, though. The OSGi platform strives to do just this, as each bundle has a different classloader and dependencies are resolved by the platform. Maybe a good solution would be to take a look at it.
If you don't want to use OSGI, one possible implementation could be to use one instance of JarClassloader class for every JAR file.
And create a new, MultiClassloader class that extends Classloader. This class internally would have an array (or List) of JarClassloaders, and in the defineClass() method would iterate through all the internal classloaders until a definition can be found, or a NoClassDefFoundException is thrown. A couple of accessor methods can be provided to add new JarClassloaders to the class. There is several possible implementations on the net for a MultiClassLoader, so you might not even need to write your own.
If you instanciate a MultiClassloader for every connection to the server, in principle it is possible that every server uses a different version of the same class.
I've used the MultiClassloader idea in a project, where classes that contained user-defined scripts had to be loaded and unloaded from memory and it worked quite well.
Rather than abusing plot
or annotate
, which will be inefficient for many lines, you can use matplotlib.collections.LineCollection
:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
np.random.seed(5)
x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
plt.plot(x, y, "o")
# Takes list of lines, where each line is a sequence of coordinates
l1 = [(70, 100), (70, 250)]
l2 = [(70, 90), (90, 200)]
lc = LineCollection([l1, l2], color=["k","blue"], lw=2)
plt.gca().add_collection(lc)
plt.show()
It takes a list of lines [l1, l2, ...]
, where each line is a sequence of N coordinates (N can be more than two).
The standard formatting keywords are available, accepting either a single value, in which case the value applies to every line, or a sequence of M values
, in which case the value for the ith line is values[i % M]
.
This is the one. The session will last for 1440 seconds (24 minutes).
session.gc_maxlifetime 1440 1440
Just if someone is having this issue and hadn't done list[index, sub-index]
, you could be having the problem because you're missing a comma between two arrays in an array of arrays (It happened to me).
Delete generated R package from your referenced library. Sometimes Clean and Rebuild doesn't remove old R generated files.
Change submit button:
<input id="submitButtonId" type="submit" value="Delete" />
With normal button:
<input id="submitButtonId" type="button" value="Delete" />
Then use click function:
$("#submitButtonId").click(function () {
$('#submitButtonId').prop('disabled', true);
$('#myForm').submit();
});
And remember re-enable button when is necesary:
$('#submitButtonId').prop('disabled', false);
One should definitely prefer the solutions already posted, but since no one mentioned this solution yet, I think it is worth mentioning for completeness.
The @classmethod
approach can be modified to provide an alternative constructor which does not invoke the default constructor (__init__
). Instead, an instance is created using __new__
.
This could be used if the type of initialization cannot be selected based on the type of the constructor argument, and the constructors do not share code.
Example:
class MyClass(set):
def __init__(self, filename):
self._value = load_from_file(filename)
@classmethod
def from_somewhere(cls, somename):
obj = cls.__new__(cls) # Does not call __init__
super(MyClass, obj).__init__() # Don't forget to call any polymorphic base class initializers
obj._value = load_from_somewhere(somename)
return obj
Selected answer throws exceptions, and the answer from Carlos Toledo applies filtering after retrieving all values from the database.
The following one runs a single round-trip and reads a single value, using any possible indexes, without an exception.
int maxAge = _dbContext.Persons
.OrderByDescending(p => p.Age)
.Select(p => p.Age)
.FirstOrDefault();
By example:
# select distinct code from Platform where id in ( select platform__id from Build where product=p)
pl_ids = Build.objects.values('platform__id').filter(product=p)
platforms = Platform.objects.values_list('code', flat=True).filter(id__in=pl_ids).distinct('code')
platforms = list(platforms) if platforms else []
As many have already told you:
mainList.get(3);
Be sure to check the ArrayList Javadoc.
Also, be careful with the arrays indices: in Java, the first element is at index 0
. So if you are trying to get the third element, your solution would be mainList.get(2);
To stop a for
loop early in JavaScript, you use break
:
var remSize = [],
szString,
remData,
remIndex,
i;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remIndex = -1; // Set a default if we don't find it
for (i = 0; i < remSize.length; i++) {
// I'm looking for the index i, when the condition is true
if (remSize[i].size === remData.size) {
remIndex = i;
break; // <=== breaks out of the loop early
}
}
If you're in an ES2015 (aka ES6) environment, for this specific use case, you can use Array#findIndex
(to find the entry's index) or Array#find
(to find the entry itself), both of which can be shimmed/polyfilled:
var remSize = [],
szString,
remData,
remIndex;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remIndex = remSize.findIndex(function(entry) {
return entry.size === remData.size;
});
Array#find
:
var remSize = [],
szString,
remData,
remEntry;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remEntry = remSize.find(function(entry) {
return entry.size === remData.size;
});
Array#findIndex
stops the first time the callback returns a truthy value, returning the index for that call to the callback; it returns -1
if the callback never returns a truthy value. Array#find
also stops when it finds what you're looking for, but it returns the entry, not its index (or undefined
if the callback never returns a truthy value).
If you're using an ES5-compatible environment (or an ES5 shim), you can use the new some
function on arrays, which calls a callback until the callback returns a truthy value:
var remSize = [],
szString,
remData,
remIndex;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remIndex = -1; // <== Set a default if we don't find it
remSize.some(function(entry, index) {
if (entry.size === remData.size) {
remIndex = index;
return true; // <== Equivalent of break for `Array#some`
}
});
If you're using jQuery, you can use jQuery.each
to loop through an array; that would look like this:
var remSize = [],
szString,
remData,
remIndex;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remIndex = -1; // <== Set a default if we don't find it
jQuery.each(remSize, function(index, entry) {
if (entry.size === remData.size) {
remIndex = index;
return false; // <== Equivalent of break for jQuery.each
}
});
FYI, the reason why RaphaelJS doesn't work on android is that android webkit (unlike iPhone webkit) doesn't support SVG at this time. Google has only recently come to the conclusion that SVG support an android is a good idea, so it won't be available yet for some time.
Opaque will cause less system strain since 'transparent' will still attempt to apply alpha. The reason you see transparent used instead is because most web authors don't pay attention to detail (ie, just copy-pasted some embed code they found).
BTW, you are correct about it being undocumented. The best I've ever seen is a blog by a guy who claims to have talked to a Macromedia developer about it. Unfortunaetly I can't find the link.
EDIT: I think it was this one: http://www.communitymx.com/content/article.cfm?cid=e5141
Or also you can do something like this.
<div style="background=#aeaeae; float: right">
</div>
We can add any CSS inside the style attribute of HTML tags.
I changed the TextView's color to blue by using for example:
android:textColor="#3399FF"
in the xml file. How to make it underlined is explained here.
Then use its onClick property to specify a method (I'm guessing you could call setOnClickListener(this)
as another way), e.g.:
myTextView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
doSomething();
}
});
In that method, I can do whatever I want as normal, such as launch an intent. Note that you still have to do the normal myTextView.setMovementMethod(LinkMovementMethod.getInstance());
thing, like in your acitivity's onCreate() method.
In my case, I'm producing ms office file like word
or excel
, I run Win+R
and execute dcomcnfg
, in the DCOM Config, besides select OFFICE related name item (such as name contains Excel
or Word
or Office
) and Open the properties, select Identity tab and select the interactive user.
as this answer,
My error message show CLSID {000209FF-0000-0000-C000-000000000046}
, so I have to try to find this specific CLSID in DCOM Config, and it does exsits, and I select it and follow same step set the interactive user
, then it works.
One liner with .apply()
method is following:
df['color'] = df['Set'].apply(lambda set_: 'green' if set_=='Z' else 'red')
After that, df
data frame looks like this:
>>> print(df)
Type Set color
0 A Z green
1 B Z green
2 B X red
3 C Y red
Make sure to enable the use of shortcodes in text widgets.
// To enable the use, add this in your *functions.php* file:
add_filter( 'widget_text', 'do_shortcode' );
// and then you can use it in any PHP file:
<?php echo do_shortcode('[YOUR-SHORTCODE-NAME/TAG]'); ?>
Check the documentation for more.
It doesn't seem possible with SQL Server 2008 alone. You're going to need a third-party tool's help.
It will help you make your .bak act like a live database:
With the release of TypeScript 3.7, optional chaining (the ?
operator) is now officially available.
As such, you can simplify your expression to the following:
const data = change?.after?.data();
You may read more about it from that version's release notes, which cover other interesting features released on that version.
Run the following to install the latest stable release of TypeScript.
npm install typescript
That being said, Optional Chaining can be used alongside Nullish Coalescing to provide a fallback value when dealing with null
or undefined
values
const data = change?.after?.data() ?? someOtherData();
If you want to delete one item
wishlist = Wishlist.objects.get(id = 20)
wishlist.delete()
If you want to delete all items in Wishlist for example
Wishlist.objects.all().delete()
If you have WL server installed, pick it up from under
\Oracle\Middleware\wlserver_10.3\server\lib\mysql-connector-java-commercial-5.1.17-bin.jar
Otherwise, download it from:
http://www.java2s.com/Code/JarDownload/mysql/mysql-connector-java-5.1.17-bin.jar.zip
As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:
var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da
For Node.js v5.11.1 and below
Construct a new Buffer
and pass 'base64'
as the second argument:
var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da
If you want to be clean, you can check whether from
exists :
if (typeof Buffer.from === "function") {
// Node 5.10+
buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
// older Node versions, now deprecated
buf = new Buffer(b64string, 'base64'); // Ta-da
}
<tr>
s themselves are very hard to access with CSS, try tr:hover td {background:#000}
In newer version of windows the Certuil has [CertificateStoreName] where we can give the store name. In earlier version windows this was not possible.
Installing *.pfx certificate: certutil -f -p "" -enterprise -importpfx root ""
Installing *.cer certificate: certutil -addstore -enterprise -f -v root ""
For more details below command can be executed in windows cmd. C:>certutil -importpfx -? Usage: CertUtil [Options] -importPFX [CertificateStoreName] PFXFile [Modifiers]
VisualVm does not come with Apple JDK. You can use VisualVM Mac Application bundle(dmg) as a separate application, to compensate for that.
If you are talking about AjaxTabControlExtender then set TabIndex of every tabs and set Visible property True/False according to your need.
myTab.Tabs[1].Visible=true/false;
A few points:
1) "DataBind()" is only for web apps (not windows apps).
2) Your code looks very 'JAVAish' (not a bad thing, just an observation).
Try this:
mnuActionLanguage.ComboBox.DataSource = languages;
If that doesn't work... then I'm assuming that your datasource is being stepped on somewhere else in the code.
i got solution what you are getting as per imp help=y
it is mentioned that imp is only valid for TRANSPORT_TABLESPACE
as below:
Keyword Description (Default) Keyword Description (Default)
--------------------------------------------------------------------------
USERID username/password FULL import entire file (N)
BUFFER size of data buffer FROMUSER list of owner usernames
FILE input files (EXPDAT.DMP) TOUSER list of usernames
SHOW just list file contents (N) TABLES list of table names
IGNORE ignore create errors (N) RECORDLENGTH length of IO record
GRANTS import grants (Y) INCTYPE incremental import type
INDEXES import indexes (Y) COMMIT commit array insert (N)
ROWS import data rows (Y) PARFILE parameter filename
LOG log file of screen output CONSTRAINTS import constraints (Y)
DESTROY overwrite tablespace data file (N)
INDEXFILE write table/index info to specified file
SKIP_UNUSABLE_INDEXES skip maintenance of unusable indexes (N)
FEEDBACK display progress every x rows(0)
TOID_NOVALIDATE skip validation of specified type ids
FILESIZE maximum size of each dump file
STATISTICS import precomputed statistics (always)
RESUMABLE suspend when a space related error is encountered(N)
RESUMABLE_NAME text string used to identify resumable statement
RESUMABLE_TIMEOUT wait time for RESUMABLE
COMPILE compile procedures, packages, and functions (Y)
STREAMS_CONFIGURATION import streams general metadata (Y)
STREAMS_INSTANTIATION import streams instantiation metadata (N)
DATA_ONLY import only data (N)
The following keywords only apply to transportable tablespaces
TRANSPORT_TABLESPACE import transportable tablespace metadata (N)
TABLESPACES tablespaces to be transported into database
DATAFILES datafiles to be transported into database
TTS_OWNERS users that own data in the transportable tablespace set
So, Please create table space for your user:
CREATE TABLESPACE <tablespace name> DATAFILE <path to save, example: 'C:\ORACLEXE\APP\ORACLE\ORADATA\XE\ABC.dbf'> SIZE 100M AUTOEXTEND ON NEXT 100M MAXSIZE 10G EXTENT MANAGEMENT LOCAL UNIFORM SIZE 1M;
import matplotlib.pyplot as plt
from matplotlib.dates import date2num
import datetime
x = [
datetime.datetime(2011, 1, 4, 0, 0),
datetime.datetime(2011, 1, 5, 0, 0),
datetime.datetime(2011, 1, 6, 0, 0)
]
x = date2num(x)
y = [4, 9, 2]
z = [1, 2, 3]
k = [11, 12, 13]
ax = plt.subplot(111)
ax.bar(x-0.2, y, width=0.2, color='b', align='center')
ax.bar(x, z, width=0.2, color='g', align='center')
ax.bar(x+0.2, k, width=0.2, color='r', align='center')
ax.xaxis_date()
plt.show()
I don't know what's the "y values are also overlapping" means, does the following code solve your problem?
ax = plt.subplot(111)
w = 0.3
ax.bar(x-w, y, width=w, color='b', align='center')
ax.bar(x, z, width=w, color='g', align='center')
ax.bar(x+w, k, width=w, color='r', align='center')
ax.xaxis_date()
ax.autoscale(tight=True)
plt.show()
This may be a silly solution, but I was looking for a solution to this problem and got lazy.
Anyway, using input class="btn..." ... instead of button and padding the value= attribute with spaces so that they are all the same width works pretty well.
eg :
<input type="submit" class="btn btn-primary" value=" Calculate "/>
<input type="reset" class="btn btn-primary"value=" Reset "/>
I haven't been using bootstrap all that long, and maybe there is a good reason not to use this approach, but thought I might as well share
Try to add it to PATH:
PATH=$PATH:/usr/pgsql-9.1/bin/ ./pip install psycopg2
To avoid reinit(affect performance) of prefix
use TextUtils.isEmpty:
String prefix = "";
for (String item : list) {
sb.append(prefix);
if (TextUtils.isEmpty(prefix))
prefix = ",";
sb.append(item);
}
This has served me well for a while now. It prints error or warning messages in red, one line per parameter, and allows an optional exit code.
# Custom errors
EX_UNKNOWN=1
warning()
{
# Output warning messages
# Color the output red if it's an interactive terminal
# @param $1...: Messages
test -t 1 && tput setf 4
printf '%s\n' "$@" >&2
test -t 1 && tput sgr0 # Reset terminal
true
}
error()
{
# Output error messages with optional exit code
# @param $1...: Messages
# @param $N: Exit code (optional)
messages=( "$@" )
# If the last parameter is a number, it's not part of the messages
last_parameter="${messages[@]: -1}"
if [[ "$last_parameter" =~ ^[0-9]*$ ]]
then
exit_code=$last_parameter
unset messages[$((${#messages[@]} - 1))]
fi
warning "${messages[@]}"
exit ${exit_code:-$EX_UNKNOWN}
}
This snippet is straight from Stroustrup's The C++ Programming Language (4th Edition), §40.7; it requires C++11:
#include <functional>
#include <random>
class Rand_double
{
public:
Rand_double(double low, double high)
:r(std::bind(std::uniform_real_distribution<>(low,high),std::default_random_engine())){}
double operator()(){ return r(); }
private:
std::function<double()> r;
};
#include <iostream>
int main() {
// create the random number generator:
Rand_double rd{0,0.5};
// print 10 random number between 0 and 0.5
for (int i=0;i<10;++i){
std::cout << rd() << ' ';
}
return 0;
}
You could convert the dataframe to be a single column with stack
(this changes the shape from 5x3 to 15x1) and then take the standard deviation:
df.stack().std() # pandas default degrees of freedom is one
Alternatively, you can use values
to convert from a pandas dataframe to a numpy array before taking the standard deviation:
df.values.std(ddof=1) # numpy default degrees of freedom is zero
Unlike pandas, numpy will give the standard deviation of the entire array by default, so there is no need to reshape before taking the standard deviation.
A couple of additional notes:
The numpy approach here is a bit faster than the pandas one, which is generally true when you have the option to accomplish the same thing with either numpy or pandas. The speed difference will depend on the size of your data, but numpy was roughly 10x faster when I tested a few different sized dataframes on my laptop (numpy version 1.15.4 and pandas version 0.23.4).
The numpy and pandas approaches here will not give exactly the same answers, but will be extremely close (identical at several digits of precision). The discrepancy is due to slight differences in implementation behind the scenes that affect how the floating point values get rounded.
For finding generic type of one field:
((Class)((ParameterizedType)field.getGenericType()).getActualTypeArguments()[0]).getSimpleName()
var obj = {
'key1':'value',
'2':'value',
'key 1':'value'
}
console.log(obj.key1)
console.log(obj['key1'])
console.log(obj['2'])
console.log(obj['key 1'])
// will not work
console.log(obj.2)
Edit:
"I'm specifically looking to target the index, just like the first example - if it's possible."
Actually the 'index' is the key. If you want to store the position of a key you need to create a custom object to handle this.
Just adding an example that worked fine for me:
$sqldb = [string]($sqldir) + '\bin\MySQLInstanceConfig.exe'
$myarg = '-i ConnectionUsage=DSS Port=3311 ServiceName=MySQL RootPassword= ' + $rootpw
Start-Process $sqldb -ArgumentList $myarg
You can create NSAttributedString
NSDictionary *attributes = @{ NSForegroundColorAttributeName : [UIColor redColor] };
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:@"My Color String" attributes:attrs];
OR NSMutableAttributedString
to apply custom attributes with Ranges.
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@", methodPrefix, method] attributes: @{ NSFontAttributeName : FONT_MYRIADPRO(48) }];
[attributedString addAttribute:NSFontAttributeName value:FONT_MYRIADPRO_SEMIBOLD(48) range:NSMakeRange(methodPrefix.length, method.length)];
Available Attributes: NSAttributedStringKey
UPDATE:
let message: String = greeting + someMessage
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 2.0
// Note: UIFont(appFontFamily:ofSize:) is extended init.
let regularAttributes: [NSAttributedString.Key : Any] = [.font : UIFont(appFontFamily: .regular, ofSize: 15)!, .paragraphStyle : paragraphStyle]
let boldAttributes = [NSAttributedString.Key.font : UIFont(appFontFamily: .semiBold, ofSize: 15)!]
let mutableString = NSMutableAttributedString(string: message, attributes: regularAttributes)
mutableString.addAttributes(boldAttributes, range: NSMakeRange(0, greeting.count))
Not a big deal, but most regex engines support the POSIX character classes, and there's [:xdigit:]
for matching hex characters, which is simpler than the common 0-9a-fA-F
stuff.
So, the regex as requested (ie. with optional 0x
) is: /(0x)?[[:xdigit:]]+/
In objective-C, go ahead and create a category method off of the UIView class.
- (void)removeAllSubviews
{
for (UIView *subview in self.subviews)
[subview removeFromSuperview];
}
/proc/partitions
will list all the block devices and partitions that the system recognizes. You can then try using file -s <device>
to determine what kind of filesystem is present on the partition, if any.
The one I like is: cd C:
To have linux like feel then do:
ln -s /cygdrive/c/folder ~/folder
and use this like: ~/folder/..
Just list an alternaitve solution here, the Advertising ID:
https://support.google.com/googleplay/android-developer/answer/6048248?hl=en
Copied from the link above:
The advertising ID is a unique, user-resettable ID for advertising, provided by Google Play services. It gives users better controls and provides developers with a simple, standard system to continue to monetize their apps. It enables users to reset their identifier or opt out of personalized ads (formerly known as interest-based ads) within Google Play apps.
The limitations are:
https://support.google.com/googleplay/android-developer/answer/113469?hl=en&rd=1#privacy
You could use setUTCMilliseconds()
var _date = new Date();
_date.setUTCMilliseconds(1270544790922);
Of course, to see the result in logcat, you should set the Log level at least to "Info" (Log level in logcat); otherwise, as it happened to me, you won't see your output.
I know this is a late response but I was facing a similar issue and I managed to solve it by using notifyDataSetChanged()
in the right place.
So my situation was as follows.
I had to update a listview in an action bar tab (fragment) with contents returned from a completely different activity. Initially however, the listview would not reflect any changes. However, when I clicked another tab and then returned to the desired tab,the listview would be updated with the correct content from the other activity. So to solve this I used notifyDataSetChanged()
of the action bar adapter in the code of the activity which had to return the data.
This is the code snippet which I used in the activity.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.action_new_forward:
FragmentTab2.mListAdapter.notifyDataSetChanged();//this updates the adapter in my action bar tab
Intent ina = new Intent(getApplicationContext(), MainActivity.class);
ina.putExtra("stra", values1);
startActivity(ina);// This is the code to start the parent activity of my action bar tab(fragment).
}
}
This activity would return some data to FragmentTab2
and it would directly update my listview in FragmentTab2
.
Hope someone finds this useful!
Visual Studio 2008 does have a designer that allows you to add FK's. Just right-click the table... Table Properties, then go to the "Add Relations" section.
"[1-9][0-9]*|0
"
I'd just use "[0-9]+
" to represent positive whole numbers.
Use a T-SQL IF
:
IF @ABC IS NOT NULL AND @ABC != -1
UPDATE [TABLE_NAME] SET XYZ=@ABC
Take a look at the MSDN docs.
I think you are looking for something like this:
let signUpViewController = SignUpViewController()
present(signUpViewController, animated: true, completion: nil)
If you want full screen of the new page:
present(signUpViewController, animated: true, completion: nil)
Hope this helps :)
Change permanent
conda install python={version}
Change Temporarily
View your environments
run conda info --envs
on your terminal window or an Anconda Prompt
If It doesn't show environment that you want to install
run conda create -n py36 python=3.6 anaconda
for python 3.6 change version as your prefer
Activating an environment (use Anaconda prompt)
run activate envnme
envnme you can find by this commandconda info --envs
as a example when you run conda info --envs
it show
base * C:\Users\DulangaHeshan\Anaconda3
py36 C:\Users\DulangaHeshan\Anaconda3\envs\py36
then run activate py36
to check run python --version
In Windows, it is good practice to deactivate one environment before activating another. https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html?highlight=deactivate%20environment
You can use a simple HTML element <embed src="file.txt">
it loads the external resource and displays it on the screen no js needed
Open the project you want to push in Android Studio.
Click VCS -> Enable version Control Integration -> Git
There doesn't seem to be a way to add a remote through the GUI. So open Git Bash in the root of the project and do git remote add <remote_name> <remote_url>
Now when you do VCS -> Commit changes -> Commit & Push
you should see your remote and everything should work through the GUI.
If you are getting the error: fatal: remote <remote_name> already exists
that means you already added it. To see your remotes do git remote -v
and git remote rm <remote_name>
to remove.
See these pages for details:
http://www.jetbrains.com/idea/webhelp/using-git-integration.html
Comparison of some of the methods based on the result when the character is not an ASCII digit:
char c1 = (char)('0' - 1), c2 = (char)('9' + 1);
Debug.Print($"{c1 & 15}, {c2 & 15}"); // 15, 10
Debug.Print($"{c1 ^ '0'}, {c2 ^ '0'}"); // 31, 10
Debug.Print($"{c1 - '0'}, {c2 - '0'}"); // -1, 10
Debug.Print($"{(uint)c1 - '0'}, {(uint)c2 - '0'}"); // 4294967295, 10
Debug.Print($"{char.GetNumericValue(c1)}, {char.GetNumericValue(c2)}"); // -1, -1
Tortoise SVN on Windows happens to lose sync quite often with the real file status.
In that case try doing an svn cleanup
.
Another thing, it may also depend where your source files are located, different drive, network drive, etc. There's an option in Tortoise to allow icon overlay or not, on remote drives.
Check this out in: TortoiseSVN / Settings / Icon Overlays / Drive types
Four easy steps using terminal for people who uses the default process.. :)
echo $JAVA_HOME
gives you current java home. For eg: /Library/Java/JavaVirtualMachines/jdk1.8.0_191.jdk/Contents/Home/
cd /Library/Java/JavaVirtualMachines/
will take you to the folder where u normally install jdks (It might be different for your machines)
ls
shows you available folders (normally it will have the version numbers, for eg: jdk1.8.0_191.jdk openjdk-11.0.2.jdk
)export JAVA_HOME='/Library/Java/JavaVirtualMachines/openjdk-11.0.2.jdk/Contents/Home'
will change the java home..protected void grdDataListeDetay_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[3].Text != "0")
{
for (int i = 0; i <= e.Row.Cells.Count - 1; i++)
{
e.Row.Cells[i].BackColor = System.Drawing.Color.Beige;
}
}
}
}
Btw, you cannot encrypt with DSA, only sign. Although they are mathematically equivalent (more or less) you cannot use DSA in practice as an encryption scheme, only as a digital signature scheme.
try this Dim Arraystr() as String ={}
You can also use sqlcmd
mode for this (enable this on the "Query" menu in Management Studio).
:setvar dbname "TEST"
CREATE DATABASE $(dbname)
GO
ALTER DATABASE $(dbname) SET COMPATIBILITY_LEVEL = 90
GO
ALTER DATABASE $(dbname) SET RECOVERY SIMPLE
GO
EDIT:
Check this MSDN article to set parameters via the SQLCMD tool.
Since Version 0.7.7 there is a new way to create an aggregated report:
You create a separate 'report' project which collects all the necessary reports (Any goal in the aggregator project is executed before its modules therefore it can't be used).
aggregator pom
|- parent pom
|- module a
|- module b
|- report module
The root pom looks like this (don't forget to add the new report module under modules):
<build>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.8</version>
<executions>
<execution>
<id>prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
The poms from each sub module doesn't need to be changed at all. The pom from the report module looks like this:
<!-- Add all sub modules as dependencies here -->
<dependencies>
<dependency>
<module a>
</dependency>
<dependency>
<module b>
</dependency>
...
<build>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.8</version>
<executions>
<execution>
<id>report-aggregate</id>
<phase>verify</phase>
<goals>
<goal>report-aggregate</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
A full exmple can be found here.
# needed to create data for 1000 fictitious employees for testing code
# code relating to randomly assigning forenames, surnames, and genders
# has been removed as not germaine to the question asked above but FYI
# genders were randomly assigned, forenames/surnames were web scrapped,
# there is no accounting for leap years, and the data stored in mySQL
import random
from datetime import datetime
from datetime import timedelta
for employee in range(1000):
# assign a random date of birth (employees are aged between sixteen and sixty five)
dlt = random.randint(365*16, 365*65)
dob = datetime.today() - timedelta(days=dlt)
# assign a random date of hire sometime between sixteenth birthday and yesterday
doh = datetime.today() - timedelta(days=random.randint(1, dlt-365*16))
print("born {} hired {}".format(dob.strftime("%d-%m-%y"), doh.strftime("%d-%m-%y")))
On January 7th 2019, GitHub announced free and unlimited private repositories for all GitHub users, paying or not. When creating a new repository, you can simply select the Private option.
If you want a big database of real data to play with, you could sign up for the Netflix Prize contest and get access to their data, which is pretty large (a few gigs of entries).
The URL above does not contain the dataset anylonger (october 2016). The wikipedia page about the Netflix Prize reports that a law suit was settled regarding privacy concerns.
height: 100%
gives the element 100% height of its parent container.
height: auto
means the element height will depend upon the height of its children.
Consider these examples:
height: 100%
<div style="height: 50px">
<div id="innerDiv" style="height: 100%">
</div>
</div>
#innerDiv
is going to have height: 50px
height: auto
<div style="height: 50px">
<div id="innerDiv" style="height: auto">
<div id="evenInner" style="height: 10px">
</div>
</div>
</div>
#innerDiv
is going to have height: 10px
For char or short to int, you just need to assign the value.
char ch = 16;
int in = ch;
Same to int64.
long long lo = ch;
All values will be 16.
You can pass as many arguments as you want, separating them by commas:
{{ path('_files_manage', {project: project.id, user: user.id}) }}
You can remove the back button by passing an empty new Container()
as the leading
argument to your AppBar
.
If you find yourself doing this, you probably don't want the user to be able to press the device's back button to get back to the earlier route. Instead of calling pushNamed
, try calling Navigator.pushReplacementNamed
to cause the earlier route to disappear.
The function pushReplacementNamed
will remove the previous route in the backstack and replace it with the new route.
Full code sample for the latter is below.
import 'package:flutter/material.dart';
class LogoutPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Logout Page"),
),
body: new Center(
child: new Text('You have been logged out'),
),
);
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Remove Back Button"),
),
floatingActionButton: new FloatingActionButton(
child: new Icon(Icons.fullscreen_exit),
onPressed: () {
Navigator.pushReplacementNamed(context, "/logout");
},
),
);
}
}
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
home: new MyHomePage(),
routes: {
"/logout": (_) => new LogoutPage(),
},
);
}
}
If you declare the variable "annualRate" like
class Program {
**static double annualRate;**
public static void Main() {
Try it..
Python 2:
import urlparse
url = 'http://foo.appspot.com/abc?def=ghi'
parsed = urlparse.urlparse(url)
print urlparse.parse_qs(parsed.query)['def']
Python 3:
import urllib.parse as urlparse
from urllib.parse import parse_qs
url = 'http://foo.appspot.com/abc?def=ghi'
parsed = urlparse.urlparse(url)
print(parse_qs(parsed.query)['def'])
parse_qs
returns a list of values, so the above code will print ['ghi']
.
This can happen in ES6 if you use the incorrect (older) syntax for static methods:
export default class MyClass
{
constructor()
{
...
}
myMethod()
{
...
}
}
MyClass.someEnum = {Red: 0, Green: 1, Blue: 2}; //works
MyClass.anotherMethod() //or
MyClass.anotherMethod = function()
{
return something; //doesn't work
}
Whereas the correct syntax is:
export default class MyClass
{
constructor()
{
...
}
myMethod()
{
...
}
static anotherMethod()
{
return something; //works
}
}
MyClass.someEnum = {Red: 0, Green: 1, Blue: 2}; //works
This will work in C# 7. As of this writing, it has yet to be released. But if I understand this correctly, this code will work.
switch(message)
{
case Contains("test"):
Console.WriteLine("yes");
break;
case Contains("test2"):
Console.WriteLine("yes for test2");
break;
default:
Console.WriteLine("No matches found!");
}
Source: https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/
am using this simple one
´´´´ class Connect {
public $url;
public $path;
public $username;
public $password;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, "$this->username:$this->password");
//PROPFIND request that lists all requested properties.
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PROPFIND");
$response = curl_exec($ch);
curl_close($ch);
I had almost precisely the same error, and was able to completely fix it simply by running:
gem install bundler
It's possible your bundler installation is corrupt or missing - that's what happened in my case. Note that if the above fails you can try:
sudo gem install bundler
...but generally you can do it without sudo.
I met the same problem even using -ldl
.
Besides this option, source files need to be placed before libraries, see undefined reference to `dlopen'.
You can use the services console, clicking on the left hand side and then selecting the "Connect to another computer" option in the Action menu.
If you wish to use the command line only, you can use
sc \\machine stop <service>
I know this is a year old but I just came across it with the same problem. My problem was that I didn't have a constructor in my implementation file. I think the problem here could be the comment marks at the end of the header file after the #endif...
You have to indent the docstring after the function definition there (line 3, 4):
def print_lol(the_list):
"""this doesn't works"""
print 'Ain't happening'
Indented:
def print_lol(the_list):
"""this works!"""
print 'Aaaand it's happening'
Or you can use #
to comment instead:
def print_lol(the_list):
#this works, too!
print 'Hohoho'
Also, you can see PEP 257 about docstrings.
Hope this helps!
From 6.11. Boolean operations:
In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.
The key phrasing here that I think you are misunderstanding is "interpreted as false" or "interpreted as true". This does not mean that any of those values are identical to True or False, or even equal to True or False.
The expression '/bla/bla/bla'
will be treated as true where a Boolean expression is expected (like in an if
statement), but the expressions '/bla/bla/bla' is True
and '/bla/bla/bla' == True
will evaluate to False for the reasons in Ignacio's answer.