Following is the list of conversion characters that you may use in the printf:
%d – for signed decimal integer
%f – for the floating point
%o – octal number
%c – for a character
%s – a string
%i – use for integer base 10
%u – for unsigned decimal number
%x – hexadecimal number
%% – for writing % (percentage)
%n – for new line = \n
I use pyDev with Eclipse really good, set break points, step into code, view values on any objects and variables, try it.
This is the code that I needed. A defined user control's .show() function doesn't actually show anything. It must first be wrapped into a form like so:
CustomControl customControl = new CustomControl();
Form newForm = new Form();
newForm.Controls.Add(customControl);
newForm.ShowDialog();
I have resolved this issue using below steps
Click on run search this %APPDATA%\NuGet\NuGet.config.
Open the setting and add this http_proxy keyin NuGet.config.
Then you will able install the BouncyCastle.Crypto.dll in your application.
Thank you! Responses are welcome if you help this answer.
On Arch, i fix like this:
sudo ln -s /usr/lib/libncursesw.so.6 /usr/lib/libtinfo.so.6
Download and unpack a JDK archive file (.tar.gz) and add it as a SDK in the 'Project Structure' dialog box ( Ctrl+Alt+Shift+S )
Make sure to set the 'Project language level' as well.
Yes, you could.
This is part of the C++ standard conversion, which falls in Boolean conversion clause:
§ 4.12 Boolean conversions
A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. A prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.
I had this problem too. My advice is look in your server error log file. For me, it was that the top directory for the project was not readable. The error log clearly stated this. A simple
sudo chmod 755 <site_top_folder>
fixed it for me.
document.getElementById("your checkbox id").disabled=true;
You cannot really find the display resolution from a web page. There is a CSS Media Queries statement for it, but it is poorly implemented in most devices and browsers, if at all. However, you do not need to know the resolution of the display, because changing it causes the (pixel) width of the window to change, which can be detected using the methods others have described:
$(window).resize(function() {
// This will execute whenever the window is resized
$(window).height(); // New height
$(window).width(); // New width
});
You can also use CSS Media Queries in browsers that support them to adapt your page's style to various display widths, but you should really be using em
units and percentages and min-width
and max-width
in your CSS if you want a proper flexible layout. Gmail probably uses a combination of all these.
Take a look at Blaze-Persistence Entity Views which works on top of JPA and provides first class DTO support. You can project anything to attributes within Entity Views and it will even reuse existing join nodes for associations if possible.
Here is an example mapping
@EntityView(Order.class)
interface OrderSummary {
Integer getId();
@Mapping("SUM(orderPositions.price * orderPositions.amount * orderPositions.tax)")
BigDecimal getOrderAmount();
@Mapping("COUNT(orderPositions)")
Long getItemCount();
}
Fetching this will generate a JPQL/HQL query similar to this
SELECT
o.id,
SUM(p.price * p.amount * p.tax),
COUNT(p.id)
FROM
Order o
LEFT JOIN
o.orderPositions p
GROUP BY
o.id
Here is a blog post about custom subquery providers which might be interesting to you as well: https://blazebit.com/blog/2017/entity-view-mapping-subqueries.html
To exclude dotfiles in base directory:
scp -r [!.]* server:/path/to/something
[!.]*
is a shell glob that expands to all files in working directory not starting with a dot.
Solution using Google Guava, since I prefer it to Apache Commons-Lang:
/**
* Returns a String with exactly the given length composed entirely of
* the given character.
* @param length the length of the returned string
* @param c the character to fill the String with
*/
public static String stringOfLength(final int length, final char c)
{
return Strings.padEnd("", length, c);
}
This thread was very helpful while I was investigating the subject.
I've modified some of the code available here into a jQuery plugin so it is in a re-usable form, primarily to satisfy my needs but others may appreciate a simpler interface to jumpstart using contenteditable tags.
https://gist.github.com/3410122
Due to its increasing popularity the plugin has been adopted by Makesites.org
Development will continue from here:
Let's suppose that you deal with this 2014[:-/.]06[:-/.]06
or this 06[:-/.]06[:-/.]2014
date format, then you may compare dates this way
var a = '2014.06/07', b = '2014-06.07', c = '07-06/2014', d = '07/06.2014';
parseInt(a.replace(/[:\s\/\.-]/g, '')) == parseInt(b.replace(/[:\s\/\.-]/g, '')); // true
parseInt(c.replace(/[:\s\/\.-]/g, '')) == parseInt(d.replace(/[:\s\/\.-]/g, '')); // true
parseInt(a.replace(/[:\s\/\.-]/g, '')) < parseInt(b.replace(/[:\s\/\.-]/g, '')); // false
parseInt(c.replace(/[:\s\/\.-]/g, '')) > parseInt(d.replace(/[:\s\/\.-]/g, '')); // false
As you can see, we strip separator(s) and then compare integers.
Dim psValue As String = "1,5,12,34,123,12"
psValue = psValue.Substring(0, psValue.LastIndexOf(","))
output:
1,5,12,34,123
step 1: Enter into the MongoDB shell.
mongo
step 2: for the display all the databases.
show dbs;
step 3: for a select database :
use 'databases_name'
step 4: for statistics of your database.
db.stats()
step 5: listing out all the collections(tables).
show collections
step 6:print the data from a particular collection.
db.'collection_name'.find().pretty()
The finite repetition syntax uses {m,n}
in place of star/plus/question mark.
From java.util.regex.Pattern
:
X{n} X, exactly n times
X{n,} X, at least n times
X{n,m} X, at least n but not more than m times
All repetition metacharacter have the same precedence, so just like you may need grouping for *
, +
, and ?
, you may also for {n,m}
.
ha*
matches e.g. "haaaaaaaa"
ha{3}
matches only "haaa"
(ha)*
matches e.g. "hahahahaha"
(ha){3}
matches only "hahaha"
Also, just like *
, +
, and ?
, you can add the ?
and +
reluctant and possessive repetition modifiers respectively.
System.out.println(
"xxxxx".replaceAll("x{2,3}", "[x]")
); "[x][x]"
System.out.println(
"xxxxx".replaceAll("x{2,3}?", "[x]")
); "[x][x]x"
Essentially anywhere a *
is a repetition metacharacter for "zero-or-more", you can use {...}
repetition construct. Note that it's not true the other way around: you can use finite repetition in a lookbehind, but you can't use *
because Java doesn't officially support infinite-length lookbehind.
.*
and .*?
for regexregex{n,}?
== regex{n}
?a{1}b{0,1}
instead of ab?
inspect.getframeinfo and other related functions in inspect
can help:
>>> import inspect
>>> def f1(): f2()
...
>>> def f2():
... curframe = inspect.currentframe()
... calframe = inspect.getouterframes(curframe, 2)
... print('caller name:', calframe[1][3])
...
>>> f1()
caller name: f1
this introspection is intended to help debugging and development; it's not advisable to rely on it for production-functionality purposes.
To run pip in Python 3.x, just follow the instructions on Python's page: Installing Python Modules.
python -m pip install SomePackage
Note that this is run from the command line and not the python shell (the reason for syntax error in the original question).
In addition to the above, it's interesting to note that you can get exceptions if you use IQueryable
instead of IEnumerable
:
The following works fine if products
is an IEnumerable
:
products.Skip(-4);
However if products
is an IQueryable
and it's trying to access records from a DB table, then you'll get this error:
The offset specified in a OFFSET clause may not be negative.
This is because the following query was constructed:
SELECT [p].[ProductId]
FROM [Products] AS [p]
ORDER BY (SELECT 1)
OFFSET @__p_0 ROWS
and OFFSET can't have a negative value.
How about something like this :
string url = "http://www.example.com/aaa/bbb.jpg";
Uri uri = new Uri(url);
string path_Query = uri.PathAndQuery;
string extension = Path.GetExtension(path_Query);
path_Query = path_Query.Replace(extension, string.Empty);// This will remove extension
The Git Parable explains how a typical DVCS gets created and why their creators did what they did. Also, you might want to take a look at Git for Computer Scientist; it explains what each type of object in Git does, including branches and tags.
If your goal is to initialize the static variable in your header file (instead of a *.cpp file, which you may want if you are sticking to a "header only" idiom), then you can work around the initialization problem by using a template. Templated static variables can be initialized in a header, without causing multiple symbols to be defined.
See here for an example:
Use the -j
option:
-j Store just the name of a saved file (junk the path), and do not
store directory names. By default, zip will store the full path
(relative to the current path).
ip route get 8.8.8.8| grep src| sed 's/.*src \(.* \)/\1/g'|cut -f1 -d ' '
If you are running PHP on Apache then you can use the enviroment variable called DOCUMENT_ROOT
. This means that the path is dynamic, and can be moved between servers without messing about with the code.
<?php
$fileLocation = getenv("DOCUMENT_ROOT") . "/myfile.txt";
$file = fopen($fileLocation,"w");
$content = "Your text here";
fwrite($file,$content);
fclose($file);
?>
Sometimes it is very convenient to use stringstream to convert between strings and other numerical types. The usage of stringstream
is similar to the usage of iostream
, so it is not a burden to learn.
Stringstreams can be used to both read strings and write data into strings. It mainly functions with a string buffer, but without a real I/O channel.
The basic member functions of stringstream class are
str()
, which returns the contents of its buffer in string type.
str(string)
, which set the contents of the buffer to the string argument.
Here is an example of how to use string streams.
ostringstream os;
os << "dec: " << 15 << " hex: " << std::hex << 15 << endl;
cout << os.str() << endl;
The result is dec: 15 hex: f
.
istringstream
is of more or less the same usage.
To summarize, stringstream is a convenient way to manipulate strings like an independent I/O device.
FYI, the inheritance relationships between the classes are:
Try
location ~ ^/(first/location|second/location)/ {
...
}
The ~
means to use a regular expression for the url. The ^
means to check from the first character. This will look for a /
followed by either of the locations and then another /
.
A simple way of doing this is via nargin
(N arguments in). The downside is you have to make sure that your argument list and the nargin checks match.
It is worth remembering that all inputs are optional, but the functions will exit with an error if it calls a variable which is not set. The following example sets defaults for b
and c
. Will exit if a
is not present.
function [ output_args ] = input_example( a, b, c )
if nargin < 1
error('input_example : a is a required input')
end
if nargin < 2
b = 20
end
if nargin < 3
c = 30
end
end
In below code i have done operation of sum and subtraction: because of using JavaScript if you want to call function, then you have to put your below code outside of document.ready(function{ });
and outside the script end tag.
I have taken one another script tag for this operation.And put below code between script starting tag // your code // script ending tag.
function operation()
{
var txtFirstNumberValue = parseInt(document.getElementById('basic').value);
var txtSecondNumberValue =parseInt(document.getElementById('hra').value);
var txtThirdNumberValue =parseInt(document.getElementById('transport').value);
var txtFourthNumberValue =parseInt(document.getElementById('pt').value);
var txtFiveNumberValue = parseInt(document.getElementById('pf').value);
if (txtFirstNumberValue == "")
txtFirstNumberValue = 0;
if (txtSecondNumberValue == "")
txtSecondNumberValue = 0;
if (txtThirdNumberValue == "")
txtThirdNumberValue = 0;
if (txtFourthNumberValue == "")
txtFourthNumberValue = 0;
if (txtFiveNumberValue == "")
txtFiveNumberValue = 0;
var result = ((txtFirstNumberValue + txtSecondNumberValue +
txtThirdNumberValue) - (txtFourthNumberValue + txtFiveNumberValue));
if (!isNaN(result)) {
document.getElementById('total').value = result;
}
}
And put onkeyup="operation();"
inside all 5 textboxes in your html form.
This code running in both Firefox and Chrome.
As I mentioned in my comment, I think the reason why this doesn't work is because the compiler can't infer types based on generic constraints.
Below is an alternative implementation that will compile. I've revised the IAccess interface to only have the T
generic type parameter.
interface ISignatur<T>
{
Type Type { get; }
}
interface IAccess<T>
{
ISignatur<T> Signature { get; }
T Value { get; set; }
}
class Signatur : ISignatur<bool>
{
public Type Type
{
get { return typeof(bool); }
}
}
class ServiceGate
{
public IAccess<T> Get<T>(ISignatur<T> sig)
{
throw new NotImplementedException();
}
}
static class Test
{
static void Main()
{
ServiceGate service = new ServiceGate();
var access = service.Get(new Signatur());
}
}
It seems there are direct links and anyone could get it with a download manager.
References from here
The Easiest way to do it is to have good site structure and write it as a constant.
DEFINE("BACK_ROOT","/var/www/");
RABL is probably the nicest solution to this that I've seen if you're looking for a cleaner alternative to ERb syntax. json_builder and argonaut, which are other solutions, both seem somewhat outdated and won't work with Rails 3.1 without some patching.
RABL is available via a gem or check out the GitHub repository; good examples too
A bit late to the game but if I'm understanding your needs correctly this will help people with the same issue.
Two solutions with the same first step: First navigate to the location you keep your scripts in and copy the filepath to that directory.
First Solution:
You can now use any of your scripts as if you were already that folder.
Second Solution: (can easily be paired with the first for extra usefulness)
On your desktop create a batch file with the following content.
@echo off
cmd /k cd "C:\your\file\path"
This will open a command window like what you tried to do.
For tons of info on windows commands check here: http://ss64.com/nt/
You can try: right click on the project and then click clean. After this run the project.
It works for me.
Elasticsearch supports this now out of the box:
https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
How to get append input field value as json like
temp:[
{
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
},
{
test:'test 2',
testData: [
{testName: 'do1',testId:''}
],
testRcd:'value'
}
],
You can also do the following. in your form class def:
max_number = forms.ChoiceField(widget = forms.Select(),
choices = ([('1','1'), ('2','2'),('3','3'), ]), initial='3', required = True,)
then when calling the form in your view you can dynamically set both initial choices and choice list.
yourFormInstance = YourFormClass()
yourFormInstance.fields['max_number'].choices = [(1,1),(2,2),(3,3)]
yourFormInstance.fields['max_number'].initial = [1]
Note: the initial values has to be a list and the choices has to be 2-tuples, in my example above i have a list of 2-tuples. Hope this helps.
Finding difference by index. Assuming df1 is a subset of df2 and the indexes are carried forward when subsetting
df1.loc[set(df1.index).symmetric_difference(set(df2.index))].dropna()
# Example
df1 = pd.DataFrame({"gender":np.random.choice(['m','f'],size=5), "subject":np.random.choice(["bio","phy","chem"],size=5)}, index = [1,2,3,4,5])
df2 = df1.loc[[1,3,5]]
df1
gender subject
1 f bio
2 m chem
3 f phy
4 m bio
5 f bio
df2
gender subject
1 f bio
3 f phy
5 f bio
df3 = df1.loc[set(df1.index).symmetric_difference(set(df2.index))].dropna()
df3
gender subject
2 m chem
4 m bio
But from what I see you have quite a simple error in syntax
<p th:text="${bean.field} + '!' + ${bean.field}">Static content</p>
the correct syntax would look like
<p th:text="${bean.field + '!' + bean.field}">Static content</p>
As a matter of fact, the syntax th:text="'static part' + ${bean.field}"
is equal to th:text="${'static part' + bean.field}"
.
Try it out. Even though this is probably kind of useless now after 6 months.
the problem can because of MVC MW.you must set formatterType in MVC options:
services.AddMvc(options =>
{
options.UseCustomStringModelBinder();
options.AllowEmptyInputInBodyModelBinding = true;
foreach (var formatter in options.InputFormatters)
{
if (formatter.GetType() == typeof(SystemTextJsonInputFormatter))
((SystemTextJsonInputFormatter)formatter).SupportedMediaTypes.Add(
Microsoft.Net.Http.Headers.MediaTypeHeaderValue.Parse("text/plain"));
}
}).AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
});
You should know that it is not possible to directly run a DDL statement like you do for DML from a PL/SQL block because PL/SQL does not support late binding directly it only support compile time binding which is fine for DML. hence to overcome this type of problem oracle has provided a dynamic SQL approach which can be used to execute the DDL statements.The dynamic sql approach is about parsing and binding of sql string at the runtime. Also you should rememder that DDL statements are by default auto commit hence you should be careful about any of the DDL statement using the dynamic SQL approach incase if you have some DML (which needs to be commited explicitly using TCL) before executing the DDL in the stored proc/function.
You can use any of the following dynamic sql approach to execute a DDL statement from a pl/sql block.
1) Execute immediate
2) DBMS_SQL package
3) DBMS_UTILITY.EXEC_DDL_STATEMENT (parse_string IN VARCHAR2);
Hope this answers your question with explanation.
you don't need to set the width of header in css, just put the background image as center using this code:
background: url("images/logo.png") no-repeat top center;
or you can just use img
tag and put align="center"
in the div
Have you considered using something like Quartz Scheduler? This library has a mechanism for scheduling tasks to run at a set period of time every day using a cron like expression (take a look at CronScheduleBuilder
).
Some example code (not tested):
public class GetDatabaseJob implements InterruptableJob
{
public void execute(JobExecutionContext arg0) throws JobExecutionException
{
getFromDatabase();
}
}
public class Example
{
public static void main(String[] args)
{
JobDetails job = JobBuilder.newJob(GetDatabaseJob.class);
// Schedule to run at 5 AM every day
ScheduleBuilder scheduleBuilder =
CronScheduleBuilder.cronSchedule("0 0 5 * * ?");
Trigger trigger = TriggerBuilder.newTrigger().
withSchedule(scheduleBuilder).build();
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.scheduleJob(job, trigger);
scheduler.start();
}
}
There's a bit more work upfront, and you may need to rewrite your job execution code, but it should give you more control over how you want you job to run. Also it would be easier to change the schedule should you need to.
Late answer, but the accepted answer didn't work for me.
If you set both start and end dates manually (not using curdate()
), make sure to specify the hours, minutes and seconds (2019-12-02 23:59:59
) on the end date or you won't get any results from that day, i.e.:
This WILL include records from 2019-12-02
:
SELECT *SOMEFIELDS* FROM *YOURTABLE* where *YOURDATEFIELD* between '2019-12-01' and '2019-12-02 23:59:59'
This WON'T include records from 2019-12-02
:
SELECT *SOMEFIELDS* FROM *YOURTABLE* where *YOURDATEFIELD* between '2019-12-01' and '2019-12-02'
d
stands for Declaration Files:
When a TypeScript script gets compiled there is an option to generate a declaration file (with the extension .d.ts) that functions as an interface to the components in the compiled JavaScript. In the process the compiler strips away all function and method bodies and preserves only the signatures of the types that are exported. The resulting declaration file can then be used to describe the exported virtual TypeScript types of a JavaScript library or module when a third-party developer consumes it from TypeScript.
The concept of declaration files is analogous to the concept of header file found in C/C++.
declare module arithmetics {
add(left: number, right: number): number;
subtract(left: number, right: number): number;
multiply(left: number, right: number): number;
divide(left: number, right: number): number;
}
Type declaration files can be written by hand for existing JavaScript libraries, as has been done for jQuery and Node.js.
Large collections of declaration files for popular JavaScript libraries are hosted on GitHub in DefinitelyTyped and the Typings Registry. A command-line utility called typings is provided to help search and install declaration files from the repositories.
When you want to run an executable file from the Command prompt, (cmd.exe), or a batch file, it will:
%PATH%
environment variable for the executable file.If the file isn't found in either of those options you will need to either:
%PATH%
by apending it, (recommended only with extreme caution).You can see which locations are specified in %PATH%
from the Command prompt, Echo %Path%
.
Because of your reported error we can assume that Mobile.exe
is not in the current directory or in a location specified within the %Path%
variable, so you need to use 1.
, 2.
or 3.
.
Examples for 1.
C:\directory_path_without_spaces\My-App\Mobile.exe
or:
"C:\directory path with spaces\My-App\Mobile.exe"
Alternatively you may try:
Start C:\directory_path_without_spaces\My-App\Mobile.exe
or
Start "" "C:\directory path with spaces\My-App\Mobile.exe"
Where ""
is an empty title, (you can optionally add a string between those doublequotes).
Examples for 2.
CD /D C:\directory_path_without_spaces\My-App
Mobile.exe
or
CD /D "C:\directory path with spaces\My-App"
Mobile.exe
You could also use the /D
option with Start
to change the working directory for the executable to be run by the start command
Start /D C:\directory_path_without_spaces\My-App Mobile.exe
or
Start "" /D "C:\directory path with spaces\My-App" Mobile.exe
To rotate a DIV we can add some CSS that, well, rotates the DIV using CSS transform rotate.
To toggle the rotation we can keep a flag, a simple variable with a boolean value that tells us what way to rotate.
var rotated = false;
document.getElementById('button').onclick = function() {
var div = document.getElementById('div'),
deg = rotated ? 0 : 66;
div.style.webkitTransform = 'rotate('+deg+'deg)';
div.style.mozTransform = 'rotate('+deg+'deg)';
div.style.msTransform = 'rotate('+deg+'deg)';
div.style.oTransform = 'rotate('+deg+'deg)';
div.style.transform = 'rotate('+deg+'deg)';
rotated = !rotated;
}
var rotated = false;_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
var div = document.getElementById('div'),_x000D_
deg = rotated ? 0 : 66;_x000D_
_x000D_
div.style.webkitTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.mozTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.msTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.oTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.transform = 'rotate('+deg+'deg)'; _x000D_
_x000D_
rotated = !rotated;_x000D_
}
_x000D_
#div {_x000D_
position:relative; _x000D_
height: 200px; _x000D_
width: 200px; _x000D_
margin: 30px;_x000D_
background: red;_x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
To add some animation to the rotation all we have to do is add CSS transitions
div {
-webkit-transition: all 0.5s ease-in-out;
-moz-transition: all 0.5s ease-in-out;
-o-transition: all 0.5s ease-in-out;
transition: all 0.5s ease-in-out;
}
var rotated = false;_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
var div = document.getElementById('div'),_x000D_
deg = rotated ? 0 : 66;_x000D_
_x000D_
div.style.webkitTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.mozTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.msTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.oTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.transform = 'rotate('+deg+'deg)'; _x000D_
_x000D_
rotated = !rotated;_x000D_
}
_x000D_
#div {_x000D_
position:relative; _x000D_
height: 200px; _x000D_
width: 200px; _x000D_
margin: 30px;_x000D_
background: red;_x000D_
-webkit-transition: all 0.5s ease-in-out;_x000D_
-moz-transition: all 0.5s ease-in-out;_x000D_
-o-transition: all 0.5s ease-in-out;_x000D_
transition: all 0.5s ease-in-out;_x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
Another way to do it is using classes, and setting all the styles in a stylesheet, thus keeping them out of the javascript
document.getElementById('button').onclick = function() {
document.getElementById('div').classList.toggle('rotated');
}
document.getElementById('button').onclick = function() {_x000D_
document.getElementById('div').classList.toggle('rotated');_x000D_
}
_x000D_
#div {_x000D_
position:relative; _x000D_
height: 200px; _x000D_
width: 200px; _x000D_
margin: 30px;_x000D_
background: red;_x000D_
-webkit-transition: all 0.5s ease-in-out;_x000D_
-moz-transition: all 0.5s ease-in-out;_x000D_
-o-transition: all 0.5s ease-in-out;_x000D_
transition: all 0.5s ease-in-out;_x000D_
}_x000D_
_x000D_
#div.rotated {_x000D_
-webkit-transform : rotate(66deg); _x000D_
-moz-transform : rotate(66deg); _x000D_
-ms-transform : rotate(66deg); _x000D_
-o-transform : rotate(66deg); _x000D_
transform : rotate(66deg); _x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
This is just Christopher Parker's answer adapted to use the new1 classes from Java 8:
final DateTimeFormatter OLD_FORMATTER = DateTimeFormatter.ofPattern("dd/MM/yyyy");
final DateTimeFormatter NEW_FORMATTER = DateTimeFormatter.ofPattern("yyyy/MM/dd");
String oldString = "26/07/2017";
LocalDate date = LocalDate.parse(oldString, OLD_FORMATTER);
String newString = date.format(NEW_FORMATTER);
1 well, not that new anymore, Java 9 should be released soon.
After removing/deleting the rm ~/.ssh/known_hosts
, my issue was fixed
Swift 3, and now Swift 4, have replaced many "stringly-typed" APIs with struct
"wrapper types", as is the case with NotificationCenter. Notifications are now identified by a struct Notfication.Name
rather than by String
. For more details see the now legacy Migrating to Swift 3 guide
Swift 2.2 usage:
// Define identifier
let notificationIdentifier: String = "NotificationIdentifier"
// Register to receive notification
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(_:)), name: notificationIdentifier, object: nil)
// Post a notification
NSNotificationCenter.defaultCenter().postNotificationName(notificationIdentifier, object: nil)
Swift 3 & 4 usage:
// Define identifier
let notificationName = Notification.Name("NotificationIdentifier")
// Register to receive notification
NotificationCenter.default.addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification), name: notificationName, object: nil)
// Post notification
NotificationCenter.default.post(name: notificationName, object: nil)
// Stop listening notification
NotificationCenter.default.removeObserver(self, name: notificationName, object: nil)
All of the system notification types are now defined as static constants on Notification.Name
; i.e. .UIApplicationDidFinishLaunching
, .UITextFieldTextDidChange
, etc.
You can extend Notification.Name
with your own custom notifications in order to stay consistent with the system notifications:
// Definition:
extension Notification.Name {
static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")
}
// Usage:
NotificationCenter.default.post(name: .yourCustomNotificationName, object: nil)
Swift 4.2 usage:
Same as Swift 4, except now system notifications names are part of UIApplication. So in order to stay consistent with the system notifications you can extend UIApplication
with your own custom notifications instead of Notification.Name :
// Definition:
UIApplication {
public static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")
}
// Usage:
NotificationCenter.default.post(name: UIApplication.yourCustomNotificationName, object: nil)
Very close to what you posted, actually.
To get the assigned value, or default
if it's missing:
FOO="${VARIABLE:-default}" # If variable not set or null, use default.
Or to assign default
to VARIABLE
at the same time:
FOO="${VARIABLE:=default}" # If variable not set or null, set it to default.
I do not think you need float.
html,_x000D_
body,_x000D_
.container {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.div1, .div2 {_x000D_
display: inline-block;_x000D_
margin: 0;_x000D_
min-height: 100%;_x000D_
}_x000D_
_x000D_
.div1 {_x000D_
width: 25%;_x000D_
background-color: green;_x000D_
}_x000D_
_x000D_
.div2 {_x000D_
width: 75%;_x000D_
background-color: blue;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="div1"></div><!--_x000D_
--><div class="div2"></div>_x000D_
</div>
_x000D_
display: inline-block;
is used to display blocks as inline (just like spans but keeping the block effect)
Comments in the html is used because you have 75% + 25% = 100%. The space in-between the divs counts (so you have 75% + 1%? + 25% = 101%, meaning line break)
If you are on an English Windows machine, Git's default storage path will be C:\Documents and Settings\< current_user>\
, because on Windows the default Git local settings resides at C:\Documents and Settings\< current_user>\.git
and so Git creates a separate folder for each repo/clone
at C:\Documents and Settings\< current_user>\
and there are all the directories of cloned project.
For example, if you install Symfony 2 with
git clone git://github.com/symfony/symfony.git
the Symfony directory and file will be at
C:\Documents and Settings\< current_user>\symfony\
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js"></script>
<script type="text/javascript" src="jquery-2.1.0.js"></script>
<script type="text/javascript" >
function openOnImageClick(event)
{
//alert("Jai Sh Raam");
// document.getElementById("images").src = "fruits.jpg";
var target = event.target || event.srcElement; // IE
console.log(target);
console.log(target.src);
var img = document.createElement('img');
img.setAttribute('src', target.src);
img.setAttribute('width', '200');
img.setAttribute('height', '150');
document.getElementById("images").appendChild(img);
}
</script>
</head>
<body>
<h1>Screen Shot View</h1>
<p>Click the Tiger to display the Image</p>
<div id="images" >
</div>
<img src="tiger.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick(event)" />
<img src="sabaLogo1.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick(event)" />
</body>
</html>
I see there is a VBA solution and a non-VBA solution, which both are really good. I wanted to propose my Javascript solution.
There is an Excel add-in called Funfun that allows you to use javascript, HTML and css in Excel. It has an online editor with an embedded spreadsheet where you can build your chart.
I have written this code for you with Chart.js:
https://www.funfun.io/1/#/edit/5a61ed15404f66229bda3f44
To create this chart, I entered my data on the spreadsheet and read it with a json file, it is the short
file.
I make sure to put it in the right format, in script.js
, so I can add it to my chart:
var data = [];
var color = [];
var label = [];
for (var i = 1; i < $internal.data.length; i++)
{
label.push($internal.data[i][0]);
data.push([$internal.data[i][1], $internal.data[i][2]]);
color.push($internal.data[i][3]);
}
I then create the scatter chart with each dot having his designated color and position:
var dataset = [];
for (var i = 0; i < data.length; i++) {
dataset.push({
data: [{
x: data[i][0],
y: data[i][1]
}],
pointBackgroundColor: color[i],
pointStyle: "cercle",
radius: 6
});
}
After I've created my scatter chart I can upload it in Excel by pasting the URL in the funfun Excel add-in. Here is how it looks like with my example:
Once this is done You can change the color or the position of a dot instantly, in Excel, by changing the values in the spreadsheet.
If you want to add extra dots in the charts you just need to modify the radius of data
in the short
json file.
Hope this Javascript solution helps !
Disclosure : I’m a developer of funfun
Yes, your conclusion is correct. socket.recv
is a blocking call.
socket.recv(1024)
will read at most 1024 bytes, blocking if no data is waiting to be read. If you don't read all data, an other call to socket.recv
won't block.
socket.recv
will also end with an empty string if the connection is closed or there is an error.
If you want a non-blocking socket, you can use the select module (a bit more complicated than just using sockets) or you can use socket.setblocking
.
I had issues with socket.setblocking
in the past, but feel free to try it if you want.
Basically your query returns more than one result set. In API Docs uniqueResult() method says that Convenience method to return a single instance that matches the query, or null if the query returns no results
uniqueResult() method yield only single resultset
You can also use the apktool: http://ibotpeaches.github.io/Apktool/ which will also give you the xml res files. Along with that you can also use the dex2jar system which will output the dex file in the apk to a jar file that can be opened with JD-GUI and exported to standard java files.
Purpose of view is displaying model. You should use controller to redirect request before creating model and passing it to view. Use Controller.RedirectToAction method for this.
Here is my solution:
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.action == "getSource") {
this.pageSource = request.source;
var title = this.pageSource.match(/<title[^>]*>([^<]+)<\/title>/)[1];
alert(title)
}
});
chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
chrome.tabs.executeScript(
tabs[0].id,
{ code: 'var s = document.documentElement.outerHTML; chrome.runtime.sendMessage({action: "getSource", source: s});' }
);
});
First method:
Select simulator and press "command + s" button. Screenshot saved on desktop.
Second method:
Select simulator and go to "File > New Screenshot". Screenshot saved on desktop.
From this post:
To get the entire PC CPU and Memory usage:
using System.Diagnostics;
Then declare globally:
private PerformanceCounter theCPUCounter =
new PerformanceCounter("Processor", "% Processor Time", "_Total");
Then to get the CPU time, simply call the NextValue()
method:
this.theCPUCounter.NextValue();
This will get you the CPU usage
As for memory usage, same thing applies I believe:
private PerformanceCounter theMemCounter =
new PerformanceCounter("Memory", "Available MBytes");
Then to get the memory usage, simply call the NextValue()
method:
this.theMemCounter.NextValue();
For a specific process CPU and Memory usage:
private PerformanceCounter theCPUCounter =
new PerformanceCounter("Process", "% Processor Time",
Process.GetCurrentProcess().ProcessName);
where Process.GetCurrentProcess().ProcessName
is the process name you wish to get the information about.
private PerformanceCounter theMemCounter =
new PerformanceCounter("Process", "Working Set",
Process.GetCurrentProcess().ProcessName);
where Process.GetCurrentProcess().ProcessName
is the process name you wish to get the information about.
Note that Working Set may not be sufficient in its own right to determine the process' memory footprint -- see What is private bytes, virtual bytes, working set?
To retrieve all Categories, see Walkthrough: Retrieving Categories and Counters
The difference between Processor\% Processor Time
and Process\% Processor Time
is Processor
is from the PC itself and Process
is per individual process. So the processor time of the processor would be usage on the PC. Processor time of a process would be the specified processes usage. For full description of category names: Performance Monitor Counters
An alternative to using the Performance Counter
Use System.Diagnostics.Process.TotalProcessorTime and System.Diagnostics.ProcessThread.TotalProcessorTime properties to calculate your processor usage as this article describes.
use DECIMAL()
or NUMERIC()
as they are fixed precision and scale numbers.
SELECT fullName,
CAST(totalBal as DECIMAL(9,2)) _totalBal
FROM client_info
ORDER BY _totalBal DESC
Joe Edel's answer to himself is actually the right approach to resolve the pivot problem.
Basically the idea is to list out the columns in the base table firstly, and then any number of options.value
from the joint option table. Just left join
the same option table multiple times in order to get all the options.
What needs to be done by the programming language is to build this query dynamically according to a list of options needs to be queried.
You can use VLOOKUP, but this requires a wrapper function to return True
or False
. Not to mention it is (relatively) slow. Use COUNTIF or MATCH instead.
Fill down this formula in column K next to the existing values in column I (from I1
to I2691
):
=COUNTIF(<entire column E range>,<single column I value>)>0
=COUNTIF($E$1:$E$99504,$I1)>0
You can also use MATCH:
=NOT(ISNA(MATCH(<single column I value>,<entire column E range>)))
=NOT(ISNA(MATCH($I1,$E$1:$E$99504,0)))
You are getting AttributeError
because you're calling groups
on None
, which hasn't any methods.
regex.search
returning None
means the regex couldn't find anything matching the pattern from supplied string.
when using regex, it is nice to check whether a match has been made:
Result = re.search(SearchStr, htmlString)
if Result:
print Result.groups()
If nothing works for you, you can specify the full path of your python environment setup by conda.
For me, I set up an environment called "testenv" using conda.
I searched all python environments using
whereis python | grep 'miniconda'
It returned a list of python environments. Then I ran my_python_file.py using the following command.
~/miniconda3/envs/testenv/bin/python3.8 my_python_file.py
You can do the same thing on windows too but looking up for python and conda python environments is a bit different.
An other approach after trying the solutions below. When you need it clear, just initialise your list to new clear new list.
List<ModelData> dataLists = new ArrayList<>();
RaporAdapter adapter = new RaporAdapter(AyrintiliRapor.this, dataLists);
listview.setAdapter(adapter);
Or set visibility to Gone / Invisible up to need
img_pdf.setVisibility(View.INVISIBLE);
The typeof operator...
typeof(T)
... won't work with the c# switch statement. But how about this? The following post contains a static class...
Is there a better alternative than this to 'switch on type'?
...that will let you write code like this:
TypeSwitch.Do(
sender,
TypeSwitch.Case<Button>(() => textBox1.Text = "Hit a Button"),
TypeSwitch.Case<CheckBox>(x => textBox1.Text = "Checkbox is " + x.Checked),
TypeSwitch.Default(() => textBox1.Text = "Not sure what is hovered over"));
You will need have to download InternetExplorer driver executable on your system, download it from the source (http://code.google.com/p/selenium/downloads/list) after download unzip it and put on the place of somewhere in your computer. In my example, I will place it to D:\iexploredriver.exe
Then you have write below code in your eclipse main class
System.setProperty("webdriver.ie.driver", "D:/iexploredriver.exe");
WebDriver driver = new InternetExplorerDriver();
As mentioned in the error, the official manual and the comments:
Replace
public function TSStatus($host, $queryPort)
with
public function __construct($host, $queryPort)
In my case the RDLC files work with resource files (.resx), I had this error because I hadn't created the correspondent resx file for my rdlc report.
My solution was add the file .resx inside the App_LocalResources in this way:
\rep
\rep\myreport.rdlc
\rep\App_LocalResources\myreport.rdlc.resx
To convert UTC time to Local you have to use moment.local()
.
For more info see docs
var date = moment.utc().format('YYYY-MM-DD HH:mm:ss');
console.log(date); // 2015-09-13 03:39:27
var stillUtc = moment.utc(date).toDate();
var local = moment(stillUtc).local().format('YYYY-MM-DD HH:mm:ss');
console.log(local); // 2015-09-13 09:39:27
var date = moment.utc().format();_x000D_
console.log(date, "- now in UTC"); _x000D_
_x000D_
var local = moment.utc(date).local().format();_x000D_
console.log(local, "- UTC now to local");
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
_x000D_
$(".first").addClass("second");
If you'd like to add it on an event, you can do so easily as well. An example with the click event:
$(".first").click(function() {
$(this).addClass("second");
});
I hope my script help you.
<i class="mostrar-producto">mostrar...</i>
<div class="producto" style="display:none;position: absolute;">Producto</div>
My script
<script>
$(".mostrar-producto").mouseover(function(){
$(".producto").fadeIn();
});
$(".mostrar-producto").mouseleave(function(){
$(".producto").fadeOut();
});
</script>
EDIT: Per Michael Dillon's answer, SaveAsText does save the commands in a macro without having to go through converting to VBA. I don't know what happened when I tested that, but it didn't produce useful text in the resulting file.
So, I learned something new today!
ORIGINAL POST: To expand the question, I wondered if there was a way to retrieve the contents of a macro from code, and it doesn't appear that there is (at least not in A2003, which is what I'm running).
There are two collections through which you can access stored Macros:
CurrentDB.Containers("Scripts").Documents
CurrentProject.AllMacros
The properties that Intellisense identifies for the two collections are rather different, because the collections are of different types. The first (i.e., traditional, pre-A2000 way) is via a documents collection, and the methods/properties/members of all documents are the same, i.e., not specific to Macros.
Likewise, the All... collections of CurrentProject return collections where the individual items are of type Access Object. The result is that Intellisense gives you methods/properties/members that may not exist for the particular document/object.
So far as I can tell, there is no way to programatically retrieve the contents of a macro.
This would stand to reason, as macros aren't of much use to anyone who would have the capability of writing code to examine them programatically.
But if you just want to evaluate what the macros do, one alternative would be to convert them to VBA, which can be done programmatically thus:
Dim varItem As Variant
Dim strMacroName As String
For Each varItem In CurrentProject.AllMacros
strMacroName = varItem.Name
'Debug.Print strMacroName
DoCmd.SelectObject acMacro, strMacroName, True
DoCmd.RunCommand acCmdConvertMacrosToVisualBasic
Application.SaveAsText acModule, "Converted Macro- " & strMacroName, _
CurrentProject.Path & "\" & "Converted Macro- " & strMacroName & ".txt"
Next varItem
Then you could use the resulting text files for whatever you needed to do.
Note that this has to be run interactively in Access because it uses DoCmd.RunCommand, and you have to click OK for each macro -- tedious for databases with lots of macros, but not too onerous for a normal app, which shouldn't have more than a handful of macros.
No.
If the user is sophisticated or determined enough to:
then they are probably sophisticated or determined enough to:
So what's on this hidden sheet? Proprietary information like price formulas, or client names, or employee salaries? Putting that info in even an hidden tab probably isn't the greatest idea to begin with.
ConfigurationManager.AppSettings
is actually a property, so you need to use square brackets.
Overall, here's what you need to do:
SqlConnection con= new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
The problem is that you tried to set con to a string, which is not correct. You have to either pass it to the constructor or set con.ConnectionString property.
Upgrade pip as follows:
curl https://bootstrap.pypa.io/get-pip.py | python
Note: You may need to use sudo python
above if not in a virtual environment.
Python.org sites are stopping support for TLS versions 1.0 and 1.1. This means that Mac OS X version 10.12 (Sierra) or older will not be able to use pip unless they upgrade pip as above.
(Note that upgrading pip via pip install --upgrade pip
will also not upgrade it correctly. It is a chicken-and-egg issue)
This thread explains it (thanks to this Twitter post):
Mac users who use pip and PyPI:
If you are running macOS/OS X version 10.12 or older, then you ought to upgrade to the latest pip (9.0.3) to connect to the Python Package Index securely:
curl https://bootstrap.pypa.io/get-pip.py | python
and we recommend you do that by April 8th.
Pip 9.0.3 supports TLSv1.2 when running under system Python on macOS < 10.13. Official release notes: https://pip.pypa.io/en/stable/news/
Also, the Python status page:
Completed - The rolling brownouts are finished, and TLSv1.0 and TLSv1.1 have been disabled. Apr 11, 15:37 UTC
Update - The rolling brownouts have been upgraded to a blackout, TLSv1.0 and TLSv1.1 will be rejected with a HTTP 403 at all times. Apr 8, 15:49 UTC
Lastly, to avoid other install errors, make sure you also upgrade setuptools after doing the above:
pip install --upgrade setuptools
var data = {
"items": [{
"id": 1,
"category": "cat1"
}, {
"id": 2,
"category": "cat2"
}, {
"id": 3,
"category": "cat1"
}]
};
var returnedData = $.grep(data.items, function (element, index) {
return element.id == 1;
});
alert(returnedData[0].id + " " + returnedData[0].category);
The returnedData is returning an array of objects, so you can access it by array index.
I scanned the above answers and the proposed keydown
/keyup
approach works only under special circumstances. If the user alt-tabs away, or uses a key gesture to open a new browser window or tab, then a keydown
will be registered, which is fine, because at that point it's impossible to tell if the key is something the web app is monitoring, or is a standard browser or OS shortcut. Coming back to the browser page, it'll still think the key is held, though it was released in the meantime. Or some key is simply kept held, while the user is switching to another tab or application with the mouse, then released outside our page.
Modifier keys (Shift
etc.) can be monitored via mousemove
etc. assuming that there is at least one mouse interaction expected when tabbing back, which is frequently the case.
For most all other keys (except modifiers, Tab
, Delete
, but including Space
, Enter
), monitoring keypress
would work for most applications - a key held down will continue to fire. There's some latency in resetting the key though, due to the periodicity of keypress
firing. Basically, if keypress
doesn't keep firing, then it's possible to rule out most of the keys. This, combined with the modifiers is pretty airtight, though I haven't explored what to do with Tab
and Backspace
.
I'm sure there's some library out there that abstracts over this DOM weakness, or maybe some DOM standard change took care of it, since it's a rather old question.
You can also use this script to figure out more info:
EXEC sp_server_info
The result will be something like that:
attribute_id | attribute_name | attribute_value
-------------|-----------------------|-----------------------------------
1 | DBMS_NAME | Microsoft SQL Server
2 | DBMS_VER | Microsoft SQL Server 2012 - 11.0.6020.0
10 | OWNER_TERM | owner
11 | TABLE_TERM | table
12 | MAX_OWNER_NAME_LENGTH | 128
13 | TABLE_LENGTH | 128
14 | MAX_QUAL_LENGTH | 128
15 | COLUMN_LENGTH | 128
16 | IDENTIFIER_CASE | MIXED
? ? ?
? ? ?
? ? ?
As an addendum to b01's answer, the second argument of $.proxy
is often used to preserve the this
reference. Additional arguments passed to $.proxy
are partially applied to the function, pre-filling it with data. Note that any arguments $.post
passes to the callback will be applied at the end, so doSomething
should have those at the end of its argument list:
function clicked() {
var myDiv = $("#my-div");
var callback = $.proxy(doSomething, this, myDiv);
$.post("someurl.php",someData,callback,"json");
}
function doSomething(curDiv, curData) {
//"this" still refers to the same "this" as clicked()
var serverResponse = curData;
}
This approach also allows multiple arguments to be bound to the callback:
function clicked() {
var myDiv = $("#my-div");
var mySpan = $("#my-span");
var isActive = true;
var callback = $.proxy(doSomething, this, myDiv, mySpan, isActive);
$.post("someurl.php",someData,callback,"json");
}
function doSomething(curDiv, curSpan, curIsActive, curData) {
//"this" still refers to the same "this" as clicked()
var serverResponse = curData;
}
Maybe it is not quite as elegant, but the following might also work. I suspect asynchronously this would not be a good solution.
$p = Start-Process myjob.bat -redirectstandardoutput $logtempfile -redirecterroroutput $logtempfile -wait
add-content $logfile (get-content $logtempfile)
The .git
at the end of the repository name is just a convention. Typically, on git servers repositories are kept in directories named project.git
. The git client and protocol honours this convention by testing for project.git
when only project
is specified.
git://[email protected]/peter/first_app.git
is not a valid git url. git repositories can be identified and accessed via various url schemes specified here. [email protected]:peter/first_app.git
is the ssh
url mentioned on that page.
git
is flexible. It allows you to track your local branch against almost any branch of any repository. While master
(your local default branch) tracking origin/master
(the remote default branch) is a popular situation, it is not universal. Many a times you may not want to do that. This is why the first git push
is so verbose. It tells git what to do with the local master
branch when you do a git pull
or a git push
.
The default for git push
and git pull
is to work with the current branch's remote. This is a better default than origin master. The way git push determines this is explained here.
git
is fairly elegant and comprehensible but there is a learning curve to walk through.
UPDATED
I've updated your demo: http://jsfiddle.net/terryyounghk/QS56z/18/
Also, I've changed two ^=
to *=
. See http://api.jquery.com/category/selectors/
And note the :checked
selector. See http://api.jquery.com/checked-selector/
function createcodes() {
//run through each row
$('.authors-list tr').each(function (i, row) {
// reference all the stuff you need first
var $row = $(row),
$family = $row.find('input[name*="family"]'),
$grade = $row.find('input[name*="grade"]'),
$checkedBoxes = $row.find('input:checked');
$checkedBoxes.each(function (i, checkbox) {
// assuming you layout the elements this way,
// we'll take advantage of .next()
var $checkbox = $(checkbox),
$line = $checkbox.next(),
$size = $line.next();
$line.val(
$family.val() + ' ' + $size.val() + ', ' + $grade.val()
);
});
});
}
I changed the line
.ui-helper-hidden-accessible { position: absolute !important; clip: rect(1px 1px 1px 1px); clip: rect(1px,1px,1px,1px); }
to
.ui-helper-hidden-accessible { position: absolute !important; }
and everything works now. Otherwise try upping the z-index as Soldierflup suggested.
I came up with a mix of defining a class like David's answer, but not requiring a Where class to go with it. It looks something like:
var resultsGroupings = resultsRecords.GroupBy(r => new { r.IdObj1, r.IdObj2, r.IdObj3})
.Select(r => new ResultGrouping {
IdObj1= r.Key.IdObj1,
IdObj2= r.Key.IdObj2,
IdObj3= r.Key.IdObj3,
Results = r.ToArray(),
Count = r.Count()
});
private class ResultGrouping
{
public short IdObj1{ get; set; }
public short IdObj2{ get; set; }
public int IdObj3{ get; set; }
public ResultCsvImport[] Results { get; set; }
public int Count { get; set; }
}
Where resultRecords
is my initial list I'm grouping, and its a List<ResultCsvImport>
. Note that the idea here to is that, I'm grouping by 3 columns, IdObj1 and IdObj2 and IdObj3
You cannot make POST HTTP Requests by <a href="some_script.php">some_script</a>
Just open your house.php
, find in it where you have $house = $_POST['houseVar']
and change it to:
isset($_POST['houseVar']) ? $house = $_POST['houseVar'] : $house = $_GET['houseVar']
And in the streeview.php
make links like that:
<a href="house.php?houseVar=$houseNum"></a>
Or something else. I just don't know your files and what inside it.
Here's an alternative solution to this question. My adapter:
private class PagerAdapter extends FragmentPagerAdapter implements
ViewPager.OnPageChangeListener, TabListener {
private List<Fragment> mFragments = new ArrayList<Fragment>();
private ViewPager mPager;
private ActionBar mActionBar;
private Fragment mPrimaryItem;
public PagerAdapter(FragmentManager fm, ViewPager vp, ActionBar ab) {
super(fm);
mPager = vp;
mPager.setAdapter(this);
mPager.setOnPageChangeListener(this);
mActionBar = ab;
}
public void addTab(PartListFragment frag) {
mFragments.add(frag);
mActionBar.addTab(mActionBar.newTab().setTabListener(this).
setText(frag.getPartCategory()));
}
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
@Override
public int getCount() {
return mFragments.size();
}
/** (non-Javadoc)
* @see android.support.v4.app.FragmentStatePagerAdapter#setPrimaryItem(android.view.ViewGroup, int, java.lang.Object)
*/
@Override
public void setPrimaryItem(ViewGroup container, int position,
Object object) {
super.setPrimaryItem(container, position, object);
mPrimaryItem = (Fragment) object;
}
/** (non-Javadoc)
* @see android.support.v4.view.PagerAdapter#getItemPosition(java.lang.Object)
*/
@Override
public int getItemPosition(Object object) {
if (object == mPrimaryItem) {
return POSITION_UNCHANGED;
}
return POSITION_NONE;
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) { }
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) { }
@Override
public void onPageScrollStateChanged(int arg0) { }
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
@Override
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
/**
* This method removes the pages from ViewPager
*/
public void removePages() {
mActionBar.removeAllTabs();
//call to ViewPage to remove the pages
vp.removeAllViews();
mFragments.clear();
//make this to update the pager
vp.setAdapter(null);
vp.setAdapter(pagerAdapter);
}
}
Code to remove and add dynamically
//remove the pages. basically call to method removeAllViews from `ViewPager`
pagerAdapter.removePages();
pagerAdapter.addPage(pass your fragment);
After the advice of Peri Hartman, it started to work after I set null do ViewPager adapter and put the adapter again after the views removed. Before this the page 0 doesnt showed its list contents.
Thanks.
I think there is an error in the trigger code. As you want to delete all rows with the deleted patron ID, you have to use old.id (Otherwise it would delete other IDs)
Try this as the new trigger:
CREATE TRIGGER log_patron_delete AFTER DELETE on patrons
FOR EACH ROW
BEGIN
DELETE FROM patron_info
WHERE patron_info.pid = old.id;
END
Dont forget the ";" on the delete query. Also if you are entering the TRIGGER code in the console window, make use of the delimiters also.
Check your Network is properly working...this problem also occures because of internet issues
Use "\\"
to escape the \ character.
If you have PHP 5.5 or later, the best way is to use the built in function array_column()
:
$idCats = array_column($cats, 'id');
But the son has to be an array or converted to an array
I would like to expand open jfs's answer, which worked great for my problem: sorting two lists by a third, decorated list:
We can create our decorated list in any way, but in this case we will create it from the elements of one of the two original lists, that we want to sort:
# say we have the following list and we want to sort both by the algorithms name
# (if we were to sort by the string_list, it would sort by the numerical
# value in the strings)
string_list = ["0.123 Algo. XYZ", "0.345 Algo. BCD", "0.987 Algo. ABC"]
dict_list = [{"dict_xyz": "XYZ"}, {"dict_bcd": "BCD"}, {"dict_abc": "ABC"}]
# thus we need to create the decorator list, which we can now use to sort
decorated = [text[6:] for text in string_list]
# decorated list to sort
>>> decorated
['Algo. XYZ', 'Algo. BCD', 'Algo. ABC']
Now we can apply jfs's solution to sort our two lists by the third
# create and sort the list of indices
sorted_indices = list(range(len(string_list)))
sorted_indices.sort(key=decorated.__getitem__)
# map sorted indices to the two, original lists
sorted_stringList = list(map(string_list.__getitem__, sorted_indices))
sorted_dictList = list(map(dict_list.__getitem__, sorted_indices))
# output
>>> sorted_stringList
['0.987 Algo. ABC', '0.345 Algo. BCD', '0.123 Algo. XYZ']
>>> sorted_dictList
[{'dict_abc': 'ABC'}, {'dict_bcd': 'BCD'}, {'dict_xyz': 'XYZ'}]
One easy way is to drag and drop. It will copy files to /sdcard/Download. You can copy whole folders or multiple files. Make sure that "Enable Clipboard Sharing" is enabled. (under ...->Settings)
Here is the notes (from Brian Goetz book) I made, that might be of help to you
AtomicXXX classes
provide Non-blocking Compare-And-Swap implementation
Takes advantage of the support provide by hardware (the CMPXCHG instruction on Intel) When lots of threads are running through your code that uses these atomic concurrency API, they will scale much better than code which uses Object level monitors/synchronization. Since, Java's synchronization mechanisms makes code wait, when there are lots of threads running through your critical sections, a substantial amount of CPU time is spent in managing the synchronization mechanism itself (waiting, notifying, etc). Since the new API uses hardware level constructs (atomic variables) and wait and lock free algorithms to implement thread-safety, a lot more of CPU time is spent "doing stuff" rather than in managing synchronization.
not only offer better throughput, but they also provide greater resistance to liveness problems such as deadlock and priority inversion.
Here is what seems simplest and works in python 3.7
from collections import OrderedDict
d = OrderedDict([('method', 'constant'), ('data', '1.225')])
d2 = dict(d) # Now a normal dict
Now to check this:
>>> type(d2)
<class 'dict'>
>>> isinstance(d2, OrderedDict)
False
>>> isinstance(d2, dict)
True
NOTE: This also works, and gives same result -
>>> {**d}
{'method': 'constant', 'data': '1.225'}
>>> {**d} == d2
True
As well as this -
>>> dict(d)
{'method': 'constant', 'data': '1.225'}
>>> dict(d) == {**d}
True
Cheers
public void iterateStreamAPI(Map<String, Integer> map) {
map.entrySet().stream().forEach(e -> System.out.println(e.getKey() + ":"e.getValue()));
}
I'm guessing here, based on issues I've had in the past which I did solve:
I ended up with two solutions. My original solution was based on using rsh. Since then, most of our servers have had ssh installed, which has made this easier.
Using rsh, I put together a table of machines vs OS vs custom options which would guide this process in perl. Bourne shell wasn't sufficient, and we don't have bash on Sun or HP machines (and didn't have bash on AIX at the time - AIX 5L wasn't out yet). Korn shell wasn't much of an option, either, since most of our Linux boxes don't have pdksh installed. But, if you don't face these limitations, you can implement the idea in ksh or bash, I think.
Anyway, I would basically run 'rsh $machine -l $user "$cmd"' where $machine, of course, was the machine I was logging in to, $user, similarly obvious (though when I was going in as "root" this had some variance as we have multiple roots on some machines for reasons I don't fully understand), and $cmd was basically "DISPLAY=$DISPLAY xterm", though if I were launching konsole, for example, $cmd would be "konsole --display=$DISPLAY". Since $DISPLAY was being evaluated locally (where it's set properly), and not being passed literally across rsh, the display would always be set correctly.
I also had to make sure that no one did anything silly like reset DISPLAY if it was already set.
Now, I just use ssh, make sure that X11Forwarding is set to yes on the server (sshd_config), and then I can just ssh to the machine, let X commands go across the wire encrypted, and it'll always go back to the right place.
Though classmethod
and staticmethod
are quite similar, there's a slight difference in usage for both entities: classmethod
must have a reference to a class object as the first parameter, whereas staticmethod
can have no parameters at all.
class Date(object):
def __init__(self, day=0, month=0, year=0):
self.day = day
self.month = month
self.year = year
@classmethod
def from_string(cls, date_as_string):
day, month, year = map(int, date_as_string.split('-'))
date1 = cls(day, month, year)
return date1
@staticmethod
def is_date_valid(date_as_string):
day, month, year = map(int, date_as_string.split('-'))
return day <= 31 and month <= 12 and year <= 3999
date2 = Date.from_string('11-09-2012')
is_date = Date.is_date_valid('11-09-2012')
Let's assume an example of a class, dealing with date information (this will be our boilerplate):
class Date(object):
def __init__(self, day=0, month=0, year=0):
self.day = day
self.month = month
self.year = year
This class obviously could be used to store information about certain dates (without timezone information; let's assume all dates are presented in UTC).
Here we have __init__
, a typical initializer of Python class instances, which receives arguments as a typical instancemethod
, having the first non-optional argument (self
) that holds a reference to a newly created instance.
Class Method
We have some tasks that can be nicely done using classmethod
s.
Let's assume that we want to create a lot of Date
class instances having date information coming from an outer source encoded as a string with format 'dd-mm-yyyy'. Suppose we have to do this in different places in the source code of our project.
So what we must do here is:
Date
by passing those values to the initialization call.This will look like:
day, month, year = map(int, string_date.split('-'))
date1 = Date(day, month, year)
For this purpose, C++ can implement such a feature with overloading, but Python lacks this overloading. Instead, we can use classmethod
. Let's create another "constructor".
@classmethod
def from_string(cls, date_as_string):
day, month, year = map(int, date_as_string.split('-'))
date1 = cls(day, month, year)
return date1
date2 = Date.from_string('11-09-2012')
Let's look more carefully at the above implementation, and review what advantages we have here:
cls
is an object that holds the class itself, not an instance of the class. It's pretty cool because if we inherit our Date
class, all children will have from_string
defined also.Static method
What about staticmethod
? It's pretty similar to classmethod
but doesn't take any obligatory parameters (like a class method or instance method does).
Let's look at the next use case.
We have a date string that we want to validate somehow. This task is also logically bound to the Date
class we've used so far, but doesn't require instantiation of it.
Here is where staticmethod
can be useful. Let's look at the next piece of code:
@staticmethod
def is_date_valid(date_as_string):
day, month, year = map(int, date_as_string.split('-'))
return day <= 31 and month <= 12 and year <= 3999
# usage:
is_date = Date.is_date_valid('11-09-2012')
So, as we can see from usage of staticmethod
, we don't have any access to what the class is---it's basically just a function, called syntactically like a method, but without access to the object and its internals (fields and another methods), while classmethod does.
The information is not available through document.cookie, but if you're really desperate for it, you could try performing a request through the XmlHttpRequest object to the current page and access the cookie header using getResponseHeader().
The first regex will match one whitespace character. The second regex will reluctantly match one or more whitespace characters. For most purposes, these two regexes are very similar, except in the second case, the regex can match more of the string, if it prevents the regex match from failing. from http://www.coderanch.com/t/570917/java/java/regex-difference
I would say that you need to check if the state already has the same value you are trying to set. If it's the same, there is no point to set state again for the same value.
Make sure to set your state like this:
let top = newValue /*true or false*/
if(top !== this.state.top){
this.setState({top});
}
You can install the package gcolor2
for this:
sudo apt-get install gcolor2
Then:
Applications -> Graphics -> GColor2
To insert the Value into the Dictionary
Dictionary<string, string> dDS1 = new Dictionary<string, string>();//Declaration
dDS1.Add("VEqpt", "aaaa");//adding key and value into the dictionary
string Count = dDS1["VEqpt"];//assigning the value of dictionary key to Count variable
dDS1["VEqpt"] = Count + "bbbb";//assigning the value to key
Write the following method:
public boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} // try
catch (Exception e) {
return false;
} // catch
}
Now, you can check whether alert is present or not by using the method written above as below:
if (isAlertPresent()) {
driver.switchTo().alert();
driver.switchTo().alert().accept();
driver.switchTo().defaultContent();
}
Either !=
or ne
will work, but you need to get the accessor syntax and nested quotes sorted out.
<c:if test="${content.contentType.name ne 'MCE'}">
<%-- snip --%>
</c:if>
The "up" affordance indicator is provided by a drawable specified in the homeAsUpIndicator
attribute of the theme. To override it with your own custom version it would be something like this:
<style name="Theme.MyFancyTheme" parent="android:Theme.Holo">
<item name="android:homeAsUpIndicator">@drawable/my_fancy_up_indicator</item>
</style>
If you are supporting pre-3.0 with your application be sure you put this version of the custom theme in values-v11
or similar.
import numpy as np
import scipy.stats
def mean_confidence_interval(data, confidence=0.95):
a = 1.0 * np.array(data)
n = len(a)
m, se = np.mean(a), scipy.stats.sem(a)
h = se * scipy.stats.t.ppf((1 + confidence) / 2., n-1)
return m, m-h, m+h
you can calculate like this way.
The reason for using POST when making changes to data:
Also, don't put sensitive information in the query string (only option with GET) because it shows up in the address bar, bookmarks and server logs.
Hopefully this explains why people say POST is 'secure'. If you are transmitting sensitive data you must use SSL.
For Python 3
Remove the rb
argument and use either r
or don't pass argument (default read mode
).
with open( <path-to-file>, 'r' ) as theFile:
reader = csv.DictReader(theFile)
for line in reader:
# line is { 'workers': 'w0', 'constant': 7.334, 'age': -1.406, ... }
# e.g. print( line[ 'workers' ] ) yields 'w0'
print(line)
For Python 2
import csv
with open( <path-to-file>, "rb" ) as theFile:
reader = csv.DictReader( theFile )
for line in reader:
# line is { 'workers': 'w0', 'constant': 7.334, 'age': -1.406, ... }
# e.g. print( line[ 'workers' ] ) yields 'w0'
Python has a powerful built-in CSV handler. In fact, most things are already built in to the standard library.
Smoke tests are tests which aim is to check if everything was build correctly. I mean here integration, connections. So you check from technically point of view if you can make wider tests. You have to execute some test cases and check if the results are positive.
Sanity tests in general have the same aim - check if we can make further test. But in sanity test you focus on business value so you execute some test cases but you check the logic.
In general people say smoke tests for both above because they are executed in the same time (sanity after smoke tests) and their aim is similar.
In PHP it depends on if you are validating types:
(
( false !== 0 ) && ( false !== -1 ) && ( false == 0 ) && ( false == -1 ) &&
( false !== null ) && ( false == null )
)
Technically null is 0x00
but in PHP ( null == 0x00 ) && ( null !== 0x00 )
.
0
is an integer value.
I'm not sure how much of your "slowness" will be due to the loop you're doing to find entries with particular attribute values, but you can remove this loop by being more specific with your filter. Try this page for some guidance ... Search Filter Syntax
The backslash \
is the line continuation character the error message is talking about, and after it, only newline characters/whitespace are allowed (before the next non-whitespace continues the "interrupted" line.
print "This is a very long string that doesn't fit" + \
"on a single line"
Outside of a string, a backslash can only appear in this way. For division, you want a slash: /
.
If you want to write a verbatim backslash in a string, escape it by doubling it: "\\"
In your code, you're using it twice:
print("Length between sides: " + str((length*length)*2.6) +
" \ 1.5 = " + # inside a string; treated as literal
str(((length*length)*2.6)\1.5)+ # outside a string, treated as line cont
# character, but no newline follows -> Fail
" Units")
My simple answer.
def get_files_tree(src="src_path"):
req_files = []
for r, d, files in os.walk(src):
for file in files:
src_file = os.path.join(r, file)
src_file = src_file.replace('\\', '/')
if src_file.endswith('.db'):
continue
req_files.append(src_file)
return req_files
def copy_tree_force(src_path="",dest_path=""):
"""
make sure that all the paths has correct slash characters.
"""
for cf in get_files_tree(src=src_path):
df= cf.replace(src_path, dest_path)
if not os.path.exists(os.path.dirname(df)):
os.makedirs(os.path.dirname(df))
shutil.copy2(cf, df)
Good answers above- if you're looking for something reusable here is the code. Note that you might want to check the decimal places value, and this may overflow.
public static decimal TruncateToDecimalPlace(this decimal numberToTruncate, int decimalPlaces)
{
decimal power = (decimal)(Math.Pow(10.0, (double)decimalPlaces));
return Math.Truncate((power * numberToTruncate)) / power;
}
I was able to do that by using \n
in the line parameter.
It is specially useful if the file can be validated, and adding a single line generates an invalid file.
In my case, I was adding AuthorizedKeysCommand
and AuthorizedKeysCommandUser
to sshd_config, with the following command:
- lineinfile: dest=/etc/ssh/sshd_config line='AuthorizedKeysCommand /etc/ssh/ldap-keys\nAuthorizedKeysCommandUser nobody' validate='/usr/sbin/sshd -T -f %s'
Adding only one of the options generates a file that fails validation.
Presuming you have a .dmp file created by oracle exp then
imp help=y
will be your friend. It will lead you to
imp file=<file>.dmp show=y
to see the contents of the dump and then something like
imp scott/tiger@example file=<file>.dmp fromuser=<source> touser=<dest>
to import from one user to another. Be prepared for a long haul though if it is a complicated schema as you will need to precreate all referenced schema users, and tablespaces to make the imp work correctly
As easy as
SELECT lpad(42::text, 4, '0')
References:
sqlfiddle: http://sqlfiddle.com/#!15/d41d8/3665
import { HttpClientModule } from '@angular/common/http';
The HttpClient API was introduced in the version 4.3.0. It is an evolution of the existing HTTP API and has it's own package @angular/common/http. One of the most notable changes is that now the response object is a JSON by default, so there's no need to parse it with map method anymore .Straight away we can use like below
http.get('friends.json').subscribe(result => this.result =result);
You can do:
>>> a = 'ZENOVW'
>>> ''.join(sorted(a))
'ENOVWZ'
Use the URL
https://webcache.googleusercontent.com/search?q=cache:<your url without "http://">
Example:
https://webcache.googleusercontent.com/search?q=cache:stackoverflow.com
It contains a header like this:
This is Google's cache of https://stackoverflow.com/. It is a snapshot of the page as it appeared on 21 Aug 2012 11:33:38 GMT. The current page could have changed in the meantime. Learn more
Tip: To quickly find your search term on this page, press Ctrl+F or ?+F (Mac) and use the find bar.
This error happens when you have a ViewBag Non-Existent in your razor code calling a method.
Controller
public ActionResult Accept(int id)
{
return View();
}
razor:
<div class="form-group">
@Html.LabelFor(model => model.ToId, "To", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.Flag(Model.from)
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input value="@ViewBag.MaximounAmount.ToString()" />@* HERE is the error *@
</div>
</div>
For some reason, the .net aren't able to show the error in the correct line.
Normally this causes a lot of wasted time.
Try this code. This seems working in my case.
$this->db->where(array('id !='=> $id))
On a 32-bit system, kmalloc() returns the kernel logical address (its a virtual address though) which has the direct mapping (actually with constant offset) to physical address. This direct mapping ensures that we get a contiguous physical chunk of RAM. Suited for DMA where we give only the initial pointer and expect a contiguous physical mapping thereafter for our operation.
vmalloc() returns the kernel virtual address which in turn might not be having a contiguous mapping on physical RAM. Useful for large memory allocation and in cases where we don't care about that the memory allocated to our process is continuous also in Physical RAM.
I met some problems in Clion and finally, I solved them. Here is some experience.
You can use Include Directives
<%
if(request.getParameter("p")!=null)
{
String p = request.getParameter("p");
%>
<%@include file="<%="includes/" + p +".jsp"%>"%>
<%
}
%>
or JSP Include Action
<%
if(request.getParameter("p")!=null)
{
String p = request.getParameter("p");
%>
<jsp:include page="<%="includes/"+p+".jsp"%>"/>
<%
}
%>
the different is include directive includes a file during the translation phase. while JSP Include Action includes a file at the time the page is requested
I recommend Spring MVC Framework as your controller to manipulate things. use url pattern instead of parameter.
example:
www.yourwebsite.com/products
instead of
www.yourwebsite.com/?p=products
Watch this video Spring MVC Framework
This is really a question about whether the path to the Python interpreter should be absolute or Logical (/usr/bin/env
) in respect to portability.
Encountering other answers on this and other Stack sites which talked about the issue in a general way without supporting proofs, I've performed some really, REALLY, granular testing & analysis on this very question on the unix.stackexchange.com. Rather than paste that answer here, I'll point those interested to the comparative analysis to that answer:
https://unix.stackexchange.com/a/566019/334294
Being a Linux Engineer, my goal is always to provide the most suitable, optimized hosts for my developer clients, so the issue of Python environments was something I really needed a solid answer to. My view after the testing was that the logical path in the she-bang was the better of the (2) options.
Try to run:
adb tcpip 5555
adb connect 192.168.2.4
SSL development libraries have to be installed
CentOS:
$ yum install openssl-devel libffi-devel
Ubuntu:
$ apt-get install libssl-dev libffi-dev
OS X (with Homebrew installed):
$ brew install openssl
You need to define width
of the div containing the textarea
and when you declare textarea
, you can then set .main > textarea
to have width: inherit
.
Note: .main > textarea
means a <textarea>
inside of an element with class="main"
.
Here is the working solution
The HTML:
<div class="wrapper">
<div class="left">left</div>
<div class="main">
<textarea name="" cols="" rows=""></textarea>
</div>
</div>
The CSS:
.wrapper {
display: table;
width: 100%;
}
.left {
width: 20%;
background: #cccccc;
display: table-cell;
}
.main {
width: 80%;
background: gray;
display: inline;
}
.main > textarea {
width: inherit;
}
.container {_x000D_
position: relative;_x000D_
width: 50%;_x000D_
}_x000D_
_x000D_
.image {_x000D_
display: block;_x000D_
width: 100%;_x000D_
height: auto;_x000D_
}_x000D_
_x000D_
.overlay {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
opacity: 0;_x000D_
transition: .5s ease;_x000D_
background-color: #008CBA;_x000D_
}_x000D_
_x000D_
.container:hover .overlay {_x000D_
opacity: 1;_x000D_
}_x000D_
_x000D_
.text {_x000D_
color: white;_x000D_
font-size: 20px;_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
transform: translate(-50%, -50%);_x000D_
-ms-transform: translate(-50%, -50%);_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head></head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
<img src="http://lorempixel.com/500/500/" alt="Avatar" class="image">_x000D_
<div class="overlay">_x000D_
<div class="text">Hello World</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Reference Link W3schools with multiple styles
or you could use this line:
link.setAttribute('onClick', 'onClickLink('+i+')');
instead of this one:
link.onclick= function() { onClickLink(i+'');};
__stdcall
is the calling convention used for the function. This tells the compiler the rules that apply for setting up the stack, pushing arguments and getting a return value.
There are a number of other calling conventions, __cdecl
, __thiscall
, __fastcall
and the wonderfully named __declspec(naked)
. __stdcall
is the standard calling convention for Win32 system calls.
Wikipedia covers the details.
It primarily matters when you are calling a function outside of your code (e.g. an OS API) or the OS is calling you (as is the case here with WinMain). If the compiler doesn't know the correct calling convention then you will likely get very strange crashes as the stack will not be managed correctly.
For the latest bootstrap-datepicker
(1.4.0 at the time of writing), you need to use this:
$('#myDatepicker').datepicker({
format: "mm/yyyy",
startView: "year",
minViewMode: "months"
})
Source: Bootstrap Datepicker Options
Here is some simple code to give output as currentdate
+ D days
= some 'x' date
(future date):
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, 5);
System.out.println(dateFormat.format(c.getTime()));
I changed this:
public string ByteArrToString(byte[] byteArr)
{
byte val;
string tempStr = "";
for (int i = 0; i <= byteArr.GetUpperBound(0); i++)
{
val = byteArr[i];
if (val < (byte)10)
tempStr += "00" + val.ToString();
else if (val < (byte)100)
tempStr += "0" + val.ToString();
else
tempStr += val.ToString();
}
return tempStr;
}
to this:
public string ByteArrToString(byte[] byteArr)
{
string temp = "";
foreach (byte b in byteArr)
temp += b.ToString().PadLeft(3, '0');
return temp;
}
Modern Java version of Steffi Keran's answer
public class Solution {
public static void main(String[] args) {
// create a simple hash map and insert some key-value pairs into it
Map<String, Integer> map = new HashMap<>();
map.put("Python", 3);
map.put("C", 0);
map.put("JavaScript", 4);
map.put("C++", 1);
map.put("Golang", 5);
map.put("Java", 2);
// Create a linked list from the above map entries
List<Map.Entry<String, Integer>> list = new LinkedList<>(map.entrySet());
// sort the linked list using Collections.sort()
list.sort(Comparator.comparing(Map.Entry::getValue));
list.forEach(System.out::println);
}
}
When it comes to Google Analytics I found raik's answer at Secure Google tracking cookies very useful. It set secure and samesite to a value.
ga('create', 'UA-XXXXX-Y', {
cookieFlags: 'max-age=7200;secure;samesite=none'
});
Also more info in this blog post
Push SVG element to last, so that its z-index will be in top. In SVG, there s no property called z-index. try below javascript to bring the element to top.
var Target = document.getElementById(event.currentTarget.id);
var svg = document.getElementById("SVGEditor");
svg.insertBefore(Target, svg.lastChild.nextSibling);
Target: Is an element for which we need to bring it to top svg: Is the container of elements
Here's one: (check out http://hongouru.blogspot.ie/2011/09/c-ocr-optical-character-recognition.html or http://www.codeproject.com/Articles/41709/How-To-Use-Office-2007-OCR-Using-C for more info)
using MODI;
static void Main(string[] args)
{
DocumentClass myDoc = new DocumentClass();
myDoc.Create(@"theDocumentName.tiff"); //we work with the .tiff extension
myDoc.OCR(MiLANGUAGES.miLANG_ENGLISH, true, true);
foreach (Image anImage in myDoc.Images)
{
Console.WriteLine(anImage.Layout.Text); //here we cout to the console.
}
}
May not be the most pythonic, but
>>> b = {}
>>> for i in range(0, len(a), 2):
b[a[i]] = a[i+1]
A somewhat common use case for creating an empty file is to trigger something else happening in a different process in the absence of more sophisticated in process communication. In this case, it can help to have the file creation be atomic from the outside world's point of view (particularly if the thing being triggered is going to delete the file to "consume" the trigger).
So it can help to create a junk name (Guid.NewGuid.ToString()) in the same directory as the file you want to create, and then do a File.Move from the temporary name to your desired name. Otherwise triggered code which checks for file existence and then deletes the trigger may run into race conditions where the file is deleted before it is fully closed out.
Having the temp file in the same directory (and file system) gives you the atomicity you may want. This gives something like.
public void CreateEmptyFile(string path)
{
string tempFilePath = Path.Combine(Path.GetDirectoryName(path),
Guid.NewGuid.ToString());
using (File.Create(tempFilePath)) {}
File.Move(tempFilePath, path);
}
If you get the error also when you run
composer install
Just run this command first
composer dump-autoload
This command will clean up all compiled files and their paths.
I recommend checking out docker-compose. Here's how that would work:
Create a file named, docker-compose.yml that looks like this:
version: '2'
services:
mysql:
image: mariadb:10.1.19
ports:
- 8083:3306
volumes:
- ./mysql:/var/lib/mysql
environment:
MYSQL_ROOT_PASSWORD: wp
Next, run:
$ docker-compose up
Notes:
Now, you can access the mysql console thusly:
$ mysql -P 8083 --protocol=tcp -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 5.5.5-10.1.19-MariaDB-1~jessie mariadb.org binary distribution
Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
Notes:
You can pass the -d flag to run the mysql/mariadb container in detached/background mode.
The password is "wp" which is defined in the docker-compose.yml file.
Same advice as maniekq but full example with docker-compose.
Do this: Step 1: Your String
String str = ";;;;;;\n" +
"Name, number, address;;;;;;\n" +
"01.01.12-16.02.12;;;;;;\n" +
";;;;;;\n" +
";;;;;;";
Step 2: Just replace all "\n" with "%n" the result looks like this
String str = ";;;;;;%n" +
"Name, number, address;;;;;;%n" +
"01.01.12-16.02.12;;;;;;%n" +
";;;;;;%n" +
";;;;;;";
Notice I've just put "%n" in place of "\n"
Step 3: Now simply call format()
str=String.format(str);
That's all you have to do.
The answers above are just not correct. A SQL Script even with data is not a backup. A backup is a BAK file that contains the full database in its current structure including indizes.
Of course a BAK file containg the full backup with all data and indizes from a remote SQL Server database can be retrieved on a local system.
This can be done with commercial software, to directly save a backup BAK file to your local machine, for example This one will directly create a backup from a remote SQL db on your local machine.
The ASIDE has since been modified to include secondary content as well.
HTML5 Doctor has a great writeup on it here: http://html5doctor.com/aside-revisited/
Excerpt:
With the new definition of aside, it’s crucial to remain aware of its context. >When used within an article element, the contents should be specifically related >to that article (e.g., a glossary). When used outside of an article element, the >contents should be related to the site (e.g., a blogroll, groups of additional >navigation, and even advertising if that content is related to the page).
If you want to use mod_rewrite for access control you can use condition like user agent, http referrer, remote addr etc.
Example
RewriteCond %{REMOTE_ADDR} !=*.*.*.* #you ip address
RewriteRule ^$ - [F]
Refrences:
None of the answers worked for me. If you are running on Ubuntu, you can try:
With python3:
sudo apt-get install python3 python-dev python3-dev \
build-essential libssl-dev libffi-dev \
libxml2-dev libxslt1-dev zlib1g-dev \
python-pip
With Python 2:
sudo apt-get install python-dev \
build-essential libssl-dev libffi-dev \
libxml2-dev libxslt1-dev zlib1g-dev \
python-pip
Update: Yes, I understand that this answer does not explain the difference between arm64 and armhf. There is a great answer that does explain that on this page. This answer was intended to help set the asker on the right path, as they clearly had a misunderstanding about the capabilities of the Raspberry Pi at the time of asking.
Where are you seeing that the architecture is armhf? On my Raspberry Pi 3, I get:
$ uname -a
armv7l
Anyway, armv7 indicates that the system architecture is 32-bit. The first ARM architecture offering 64-bit support is armv8. See this table for reference.
You are correct that the CPU in the Raspberry Pi 3 is 64-bit, but the Raspbian OS has not yet been updated for a 64-bit device. 32-bit software can run on a 64-bit system (but not vice versa). This is why you're not seeing the architecture reported as 64-bit.
You can follow the GitHub issue for 64-bit support here, if you're interested.
There doesn't seem to be a pretty way to do this. Here is a page that has a number of methods, including:
def split_seq(seq, size):
newseq = []
splitsize = 1.0/size*len(seq)
for i in range(size):
newseq.append(seq[int(round(i*splitsize)):int(round((i+1)*splitsize))])
return newseq
Just in case this helps anyone else:
If you're going to be adding the TimeOut
directive, and your website uses multiple vhosts (eg. one for port 80, one for port 443), then don't forget to add the directive to all of them!
You can remove the entire line below:
.map((res: Response) => res.json());
No need to use the map method at all.
Just use That.Its Easy.
<script language="javascript" type="text/javascript">
var images = new Array()
images[0] = "img1.jpg";
images[1] = "img2.jpg";
images[2] = "img3.jpg";
setInterval("changeImage()", 30000);
var x=0;
function changeImage()
{
document.getElementById("img").src=images[x]
x++;
if (images.length == x)
{
x = 0;
}
}
</script>
And in Body Write this Code:-
<img id="img" src="imgstart.jpg">
Here's the same as the current top answer, but in an ES6 one-liner:
myArray.sort((a, b) => a.distance - b.distance);
With webpack you can put env-specific config into the externals
field in webpack.config.js
externals: {
'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? {
serverUrl: "https://myserver.com"
} : {
serverUrl: "http://localhost:8090"
})
}
If you want to store the configs in a separate JSON file, that's possible too, you can require that file and assign to Config
:
externals: {
'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? require('./config.prod.json') : require('./config.dev.json'))
}
Then in your modules, you can use the config:
var Config = require('Config')
fetchData(Config.serverUrl + '/Enterprises/...')
For React:
import Config from 'Config';
axios.get(this.app_url, {
'headers': Config.headers
}).then(...);
Not sure if it covers your use case but it's been working pretty well for us.
In my case the problem was that the path was enclosed in quotation marks ("):
-vm
"C:\Program Files\Java\jdk1.8.0_25\bin"
Removing them fixed the problem:
-vm
C:\Program Files\Java\jdk1.8.0_25\bin
after installing the 1.7jdk from oracle, i changed my bash scripts to add:
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_13.jdk/Contents/Home
and then running java -version
showed the right version.
For the current latest mysql version (8.0.16), none of these answers worked for me.
After looking at several different answers and combining them together, this is what I ended up using that worked:
update user set authentication_string='test' where user='root';
Hope this helps.
My navigation bar was not showing, so I have used the following method in Swift 2 iOS 9
let viewController = self.storyboard?.instantiateViewControllerWithIdentifier("Dashboard") as! Dashboard
// Creating a navigation controller with viewController at the root of the navigation stack.
let navController = UINavigationController(rootViewController: viewController)
self.presentViewController(navController, animated:true, completion: nil)
If you are working with ActionBarSherlock
In your theme add this:
<style name="MyTheme" parent="Theme.Sherlock">
....
<item name="windowContentOverlay">@null</item>
<item name="android:windowContentOverlay">@null</item>
....
</style>
You could use a StringReader and convert the reader to an input stream using the solution in this other stackoverflow post.
If you use PyCharm, please change you 'Project Interpreter' to '2.7.x'
.yourClass>tbody>tr>td{border: 1px solid #ffffff !important;}
Just for people using VS2019, I think other answers are also pointing out same location.
For just digits after a currency sign : \(.+\s*\d+\s*\)
should work
Or \(.+\)
for anything inside brackets
directory size using php filesize and RecursiveIteratorIterator.
This works with any platform which is having php 5 or higher version.
/**
* Get the directory size
* @param string $directory
* @return integer
*/
function dirSize($directory) {
$size = 0;
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file){
$size+=$file->getSize();
}
return $size;
}
Showing it graphically.
Centering on parent is done by constraining both sides to the parent. You can the constrain additional objects off of the centered object.
Note. Each arrow represents a "app:layout_constraintXXX_toYYY=" attribute. (6 in the picture)
Works for me in the same way:
...
<MyComponent {...this.props}>
<Route path="path1" name="pname1" component="FirstPath">
...
</MyComponent>
...
And then, I can access "this.props.location.pathname" in the MyComponent function.
I forgot that it was I am...))) Following link describes more for make navigation bar etc.: react router this.props.location
It does appear red on Firefox and IE 8. But perhaps you need to change the border-style
too.
.field_set{_x000D_
border-color: #F00;_x000D_
border-style: solid;_x000D_
}
_x000D_
<fieldset class="field_set">_x000D_
<legend>box</legend>_x000D_
<table width="100%" border="0" cellspacing="0" cellpadding="0">_x000D_
<tr>_x000D_
<td> </td>_x000D_
</tr>_x000D_
</table>_x000D_
</fieldset>
_x000D_
I faced the same problem but the issue was very silly, By mistake I have given wrong relationship I have given relationship between 2 Ids.
In case you get a cross-domain error:
If you have control over the content of the iframe - that is, if it is merely loaded in a cross-origin setup such as on Amazon Mechanical Turk - you can circumvent this problem with the <body onload='my_func(my_arg)'>
attribute for the inner html.
For example, for the inner html, use the this
html parameter (yes - this
is defined and it refers to the parent window of the inner body element):
<body onload='changeForm(this)'>
In the inner html :
function changeForm(window) {
console.log('inner window loaded: do whatever you want with the inner html');
window.document.getElementById('mturk_form').style.display = 'none';
</script>
Try to use GMT
instead of UTC
. They refer to the same time zone, yet the name GMT
is more common and might work.
I have used Docker in production environments and staging very much. When you get used to it you will find it very powerful for building a multi container and isolated environments.
Docker has been developed based on LXC (Linux Container) and works perfectly in many Linux distributions, especially Ubuntu.
Docker containers are isolated environments. You can see it when you issue the top
command in a Docker container that has been created from a Docker image.
Besides that, they are very light-weight and flexible thanks to the dockerFile configuration.
For example, you can create a Docker image and configure a DockerFile and tell that for example when it is running then wget 'this', apt-get 'that', run 'some shell script', setting environment variables and so on.
In micro-services projects and architecture Docker is a very viable asset. You can achieve scalability, resiliency and elasticity with Docker, Docker swarm, Kubernetes and Docker Compose.
Another important issue regarding Docker is Docker Hub and its community. For example, I implemented an ecosystem for monitoring kafka using Prometheus, Grafana, Prometheus-JMX-Exporter, and Docker.
For doing that, I downloaded configured Docker containers for zookeeper, kafka, Prometheus, Grafana and jmx-collector then mounted my own configuration for some of them using YAML files, or for others, I changed some files and configuration in the Docker container and I build a whole system for monitoring kafka using multi-container Dockers on a single machine with isolation and scalability and resiliency that this architecture can be easily moved into multiple servers.
Besides the Docker Hub site there is another site called quay.io that you can use to have your own Docker images dashboard there and pull/push to/from it. You can even import Docker images from Docker Hub to quay then running them from quay on your own machine.
Note: Learning Docker in the first place seems complex and hard, but when you get used to it then you can not work without it.
I remember the first days of working with Docker when I issued the wrong commands or removing my containers and all of data and configurations mistakenly.
What was causing these errors for me (I was getting 8+ for some of my cocoapods) was fixing any runtime build issues in all the pods.
In Swift 3 and later you can:
let url = URL(string: "http://www.thisismylink.com/postName.php")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let parameters: [String: Any] = [
"id": 13,
"name": "Jack & Jill"
]
request.httpBody = parameters.percentEncoded()
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data,
let response = response as? HTTPURLResponse,
error == nil else { // check for fundamental networking error
print("error", error ?? "Unknown error")
return
}
guard (200 ... 299) ~= response.statusCode else { // check for http errors
print("statusCode should be 2xx, but is \(response.statusCode)")
print("response = \(response)")
return
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
Where:
extension Dictionary {
func percentEncoded() -> Data? {
return map { key, value in
let escapedKey = "\(key)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
let escapedValue = "\(value)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
return escapedKey + "=" + escapedValue
}
.joined(separator: "&")
.data(using: .utf8)
}
}
extension CharacterSet {
static let urlQueryValueAllowed: CharacterSet = {
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
var allowed = CharacterSet.urlQueryAllowed
allowed.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
return allowed
}()
}
This checks for both fundamental networking errors as well as high-level HTTP errors. This also properly percent escapes the parameters of the query.
Note, I used a name
of Jack & Jill
, to illustrate the proper x-www-form-urlencoded
result of name=Jack%20%26%20Jill
, which is “percent encoded” (i.e. the space is replaced with %20
and the &
in the value is replaced with %26
).
See previous revision of this answer for Swift 2 rendition.
am not sure if I fully understand the issue, but guess it's related to the one I had, am using Qt with TCP socket communication, all non-blocking, both Windows and Linux..
wanted to get a quick notification when an already connected client failed or completely disappeared, and not waiting the default 900+ seconds until the disconnect signal got raised. The trick to get this working was to set the TCP_USER_TIMEOUT socket option of the SOL_TCP layer to the required value, given in milliseconds.
this is a comparably new option, pls see http://tools.ietf.org/html/rfc5482, but apparently it's working fine, tried it with WinXP, Win7/x64 and Kubuntu 12.04/x64, my choice of 10 s turned out to be a bit longer, but much better than anything else I've tried before ;-)
the only issue I came across was to find the proper includes, as apparently this isn't added to the standard socket includes (yet..), so finally I defined them myself as follows:
#ifdef WIN32
#include <winsock2.h>
#else
#include <sys/socket.h>
#endif
#ifndef SOL_TCP
#define SOL_TCP 6 // socket options TCP level
#endif
#ifndef TCP_USER_TIMEOUT
#define TCP_USER_TIMEOUT 18 // how long for loss retry before timeout [ms]
#endif
setting this socket option only works when the client is already connected, the lines of code look like:
int timeout = 10000; // user timeout in milliseconds [ms]
setsockopt (fd, SOL_TCP, TCP_USER_TIMEOUT, (char*) &timeout, sizeof (timeout));
and the failure of an initial connect is caught by a timer started when calling connect(), as there will be no signal of Qt for this, the connect signal will no be raised, as there will be no connection, and the disconnect signal will also not be raised, as there hasn't been a connection yet..
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; ++i) {
// ...
}
Just to give you an another option, you could use https://sourceforge.net/projects/dd2vmdk/ as well. dd2vmdk is a *nix-based program that allows you to mount raw disk images (created by dd, dcfldd, dc3dd, ftk imager, etc) by taking the raw image, analyzing the master boot record (physical sector 0), and getting specific information that is need to create a vmdk file.
Personally, imo Qemu and the Zapotek's raw2vmdk tools are the best overall options to convert dd to vmdks.
Disclosure: I am the author of this project.
if this is a real program and not a study project, then look at using the Apache Commons StringUtils class - particularly the countMatches method.
If it is a study project then keep at it and learn from your exploring :)
I recently had the requirement to use JNDI with an embedded Tomcat in Spring Boot.
Actual answers give some interesting hints to solve my task but it was not enough as probably not updated for Spring Boot 2.
Here is my contribution tested with Spring Boot 2.0.3.RELEASE.
Specifying a datasource available in the classpath at runtime
You have multiple choices :
If you don't specify anyone of them, with the default configuration the instantiation of the datasource will throw an exception :
Caused by: javax.naming.NamingException: Could not create resource factory instance at org.apache.naming.factory.ResourceFactory.getDefaultFactory(ResourceFactory.java:50) at org.apache.naming.factory.FactoryBase.getObjectInstance(FactoryBase.java:90) at javax.naming.spi.NamingManager.getObjectInstance(NamingManager.java:321) at org.apache.naming.NamingContext.lookup(NamingContext.java:839) at org.apache.naming.NamingContext.lookup(NamingContext.java:159) at org.apache.naming.NamingContext.lookup(NamingContext.java:827) at org.apache.naming.NamingContext.lookup(NamingContext.java:159) at org.apache.naming.NamingContext.lookup(NamingContext.java:827) at org.apache.naming.NamingContext.lookup(NamingContext.java:159) at org.apache.naming.NamingContext.lookup(NamingContext.java:827) at org.apache.naming.NamingContext.lookup(NamingContext.java:173) at org.apache.naming.SelectorContext.lookup(SelectorContext.java:163) at javax.naming.InitialContext.lookup(InitialContext.java:417) at org.springframework.jndi.JndiTemplate.lambda$lookup$0(JndiTemplate.java:156) at org.springframework.jndi.JndiTemplate.execute(JndiTemplate.java:91) at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:156) at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:178) at org.springframework.jndi.JndiLocatorSupport.lookup(JndiLocatorSupport.java:96) at org.springframework.jndi.JndiObjectLocator.lookup(JndiObjectLocator.java:114) at org.springframework.jndi.JndiObjectTargetSource.getTarget(JndiObjectTargetSource.java:140) ... 39 common frames omitted Caused by: java.lang.ClassNotFoundException: org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:264) at org.apache.naming.factory.ResourceFactory.getDefaultFactory(ResourceFactory.java:47) ... 58 common frames omitted
To use Apache JDBC datasource, you don't need to add any dependency but you have to change the default factory class to org.apache.tomcat.jdbc.pool.DataSourceFactory
.
You can do it in the resource declaration :
resource.setProperty("factory", "org.apache.tomcat.jdbc.pool.DataSourceFactory");
I will explain below where add this line.
To use DBCP 2 datasource a dependency is required:
<dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-dbcp</artifactId> <version>8.5.4</version> </dependency>
Of course, adapt the artifact version according to your Spring Boot Tomcat embedded version.
To use HikariCP, add the required dependency if not already present in your configuration (it may be if you rely on persistence starters of Spring Boot) such as :
<dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> <version>3.1.0</version> </dependency>
and specify the factory that goes with in the resource declaration:
resource.setProperty("factory", "com.zaxxer.hikari.HikariJNDIFactory");
Datasource configuration/declaration
You have to customize the bean that creates the TomcatServletWebServerFactory
instance.
Two things to do :
enabling the JNDI naming which is disabled by default
creating and add the JNDI resource(s) in the server context
For example with PostgreSQL and a DBCP 2 datasource, do that :
@Bean
public TomcatServletWebServerFactory tomcatFactory() {
return new TomcatServletWebServerFactory() {
@Override
protected TomcatWebServer getTomcatWebServer(org.apache.catalina.startup.Tomcat tomcat) {
tomcat.enableNaming();
return super.getTomcatWebServer(tomcat);
}
@Override
protected void postProcessContext(Context context) {
// context
ContextResource resource = new ContextResource();
resource.setName("jdbc/myJndiResource");
resource.setType(DataSource.class.getName());
resource.setProperty("driverClassName", "org.postgresql.Driver");
resource.setProperty("url", "jdbc:postgresql://hostname:port/dbname");
resource.setProperty("username", "username");
resource.setProperty("password", "password");
context.getNamingResources()
.addResource(resource);
}
};
}
Here the variants for Tomcat JDBC and HikariCP datasource.
In postProcessContext()
set the factory property as explained early for Tomcat JDBC ds :
@Override
protected void postProcessContext(Context context) {
ContextResource resource = new ContextResource();
//...
resource.setProperty("factory", "org.apache.tomcat.jdbc.pool.DataSourceFactory");
//...
context.getNamingResources()
.addResource(resource);
}
};
and for HikariCP :
@Override
protected void postProcessContext(Context context) {
ContextResource resource = new ContextResource();
//...
resource.setProperty("factory", "com.zaxxer.hikari.HikariDataSource");
//...
context.getNamingResources()
.addResource(resource);
}
};
Using/Injecting the datasource
You should now be able to lookup the JNDI ressource anywhere by using a standard InitialContext
instance :
InitialContext initialContext = new InitialContext();
DataSource datasource = (DataSource) initialContext.lookup("java:comp/env/jdbc/myJndiResource");
You can also use JndiObjectFactoryBean
of Spring to lookup up the resource :
JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
bean.setJndiName("java:comp/env/jdbc/myJndiResource");
bean.afterPropertiesSet();
DataSource object = (DataSource) bean.getObject();
To take advantage of the DI container you can also make the DataSource
a Spring bean :
@Bean(destroyMethod = "")
public DataSource jndiDataSource() throws IllegalArgumentException, NamingException {
JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
bean.setJndiName("java:comp/env/jdbc/myJndiResource");
bean.afterPropertiesSet();
return (DataSource) bean.getObject();
}
And so you can now inject the DataSource in any Spring beans such as :
@Autowired
private DataSource jndiDataSource;
Note that many examples on the internet seem to disable the lookup of the JNDI resource on startup :
bean.setJndiName("java:comp/env/jdbc/myJndiResource");
bean.setProxyInterface(DataSource.class);
bean.setLookupOnStartup(false);
bean.afterPropertiesSet();
But I think that it is helpless as it invokes just after afterPropertiesSet()
that does the lookup !
N-tier data applications are data applications that are separated into multiple tiers. Also called "distributed applications" and "multitier applications," n-tier applications separate processing into discrete tiers that are distributed between the client and the server. When you develop applications that access data, you should have a clear separation between the various tiers that make up the application.
A typical n-tier application includes a presentation tier, a middle tier, and a data tier. The easiest way to separate the various tiers in an n-tier application is to create discrete projects for each tier that you want to include in your application. For example, the presentation tier might be a Windows Forms application, whereas the data access logic might be a class library located in the middle tier. Additionally, the presentation layer might communicate with the data access logic in the middle tier through a service such as a service. Separating application components into separate tiers increases the maintainability and scalability of the application. It does this by enabling easier adoption of new technologies that can be applied to a single tier without the requirement to redesign the whole solution. In addition, n-tier applications typically store sensitive information in the middle-tier, which maintains isolation from the presentation tier.
Taken from Microsoft website.
if not (line.startswith("OK ") or line.strip() == "."):
print line
Superkey - An attribute or set of attributes that uniquely defines a tuple within a relation. However, a superkey may contain additional attributes that are not necessary for unique identification.
Candidate key - A superkey such that no proper subset is a superkey within the relation. So, basically has two properties: Each candidate key uniquely identifies tuple in the relation ; & no proper subset of the composite key has the uniqueness property.
Composite key - When a candidate key consists of more than one attribute.
Primary key - The candidate key chosen to identify tuples uniquely within the relation.
Alternate key - Candidate key that is not a primary key.
Foreign key - An attribute or set of attributes within a relation that matches the candidate key of some relation.
urllib2 does not verify server certificate by default. Check this documentation.
Edit: As pointed out in below comment, this is not true anymore for newer versions (seems like >= 2.7.9) of Python. Refer the below ANSWER
The thing you really want to do is wrap all child elements. In this case you should use an items control and not resort to horrible attached properties which you will end up having a million of for every property you wish to style.
<ItemsControl>
<!-- target the wrapper parent of the child with a style -->
<ItemsControl.ItemContainerStyle>
<Style TargetType="Control">
<Setter Property="Margin" Value="0 0 5 0"></Setter>
</Style>
</ItemsControl.ItemContainerStyle>
<!-- use a stack panel as the main container -->
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<!-- put in your children -->
<ItemsControl.Items>
<Label>Auto Zoom Reset?</Label>
<CheckBox x:Name="AutoResetZoom"/>
<Button x:Name="ProceedButton" Click="ProceedButton_OnClick">Next</Button>
<ComboBox SelectedItem="{Binding LogLevel }" ItemsSource="{Binding LogLevels}" />
</ItemsControl.Items>
</ItemsControl>
A simple technique is to put this somewhere in your index:
<div class="font_preload" style="opacity: 0">
<span style="font-family: 'myfontface#1font-family', Arial, sans-serif;"></span>
<span style="font-family: 'myfontface#2font-family', Arial, sans-serif;"></span>
...
</div>
Tested on Chrome 34, Safari 7 and FF 29 and IE 11
After a bitter almost 24 hours long run trying to make xdebug to work with Netbeans 8.0.2, I have found a solution that, I hope, will work for all Ubuntu and Ubuntu related stacks.
Problem number 1: PHP and xdebug versions must be compatible
Sometimes, if you're running a Linux setup and apt-get to install xdebug, it won't get you the proper xdebug version. In my case, I had the latest php version but an old xdebug version. That must be due to my current Xubuntu version. Software versions are dependent on repositories, which are dependent on the OS version you are running.
Solution: PHP has a neat extension manager called PECL. Follow the instructions given here to have it up and running. First, as pointed out by a member at the comments, you should install PHP's developer package in order to get PECL to work:
sudo apt-get install php5-dev
Then, using PECL, you'll be able to install the latest stable version of xdebug:
sudo pecl install php5-xdebug
Once you do it, the proper version of xdebug will be installed but not ready to use. After that, you'll need to enable it. I've seen many suggestions on how to do it, but the fact of the matter is that PHP needs some modules to be enabled both to the client and the server, in this case Apache. It seems that the best practice here is to use the built in method of enabling modules, called php5enmod. Usage is described here.
Problem number 2: Enable the module correctly
First, you'll need to go inside the /etc/php5 folder. In there, you'll find 3 folders, apache2, cli, and mods_available. The mods_available folder contains text files with instructions to activate a given module. The name convention is [module].ini. Take a look inside a few of them, see how they are set up.
Now you'll have to create your ini file inside mods_available folder. Create a file named xdebug.ini, and inside the file, paste this:
[xdebug]
zend_extension = /usr/lib/php5/20121212/xdebug.so
xdebug.remote_enable=on
xdebug.remote_handler=dbgp
xdebug.remote_mode=req
xdebug.remote_host=localhost
xdebug.remote_port=9000
Make sure that the directive [xdebug] is present, exactly like the example above. It is imperative for the module to work. In fact, just copy and paste the whole code, you'll be a happier person that way. :D
Note: the zend_extension path is very important. On this example it is pointing o the current version of the PHP engine, but you should first go to /usr/lib/php5 and make sure the folder that is named with numbers is the correct one. Adjust the name to whatever you see there, and while you're at it, check inside the folder to make sure the xdebug.so is really there. It should be, if you did everything right.
Now, with your xdebug.ini created, it's time to enable the module. To do that, open a console and type:
php5enmod xdebug
If everything went right, PHP created two links to this file, one inside /etc/php5/apache2/conf.d and other inside /etc/php5/cli/conf.d
Restart your Apache server and type this on the console:
php -v
You should get something like this:
PHP 5.5.9-1ubuntu4.6 (cli) (built: Feb 13 2015 19:17:11)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies
with Zend OPcache v7.0.3, Copyright (c) 1999-2014, by Zend Technologies
with Xdebug v2.3.1, Copyright (c) 2002-2015, by Derick Rethans
Which means the PHP client did read your xdebug.ini file and loaded the xdebug.so module. So far so good.
Now create a phpinfo script somewhere on your web server, and run it. This is what you should see, if everything went wright:
If you see this, Apache also loaded the module, and you are probably ready to go. Now let's see if Netbeans will debug correctly. Create a very simple script, add some variables, give them values, and set a break point on them. Now hit CTRL+F5, click on "step in" on your debugger panel, and see if you get something like this:
Remember to check Netbeans configuration for debugging, under tools/options/php. It should look something like this:
I hope this sheds some light on this rather obscure, confusing problem.
Best wishes!
The Bootstrap grid system has four classes:
xs (for phones)
sm (for tablets)
md (for desktops)
lg (for larger desktops)The classes above can be combined to create more dynamic and flexible layouts.
Tip: Each class scales up, so if you wish to set the same widths for xs and sm, you only need to specify xs.
OK, the answer is easy, but read on:
col-lg- stands for column large = 1200px
col-md- stands for column medium = 992px
col-xs- stands for column extra small = 768px
The pixel numbers are the breakpoints, so for example col-xs
is targeting the element when the window is smaller than 768px(likely mobile devices)...
I also created the image below to show how the grid system works, in this examples I use them with 3, like col-lg-6
to show you how the grid system work in the page, look at how lg
, md
and xs
are responsive to the window size:
IMHO the only 100% reliable way to test if you can write to a directory is to actually write to it and eventually catch exceptions.