barplot(data)
barplot(data, yaxp=c(0, max(data), 5))
yaxp=c(minY-axis, maxY-axis, Interval)
var message =/*[[${message}]]*/ 'defaultanyvalue';
Use two <input type=file>
elements instead, without the multiple
attribute.
Why not something like this?
It uses a combination of lists, iteration, and interpolation.
@mixin placeholder ($rules) {
@each $rule in $rules {
::-webkit-input-placeholder,
:-moz-placeholder,
::-moz-placeholder,
:-ms-input-placeholder {
#{nth($rule, 1)}: #{nth($rule, 2)};
}
}
}
$rules: (('border', '1px solid red'),
('color', 'green'));
@include placeholder( $rules );
I have my simple method which I have used in college.
line = "I have a nice day."
end = 1000
while end != 0:
line.replace(" ", " ")
end -= 1
This will replace every double space with a single space and will do it 1000 times. It means you can have 2000 extra spaces and will still work. :)
create table myTable
(
Column1 int not null,
Column2 int not null
)
GO
ALTER TABLE myTable
ADD PRIMARY KEY (Column1,Column2)
GO
Instead of
mount -o rw,remount /system/
use
mount -o rw,remount /system
mind the '/' at the end of the command. you ask why this matters? /system/ is the directory under /system while /system is the volume name.
Here's yet another method using Streams:
private static String toHexString(byte[] bytes) {
return IntStream.range(0, bytes.length)
.mapToObj(i -> String.format("%02X", bytes[i]))
.collect(Collectors.joining());
}
I have had an interesting issue wiht NoClassDefFoundError in JavaEE working with Liberty server. I was using IMS resource adapters and my server.xml had already resource adapter for imsudbJXA.rar. When I added new adapter for imsudbXA.rar, I would start getting this error for instance objects for DLIException, IMSConnectionSpec or SQLInteractionSpec. I could not figure why but I resolved it by creating new server.xml for my work using only imsudbXA.rar. I am sure using multiple resource adapters in server.xml is fine, I just had no time to look into that.
This approach also works with same hierarchy of Controller files:
$printReport = new PrintReportController;
$prinReport->getPrintReport();
Here is the solution: - Go to build settings - Search SWIFT_COMPILATION_MODE - If this is "Whole Module" for Release configuration then change it to "Incremental". - Archive now.
When you change the setting to "Incremental" the process succeeds.
I'm writing an answer to increase visibility to the actual syntax that solves the problem. Unfortunately, what someone might see as trivial can become a very significant headache to someone looking for a simple answer to a reasonable question.
Put the following into the file "Makefile".
MY_VAR := $(shell python -c 'import sys; print int(sys.version_info >= (2,5))')
all:
@echo MY_VAR IS $(MY_VAR)
The behavior you would like to see is the following (assuming you have recent python installed).
make
MY_VAR IS 1
If you copy and paste the above text into the Makefile, will you get this? Probably not. You will probably get an error like what is reported here:
makefile:4: *** missing separator. Stop
Why: Because although I personally used a genuine tab, Stack Overflow (attempting to be helpful) converts my tab into a number of spaces. You, frustrated internet citizen, now copy this, thinking that you now have the same text that I used. The make command, now reads the spaces and finds that the "all" command is incorrectly formatted. So copy the above text, paste it, and then convert the whitespace before "@echo" to a tab, and this example should, at last, hopefully, work for you.
Just an addition to the answers above.
If you want to execute a SQL with an "IN" statement you could do this:
ids_list = [1,2,3]
query = "SELECT id, name FROM user WHERE id IN %s"
args = [(ids_list,)] # Don't forget the "comma", to force the tuple
conn.execute(query, args)
Two points:
EDIT Watch out that if the length of list is one or zero this will raise an error!
You're able to get the current registry-url using docker info
:
...
Debug Mode (server): false
Registry: https://index.docker.io/v1/
Labels:
...
That's also the url you may use to run your self hosted-registry:
docker run -d -p 5000:5000 --name registry -e REGISTRY_PROXY_REMOTEURL=https://index.docker.io registry:2
Grep & use it right away:
$ echo $(docker info | grep -oP "(?<=Registry: ).*")
https://index.docker.io/v1/
I'd like to add df.values.tolist()
. (as long as you don't mind to get a column of lists rather than tuples)
import pandas as pd
import numpy as np
size = int(1e+07)
df = pd.DataFrame({'a': np.random.rand(size), 'b': np.random.rand(size)})
%timeit df.values.tolist()
1.47 s ± 38.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit list(zip(df.a,df.b))
1.92 s ± 131 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Problems only surface when I am I trying to give the first loaded content an active state
Does this mean that you want to add a class to the first button?
$('.o-links').click(function(e) { // ... }).first().addClass('O_Nav_Current');
instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:
CSS:
.image-area { width: 100%; height: auto; display: none; } .image-area:first-of-type { display: block; }
JavaScript:
var $slides = $('.image-area'), $btns = $('a.o-links'); $btns.on('click', function (e) { var i = $btns.removeClass('O_Nav_Current').index(this); $(this).addClass('O_Nav_Current'); $slides.filter(':visible').fadeOut(1000, function () { $slides.eq(i).fadeIn(1000); }); e.preventDefault(); }).first().addClass('O_Nav_Current');
Addition to @icksde and @Korah (thx both!)
When building the options with AJAX the document.ready may be triggered before the list is built, so
This doesn't work
$(document).ready(function() {
$("#gate").val('Gateway 2');
});
This does
A timeout does work but as @icksde says it's fragile (I did actually need 20ms in stead of 10ms). It's better to fit it inside the AJAX function like this:
$("#someObject").change(function() {
$.get("website/page.php", {parameters}, function(data) {
$("#gate").append("<option value='Gateway 2'">" + "Gateway 2" + "</option>");
$("#gate").val('Gateway 2');
}, "json");
});
Try this to read a file:
BufferedReader reader = null;
try {
File file = new File("sample-file.dat");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
you can just wrap it into another element and call html
after that:
$('<div><iframe width="854" height="480" src="http://www.youtube.com/embed/gYKqrjq5IjU?feature=oembed" frameborder="0" allowfullscreen></iframe></div>').html();
note that outerHTML
doesn't exist on older browsers but innerHTML
still does (it doesn't exist for example in ff < 11 while it's still used on many older computers)
You just can't be sure on a Unix system, that a .txt file truly is a text file. Your best bet is to use "file". Maybe try using:
file -ib "$file"
Then you can use a list of MIME types to match against or parse the first part of the MIME where you get stuff like "text", "application", etc.
Extending the accepted answer for a common usecase. In particular:
View the circles at a natural aspect ratio.
Automatically extend the axes limits to include the newly plotted circles.
Self-contained example:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.add_patch(plt.Circle((0, 0), 0.2, color='r', alpha=0.5))
ax.add_patch(plt.Circle((1, 1), 0.5, color='#00ffff', alpha=0.5))
ax.add_artist(plt.Circle((1, 0), 0.5, color='#000033', alpha=0.5))
#Use adjustable='box-forced' to make the plot area square-shaped as well.
ax.set_aspect('equal', adjustable='datalim')
ax.plot() #Causes an autoscale update.
plt.show()
Note the difference between ax.add_patch(..)
and ax.add_artist(..)
: of the two, only the former makes autoscaling machinery take the circle into account (reference: discussion), so after running the above code we get:
See also: set_aspect(..)
documentation.
You can use the MATCH_PARENT constant or its numeric value -1.
There are already so many good answers on this thread! I am going to post this to help anybody trying to do this automatically! To automatically remove unused imports for the whole project this article was really helpful to me.
In the article the author explains it like this:
Make a stand alone tslint file that has the following in it:
{
"extends": ["tslint-etc"],
"rules": {
"no-unused-declaration": true
}
}
Then run the following command to fix the imports:
tslint --config tslint-imports.json --fix --project .
Consider fixing any other errors it throws. (I did)
Then check the project works by building it:
ng build
or
ng build name_of_project --configuration=production
End: If it builds correctly, you have successfully removed imports automatically!
NOTE: This only removes unnecessary imports. It does not provide the other features that VS Code does when using one of the commands previously mentioned.
I have done a custom component tried two way binding
Mycomponent:
<input type="checkbox" [(ngModel)]="model" >
_model: boolean;
@Output() checked: EventEmitter<boolean> = new EventEmitter<boolean>();
@Input('checked')
set model(checked: boolean) {
this._model = checked;
this.checked.emit(this._model);
console.log('@Input(setmodel'+checked);
}
get model() {
return this._model;
}
strange thing is this works
<mycheckbox [checked]="isChecked" (checked)="isChecked = $event">
while this wont
<mycheckbox [(checked)]="isChecked">
With EF or LINQ to SQL:
var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();
With LINQ to Objects I suggest to use morelinq extension MaxBy
(get morelinq from nuget):
var item = items.MaxBy(i => i.Value);
Edit Web Config for each crystaldecisions file version make it equal the same version off the dll file (from rght click on it and select from properties from solution explorer ) Eg. crystaldecisions.reportappserver.commlayer.dll --> 13.0.2000.0 after upgrade crystal report to CRforVS_13_0_21 edit it to ---> 13.0.35.00.0
You're going to have to either use JS or write a function/method in whatever non-markup language you're using to do this. For instance you could write something that will save the status to a cookie or session variable then check for it on page load. If you want to do it without reloading the page then JS is going to be your only option.
you don't have to use regex. In your favourite language, split on spaces, go over the splitted words, check for cat and mat. eg in Python
>>> for line in open("file"):
... g=0;f=0
... s = line.split()
... for item in s:
... if item =="cat": f=1
... if item =="mat": g=1
... if (g,f)==(1,1): print "found: " ,line.rstrip()
found: The cat slept on the mat in front of the fire.
found: At 5:00 pm, I found the cat scratching the wool off the mat.
xfs_mkfile 10240m 10Gigfile
fallocate -l 10G 10Gigfile
mkfile 10240m 10Gigfile
prealloc 10Gigfile 10737418240
Try mkfile <size>
myfile as an alternative of dd
. With the -n
option the size is noted, but disk blocks aren't allocated until data is written to them. Without the -n
option, the space is zero-filled, which means writing to the disk, which means taking time.
mkfile is derived from SunOS and is not available everywhere. Most Linux systems have xfs_mkfile
which works exactly the same way, and not just on XFS file systems despite the name. It's included in xfsprogs (for Debian/Ubuntu) or similar named packages.
Most Linux systems also have fallocate
, which only works on certain file systems (such as btrfs, ext4, ocfs2, and xfs), but is the fastest, as it allocates all the file space (creates non-holey files) but does not initialize any of it.
pip is not give permission so can't do pip install.Try below command.
apt-get install python-virtualenv
I answered a similar question for VB.NET
. It shouldn't however be too hard to convert. You embedd the DLL's
into your Ressource
folder and on the first usage, the
AppDomain.CurrentDomain.AssemblyResolve
event gets fired.
If you want to reference it during development, just add a normal DLL
reference to your project.
To answer the WHY in your question:
Because the equality operator can only be applied to simple variable types, such as float
s, int
s, or char
s, and not to more sophisticated types, such as structures or arrays.
To determine if two strings are equal, you must explicitly compare the two character strings character by character.
This works on jdk1.8.0_65
wsimport -J-Djavax.xml.accessExternalSchema=all -keep -verbose https://your webservice url?wsdl
SELECT field1 FROM OPENQUERY
([NameOfLinkedSERVER],
'SELECT field1 FROM TABLENAME')
WHERE field1=@someParameter T1
INNER JOIN MYSQLSERVER.DATABASE.DBO.TABLENAME
T2 ON T1.PK = T2.PK
Arrays.stream(ints).forEach(list::add);
This basically does 1 (iterate over the array) with 2 (using Java 8). (with 1 and 2 referring to your original question)
No one seems to have mentioned about the negative infinity explicitly, so I think I should add it.
For negative infinity:
-math.inf
For positive infinity (just for the sake of completeness):
math.inf
AVD cant find SDK root, possibly because they are in different directories.Set your environment variables as shown in the screenshot below:
While Guffa's answer works in many situations, in some cases you may not want the left and/or right pieces of padding to be the parent of the center div. In these cases, you can use a block formatting context on the center and float the padding divs left and right. Here's the code
The HTML:
<div class="container">
<div class="left"></div>
<div class="right"></div>
<div class="center"></div>
</div>
The CSS:
.container {
width: 100px;
height: 20px;
}
.left, .right {
width: 20px;
height: 100%;
float: left;
background: black;
}
.right {
float: right;
}
.center {
overflow: auto;
height: 100%;
background: blue;
}
I feel that this element hierarchy is more natural when compared to nested nested divs, and better represents what's on the page. Because of this, borders, padding, and margin can be applied normally to all elements (ie: this 'naturality' goes beyond style and has ramifications).
Note that this only works on divs and other elements that share its 'fill 100% of the width by default' property. Inputs, tables, and possibly others will require you to wrap them in a container div and add a little more css to restore this quality. If you're unlucky enough to be in that situation, contact me and I'll dig up the css.
jsfiddle here: jsfiddle.net/RgdeQ
Enjoy!
I dont know if you want to achieve that in js or java, in js the simplest way to get the unix timestampt (this is time in seconds from 1/1/1970) it's as follows:
var myDate = new Date();
console.log(+myDate); // +myDateObject give you the unix from that date
let's understand the difference between throw and throw ex. I heard that in many .net interviews this common asked is being asked.
Just to give an overview of these two terms, throw and throw ex are both used to understand where the exception has occurred. Throw ex rewrites the stack trace of exception irrespective where actually has been thrown.
Let's understand with an example.
Let's understand first Throw.
static void Main(string[] args) {
try {
M1();
} catch (Exception ex) {
Console.WriteLine(" -----------------Stack Trace Hierarchy -----------------");
Console.WriteLine(ex.StackTrace.ToString());
Console.WriteLine(" ---------------- Method Name / Target Site -------------- ");
Console.WriteLine(ex.TargetSite.ToString());
}
Console.ReadKey();
}
static void M1() {
try {
M2();
} catch (Exception ex) {
throw;
};
}
static void M2() {
throw new DivideByZeroException();
}
output of the above is below.
shows complete hierarchy and method name where actually the exception has thrown.. it is M2 -> M2. along with line numbers
Secondly.. lets understand by throw ex. Just replace throw with throw ex in M2 method catch block. as below.
output of throw ex code is as below..
You can see the difference in the output.. throw ex just ignores all the previous hierarchy and resets stack trace with line/method where throw ex is written.
new syntax
<%= form_for :user, url: custom_user_path, method: :post do |f|%>
<%end%>
This already has good answers for most purposes, but I'll add mine which is more specific.
In English, normally when we alphabetise, we ignore the word "the" at the beginning of a phrase. So "The United States" would be ordered under "U" and not "T".
This does that for you.
It would probably be best to put these in categories.
// Sort an array of NSStrings alphabetically, ignoring the word "the" at the beginning of a string.
-(NSArray*) sortArrayAlphabeticallyIgnoringThes:(NSArray*) unsortedArray {
NSArray * sortedArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(NSString* a, NSString* b) {
//find the strings that will actually be compared for alphabetical ordering
NSString* firstStringToCompare = [self stringByRemovingPrecedingThe:a];
NSString* secondStringToCompare = [self stringByRemovingPrecedingThe:b];
return [firstStringToCompare compare:secondStringToCompare];
}];
return sortedArray;
}
// Remove "the"s, also removes preceding white spaces that are left as a result. Assumes no preceding whitespaces to start with. nb: Trailing white spaces will be deleted too.
-(NSString*) stringByRemovingPrecedingThe:(NSString*) originalString {
NSString* result;
if ([[originalString substringToIndex:3].lowercaseString isEqualToString:@"the"]) {
result = [[originalString substringFromIndex:3] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}
else {
result = originalString;
}
return result;
}
Here's a rather simple solution:
In the controller we return our errors like this:
if (!ModelState.IsValid)
{
return Json(new { success = false, errors = ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage).ToList() }, JsonRequestBehavior.AllowGet);
}
Here's some of the client script:
function displayValidationErrors(errors)
{
var $ul = $('div.validation-summary-valid.text-danger > ul');
$ul.empty();
$.each(errors, function (idx, errorMessage) {
$ul.append('<li>' + errorMessage + '</li>');
});
}
That's how we handle it via ajax:
$.ajax({
cache: false,
async: true,
type: "POST",
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
var isSuccessful = (data['success']);
if (isSuccessful) {
$('#partial-container-steps').html(data['view']);
initializePage();
}
else {
var errors = data['errors'];
displayValidationErrors(errors);
}
}
});
Also, I render partial views via ajax in the following way:
var view = this.RenderRazorViewToString(partialUrl, viewModel);
return Json(new { success = true, view }, JsonRequestBehavior.AllowGet);
RenderRazorViewToString method:
public string RenderRazorViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View,
ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
SignTool is available as part of the Windows SDK (which comes with Visual Studio Community 2015). Make sure to select the "ClickOnce Publishing Tools" from the feature list during the installation of Visual Studio 2015 to get the SignTool.
Once Visual Studio is installed you can run the signtool
command from the Visual Studio Command Prompt.
By default (on Windows 10) the SignTool will be installed in:
C:\Program Files (x86)\Windows Kits\10\bin\x86\signtool.exe
I'm fashionably late to this question, but I think it's worth a clearer response than the accepted one (which is correct, but doesn't emphasize the actual important part, which you need to deduce yourself).
In the parent POM, the main difference between the <dependencies>
and <dependencyManagement>
is this:
Artifacts specified in the <dependencies>
section will ALWAYS be included as a dependency of the child module(s).
Artifacts specified in the <dependencyManagement>
section, will only be included in the child module if they were also specified in the <dependencies>
section of the child module itself. Why is it good you ask? Because you specify the version and/or scope in the parent, and you can leave them out when specifying the dependencies in the child POM. This can help you use unified versions for dependencies for child modules, without specifying the version in each child module.
Look no more for IP addresses not being set in the expected header. Just do the following to inspect the whole server variables and figure out which one is suitable for your case:
print_r($_SERVER);
select name, max(value)
from out_pumptable
group by name
Declare dateToday variable and use Date() function to set it.. then use that variable to assign to minDate which is parameter of datepicker.
var dateToday = new Date();
$(function() {
$( "#datepicker" ).datepicker({
numberOfMonths: 3,
showButtonPanel: true,
minDate: dateToday
});
});
That's it... Above answer was really helpful... keep it up guys..
You can map() arrays, but there is no such operation for Maps. The solution from Dr. Axel Rauschmayer:
Example:
let map0 = new Map([
[1, "a"],
[2, "b"],
[3, "c"]
]);
const map1 = new Map(
[...map0]
.map(([k, v]) => [k * 2, '_' + v])
);
resulted in
{2 => '_a', 4 => '_b', 6 => '_c'}
To disable one button, at dialog open:
$("#InspectionExistingFacility").dialog({
autoOpen: false, modal: true, width: 700, height: 550,
open: function (event, ui) {
$("#InspectionExistingFacility").parent().find(":button:contains('Next')").prop("disabled", true).addClass("ui-state-disabled");
},
show: { effect: "fade", duration: 600 }, hide: { effect: "slide", duration: 1000 },
buttons: { 'Next step': function () { }, Close: function () { $(this).dialog("close"); } }
});
Memoization effectively refers to remembering ("memoization" ? "memorandum" ? to be remembered) results of method calls based on the method inputs and then returning the remembered result rather than computing the result again. You can think of it as a cache for method results. For further details, see page 387 for the definition in Introduction To Algorithms (3e), Cormen et al.
A simple example for computing factorials using memoization in Python would be something like this:
factorial_memo = {}
def factorial(k):
if k < 2: return 1
if k not in factorial_memo:
factorial_memo[k] = k * factorial(k-1)
return factorial_memo[k]
You can get more complicated and encapsulate the memoization process into a class:
class Memoize:
def __init__(self, f):
self.f = f
self.memo = {}
def __call__(self, *args):
if not args in self.memo:
self.memo[args] = self.f(*args)
#Warning: You may wish to do a deepcopy here if returning objects
return self.memo[args]
Then:
def factorial(k):
if k < 2: return 1
return k * factorial(k - 1)
factorial = Memoize(factorial)
A feature known as "decorators" was added in Python 2.4 which allow you to now simply write the following to accomplish the same thing:
@Memoize
def factorial(k):
if k < 2: return 1
return k * factorial(k - 1)
The Python Decorator Library has a similar decorator called memoized
that is slightly more robust than the Memoize
class shown here.
You can do injection on Directives, and it looks just like it does everywhere else.
app.directive('changeIt', ['myData', function(myData){
return {
restrict: 'C',
link: function (scope, element, attrs) {
scope.name = myData.name;
}
}
}]);
Update 2020 - CLI
As @mix3d pointed out you can just run a command where file.js
is your file and someFunction
is your function optionally followed by parameters separated with spaces
npx run-func file.js someFunction "just some parameter"
That's it.
file.js
called in the example above
const someFunction = (param) => console.log('Welcome, your param is', param)
// exporting is crucial
module.exports = { someFunction }
More detailed description
Run directly from CLI (global)
Install
npm i -g run-func
Usage i.e. run function "init", it must be exported, see the bottom
run-func db.js init
or
Run from package.json script (local)
Install
npm i -S run-func
Setup
"scripts": {
"init": "run-func db.js init"
}
Usage
npm run init
Params
Any following arguments will be passed as function parameters init(param1, param2)
run-func db.js init param1 param2
Important
the function (in this example init
) must be exported in the file containing it
module.exports = { init };
or ES6 export
export { init };
Java script plays on browser where java code is server side thing so you can't simply do this.
What you can do is submit the calculated variable from javascript to server by form-submission, or using URL parameter or using AJAX calls and then you can make it available on server
HTML
<input type="hidden" id="hiddenField"/>
make sure this fields lays under <form>
Javascript
document.getElementById("hiddenField").value=yourCalculatedVariable;
on server you would get this as a part of request
here is my solution:
List<String> list1 = new List<String>();
List<String> list2 = new List<String>();
List<String> exceptValue = new List<String>();
foreach(String L1 in List1)
{
if(!List2.Contains(L1)
{
exceptValue.Add(L1);
}
}
foreach(String L2 in List2)
{
if(!List1.Contains(L2)
{
exceptValue.Add(L2);
}
}
You need to use the change directory command 'cd' to change directory
cd C:\Users\MyName\Desktop
you can use cd \d
to change the drive as well.
link for additional resources http://ss64.com/nt/cd.html
You can use line-height: 50px;
, you won't need vertical-align: middle;
there.
The above will fail if you've multiple lines, so in that case you can wrap your text using span
and than use display: table-cell;
and display: table;
along with vertical-align: middle;
, also don't forget to use width: 100%;
for #abc
#abc{
font:Verdana, Geneva, sans-serif;
font-size:18px;
text-align:left;
background-color:#0F0;
height:50px;
display: table;
width: 100%;
}
#abc span {
vertical-align:middle;
display: table-cell;
}
Another solution I can think of here is to use transform
property with translateY()
where Y
obviously stands for Y Axis. It's pretty straight forward... All you need to do is set the elements position to absolute
and later position 50%
from the top
and translate from it's axis with negative -50%
div {
height: 100px;
width: 100px;
background-color: tomato;
position: relative;
}
p {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
Note that this won't be supported on older browsers, for example IE8, but you can make IE9 and other older browser versions of Chrome and Firefox by using -ms, -moz
and -webkit
prefixes respectively.
For more information on transform
, you can refer here.
HTML5 spec:
http://www.w3.org/TR/html5/forms.html#enabling-and-disabling-form-controls:-the-disabled-attribute :
The checked content attribute is a boolean attribute
http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes :
The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.
If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.
Conclusion:
The following are valid, equivalent and true:
<input type="text" disabled />
<input type="text" disabled="" />
<input type="text" disabled="disabled" />
<input type="text" disabled="DiSaBlEd" />
The following are invalid:
<input type="text" disabled="0" />
<input type="text" disabled="1" />
<input type="text" disabled="false" />
<input type="text" disabled="true" />
The absence of the attribute is the only valid syntax for false:
<input type="text" />
Recommendation
If you care about writing valid XHTML, use disabled="disabled"
, since <input disabled>
is invalid and other alternatives are less readable. Else, just use <input disabled>
as it is shorter.
May I suggest Node ORM?
https://github.com/dresende/node-orm2
There's documentation on the Readme, supports MySQL, PostgreSQL and SQLite.
MongoDB is available since version 2.1.x (released in July 2013)
UPDATE: This package is no longer maintained, per the project's README. It instead recommends bookshelf and sequelize
I would checkout the remote file from the "master" (the remote/origin repository) like this:
git checkout master <FileWithPath>
Example: git checkout master components/indexTest.html
Try reducing the range of the for loop to range(len(a)-1)
:
a = [0,1,2,3]
b = []
for i in range(len(a)-1):
b.append(a[i]+a[i+1])
print(b)
This can also be written as a list comprehension:
b = [a[i] + a[i+1] for i in range(len(a)-1)]
print(b)
In HTML only:
<label>
<input type="file" name="input-name" style="display: none;" />
<span>Select file</span>
</label>
Edit: I hadn't tested this in Blink, it actually doesn't work with a <button>
, but it should work with most other elements–at least in recent browsers.
Check this fiddle with the code above.
I'm doing this exact thing, but you need to do some kind of code generation for this to work.
In my solution, I added a project "EnumeratedTypes". This is a console application which gets all of the values from the database and constructs the enums from them. Then it saves all of the enums to an assembly.
The enum generation code is like this:
// Get the current application domain for the current thread
AppDomain currentDomain = AppDomain.CurrentDomain;
// Create a dynamic assembly in the current application domain,
// and allow it to be executed and saved to disk.
AssemblyName name = new AssemblyName("MyEnums");
AssemblyBuilder assemblyBuilder = currentDomain.DefineDynamicAssembly(name,
AssemblyBuilderAccess.RunAndSave);
// Define a dynamic module in "MyEnums" assembly.
// For a single-module assembly, the module has the same name as the assembly.
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(name.Name,
name.Name + ".dll");
// Define a public enumeration with the name "MyEnum" and an underlying type of Integer.
EnumBuilder myEnum = moduleBuilder.DefineEnum("EnumeratedTypes.MyEnum",
TypeAttributes.Public, typeof(int));
// Get data from database
MyDataAdapter someAdapter = new MyDataAdapter();
MyDataSet.MyDataTable myData = myDataAdapter.GetMyData();
foreach (MyDataSet.MyDataRow row in myData.Rows)
{
myEnum.DefineLiteral(row.Name, row.Key);
}
// Create the enum
myEnum.CreateType();
// Finally, save the assembly
assemblyBuilder.Save(name.Name + ".dll");
My other projects in the solution reference this generated assembly. As a result, I can then use the dynamic enums in code, complete with intellisense.
Then, I added a post-build event so that after this "EnumeratedTypes" project is built, it runs itself and generates the "MyEnums.dll" file.
By the way, it helps to change the build order of your project so that "EnumeratedTypes" is built first. Otherwise, once you start using your dynamically generated .dll, you won't be able to do a build if the .dll ever gets deleted. (Chicken and egg kind of problem -- your other projects in the solution need this .dll to build properly, and you can't create the .dll until you build your solution...)
I got most of the above code from this msdn article.
Hope this helps!
I tried to copy an xml file from one location to another. Here is my code:
public void SaveStockInfoToAnotherFile()
{
string sourcePath = @"C:\inetpub\wwwroot";
string destinationPath = @"G:\ProjectBO\ForFutureAnalysis";
string sourceFileName = "startingStock.xml";
string destinationFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xml"; // Don't mind this. I did this because I needed to name the copied files with respect to time.
string sourceFile = System.IO.Path.Combine(sourcePath, sourceFileName);
string destinationFile = System.IO.Path.Combine(destinationPath, destinationFileName);
if (!System.IO.Directory.Exists(destinationPath))
{
System.IO.Directory.CreateDirectory(destinationPath);
}
System.IO.File.Copy(sourceFile, destinationFile, true);
}
Then I called this function inside a timer_elapsed function of certain interval which I think you don't need to see. It worked. Hope this helps.
Don't know if this has been solved yet but I was getting similar problems with Anaconda python 3.7.3 and Idle on Windows 10. Fixed it by adding:
<path>\Anaconda3
<path>\Anaconda3\scripts
<path>\Anaconda3\Library\bin
to the PATH variable.
This code first compares x and 0 and then decrements x. (Also said in the first answer: You're post-decrementing x and then comparing x and 0 with the >
operator.) See the output of this code:
9 8 7 6 5 4 3 2 1 0
We now first compare and then decrement by seeing 0 in the output.
If we want to first decrement and then compare, use this code:
#include <stdio.h>
int main(void)
{
int x = 10;
while( --x> 0 ) // x goes to 0
{
printf("%d ", x);
}
return 0;
}
That output is:
9 8 7 6 5 4 3 2 1
For SSMS 18, I found the files at:
C:\Users\YourUserName\Documents\Visual Studio 2017\Backup Files\Solution1
For SSMS 17, It was used to be at:
C:\Users\YourUserName\Documents\Visual Studio 2015\Backup Files\Solution1
If you have the same method name in two different classes and you just want to run one of them, this works:
pytest tests.py -k 'TestClassName and test_method_name'
You can do it by javascript on client side or using some regex validator on the textbox.
script type="text/javascript" language="javascript">
function validateNumbersOnly(e) {
var unicode = e.charCode ? e.charCode : e.keyCode;
if ((unicode == 8) || (unicode == 9) || (unicode > 47 && unicode < 58)) {
return true;
}
else {
window.alert("This field accepts only Numbers");
return false;
}
}
</script>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator6" runat="server" Display="None" ErrorMessage="Accepts only numbers." ControlToValidate="TextBox1" ValidationExpression="^[0-9]*$" Text="*"></asp:RegularExpressionValidator>
In our databases we use an enum that ensures we pass it either TRUE or FALSE. If you do it either of the first two ways it is too easy to either start adding new meaning to the integer without going through a proper design, or ending up with that char field having Y, y, N, n, T, t, F, f values and having to remember which section of code uses which table and which version of true it is using.
Does using .live work for you?
$("#my-button").live("click", function(){ alert("yay!"); });
EDIT
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
Check if you have something configured inside the config file /application/config/config.php
e.g.
$config['base_url'] = 'http://example.com/';
In config.inc.php
in the top-level directory, set
$cfg['DefaultLang'] = 'en-utf-8'; // Language if no other language is recognized
// or
$cfg['Lang'] = 'en-utf-8'; // Force this language for all users
If Lang
isn't set, you should be able to select the language in the initial welcome screen, and the language your browser prefers should be preselected there.
Swift 5/iOS 13
To change color of title in controller:
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
Python with 1 stack and no flag:
def postorderTraversal(self, root):
ret = []
if not root:
return ret
stack = [root]
current = None
while stack:
previous = current
current = stack.pop()
if previous and ((previous is current) or (previous is current.left) or (previous is current.right)):
ret.append(current.val)
else:
stack.append(current)
if current.right:
stack.append(current.right)
if current.left:
stack.append(current.left)
return ret
And what is better is with similar statements, in order traversal works too
def inorderTraversal(self, root):
ret = []
if not root:
return ret
stack = [root]
current = None
while stack:
previous = current
current = stack.pop()
if None == previous or previous.left is current or previous.right is current:
if current.right:
stack.append(current.right)
stack.append(current)
if current.left:
stack.append(current.left)
else:
ret.append(current.val)
return ret
This:
print "\n"
is printing out two \n
characters -- the one you tell it to, and the one that Python prints out at the end of any line which doesn't end with a ,
like you use in print a,
. Simply use
print
instead.
FileInfo.Length
will return the length of file, in bytes (not size on disk), so this is what you are looking for, I think.
Use the df command:
df -h
It registers the driver; something of the form:
public class SomeDriver implements Driver {
static {
try {
DriverManager.registerDriver(new SomeDriver());
} catch (SQLException e) {
// TODO Auto-generated catch block
}
}
//etc: implemented methods
}
SELECT name, create_date, modify_date
FROM sys.objects
WHERE type = 'P'
ORDER BY modify_date DESC
The type
for a function is FN
rather than P
for procedure. Or you can filter on the name column.
You had better use find_library command instead of link_directories. Concretely speaking there are two ways:
designate the path within the command
find_library(NAMES gtest PATHS path1 path2 ... pathN)
set the variable CMAKE_LIBRARY_PATH
set(CMAKE_LIBRARY_PATH path1 path2)
find_library(NAMES gtest)
the reason is as flowings:
Note This command is rarely necessary and should be avoided where there are other choices. Prefer to pass full absolute paths to libraries where possible, since this ensures the correct library will always be linked. The find_library() command provides the full path, which can generally be used directly in calls to target_link_libraries(). Situations where a library search path may be needed include: Project generators like Xcode where the user can switch target architecture at build time, but a full path to a library cannot be used because it only provides one architecture (i.e. it is not a universal binary).
Libraries may themselves have other private library dependencies that expect to be found via RPATH mechanisms, but some linkers are not able to fully decode those paths (e.g. due to the presence of things like $ORIGIN).
If a library search path must be provided, prefer to localize the effect where possible by using the target_link_directories() command rather than link_directories(). The target-specific command can also control how the search directories propagate to other dependent targets.
Something like this might help (taken from a working app).
#include <memory>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
struct thread_pool {
typedef std::unique_ptr<boost::asio::io_service::work> asio_worker;
thread_pool(int threads) :service(), service_worker(new asio_worker::element_type(service)) {
for (int i = 0; i < threads; ++i) {
auto worker = [this] { return service.run(); };
grp.add_thread(new boost::thread(worker));
}
}
template<class F>
void enqueue(F f) {
service.post(f);
}
~thread_pool() {
service_worker.reset();
grp.join_all();
service.stop();
}
private:
boost::asio::io_service service;
asio_worker service_worker;
boost::thread_group grp;
};
You can use it like this:
thread_pool pool(2);
pool.enqueue([] {
std::cout << "Hello from Task 1\n";
});
pool.enqueue([] {
std::cout << "Hello from Task 2\n";
});
Keep in mind that reinventing an efficient asynchronous queuing mechanism is not trivial.
Boost::asio::io_service is a very efficient implementation, or actually is a collection of platform-specific wrappers (e.g. it wraps I/O completion ports on Windows).
I'm late to the party, but searching for the correct way to do it I came across this page it was one of the top Google search returns, so I will like to share my view on the problem, which I consider it to be up to date at the time of writing this post (beginning of 2017). From PHP 7.1.0 the mcrypt_decrypt
and mcrypt_encrypt
is going to be deprecated, so building future proof code should use openssl_encrypt and openssl_decrypt
You can do something like:
$string_to_encrypt="Test";
$password="password";
$encrypted_string=openssl_encrypt($string_to_encrypt,"AES-128-ECB",$password);
$decrypted_string=openssl_decrypt($encrypted_string,"AES-128-ECB",$password);
Important: This uses ECB mode, which isn't secure. If you want a simple solution without taking a crash course in cryptography engineering, don't write it yourself, just use a library.
You can use any other chipper methods as well, depending on your security need. To find out the available chipper methods please see the openssl_get_cipher_methods function.
I'm using zsh on my Mac, what worked for me is at first install pipenv
pip3 install --user pipenv
Then I changed the PATH in the ~/.zshrc
vi ~/.zshrc
In the editor press i to insert your text:
export PATH="/Users/yourUser/Library/Python/3.9/bin:$PATH"
Press esc and then write :wq! Close the terminal and re-open it. And finally write pipenv
This way worked for me using macOS BigSur 11.1
ALL_SOURCE describes the text source of the stored objects accessible to the current user.
Here is one of the solution
select * from ALL_SOURCE where text like '%some string%';
The trick here is that the ToolTip control is an extender control, which means that it will extend the set of properties for other controls on the form. Behind the scenes this is achieved by generating code like in Svetlozar's answer. There are other controls working in the same manner (such as the HelpProvider
).
Converting from java.lang.Object
directly to ArrayList<T>
which has elements of T is not recommended as it can lead to casting Exceptions. The recommended way is to first convert to a primitive array of T
and then use Arrays.asList(T[])
One of the ways how you get entity from a java javax.ws.rs.core.Response
is as follows -
T[] t_array = response.readEntity(object);
ArrayList<T> t_arraylist = Arrays.asList(t_array);
You will still get Unchecked cast warnings.
<input type="checkbox" id="something" />
$("#something").click( function(){
if( $(this).is(':checked') ) alert("checked");
});
Edit: Doing this will not catch when the checkbox changes for other reasons than a click, like using the keyboard. To avoid this problem, listen to change
instead of click
.
For checking/unchecking programmatically, take a look at Why isn't my checkbox change event triggered?
Try this
df = pd.read_csv("rating-data.tsv",sep='\t')
df.head()
You actually need to fix the sep parameter.
There is no such thing as a read-only drop-down. What you could do is reset it to the first value manually after each change.
$("select").change(function(event) {
$(this).val($(this).find("option").first().val());
});
Create a table layout panel with two columns in your form and name it tlpFields
.
Then, simply add new control to table layout panel (in this case I added 5 labels in column-1 and 5 textboxes in column-2).
tlpFields.RowStyles.Clear(); //first you must clear rowStyles
for (int ii = 0; ii < 5; ii++)
{
Label l1= new Label();
TextBox t1 = new TextBox();
l1.Text = "field : ";
tlpFields.Controls.Add(l1, 0, ii); // add label in column0
tlpFields.Controls.Add(t1, 1, ii); // add textbox in column1
tlpFields.RowStyles.Add(new RowStyle(SizeType.Absolute,30)); // 30 is the rows space
}
Finally, run the code.
As a late corolloary to the earlier answers here, you probably end up in situations where you want some but not all variables to be interpolated. You can solve that by using backslashes to escape dollar signs and backticks; or you can put the static text in a variable.
Name='Rich Ba$tard'
dough='$$$dollars$$$'
cat <<____HERE
$Name, you can win a lot of $dough this week!
Notice that \`backticks' need escaping if you want
literal text, not `pwd`, just like in variables like
\$HOME (current value: $HOME)
____HERE
Demo: https://ideone.com/rMF2XA
Note that any of the quoting mechanisms -- \____HERE
or "____HERE"
or '____HERE'
-- will disable all variable interpolation, and turn the here-document into a piece of literal text.
A common task is to combine local variables with script which should be evaluated by a different shell, programming language, or remote host.
local=$(uname)
ssh -t remote <<:
echo "$local is the value from the host which ran the ssh command"
# Prevent here doc from expanding locally; remote won't see backslash
remote=\$(uname)
# Same here
echo "\$remote is the value from the host we ssh:ed to"
:
For example,
package main
func main() {
mymap := make(map[int]string)
keys := make([]int, 0, len(mymap))
for k := range mymap {
keys = append(keys, k)
}
}
To be efficient in Go, it's important to minimize memory allocations.
debugPrint()
(and CustomDebugStringConvertible
protocol)!Don't forget about debugPrint()
which works like print()
but most suitable for debugging.
Examples:
print("Hello World!")
becomes Hello World
debugPrint("Hello World!")
becomes "Hello World"
(Quotes!)print(1..<6)
becomes 1..<6
debugPrint(1..<6)
becomes Range(1..<6)
Any class can customize their debug string representation via CustomDebugStringConvertible
protocol.
In the new rspec
expect
syntax this would be:
expect(subject).to receive(:bar).with("an argument I want")
When you create a cookie via PHP die Default Value is 0, from the manual:
If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes)
Otherwise you can set the cookies lifetime in seconds as the third parameter:
http://www.php.net/manual/en/function.setcookie.php
But if you mean to get the remaining lifetime of an already existing cookie, i fear that, is not possible (at least not in a direct way).
Although it's not regex, you can use the function validate_phone()
from the Python library DataPrep to validate US phone numbers. Install it with pip install dataprep
.
>>> from dataprep.clean import validate_phone
>>> df = pd.DataFrame({'phone': ['1-234-567-8901', '1-234-567-8901 x1234',
'1-234-567-8901 ext1234', '1 (234) 567-8901', '1.234.567.8901',
'1/234/567/8901', 12345678901, '12345678', '123-456-78987']})
>>> validate_phone(df['phone'])
0 True
1 True
2 True
3 True
4 True
5 True
6 True
7 False
8 False
Name: phone, dtype: bool
Table cells don't respect margin, but you could use transparent borders instead:
div {
display: table-cell;
border: 5px solid transparent;
}
Note: you can't use percentages here... :(
Using text nodes in jquery is a particularly delicate endeavour and most operations are made to skip them altogether.
Instead of going through the trouble of carefully avoiding the wrong nodes, why not just wrap whatever you need to replace inside a <span>
for instance:
<td><span class="replaceme">8: Tap on APN and Enter <B>www</B>.</span></td>
Then:
$('.replaceme').html('Whatever <b>HTML</b> you want here.');
The motivation is to write code that doesn't depend explicitly on Spring. That way, if you choose to switch containers, you don't have to rewrite any code.
Think of the container as something is invisible to your code, magically providing for its needs, without being asked.
Dependency injection is a counterpoint to the "service locator" pattern. If you are going to lookup dependencies by name, you might as well get rid of the DI container and use something like JNDI.
$result_array = array();
$array = array("Tim","John","Mark");
$new_element = "Bill";
$position = 1;
for ($i=0; $i<count($array); $i++)
{
if ($i==$position)
{
$result_array[] = $new_element;
}
$result_array[] = $array[$i];
}
print_r($result_array);
// Result will Array([0] => "Tim",[1] => "Bill", [2] => "John",[1] => "Mark")
i think this is a best mode to cast to int
public int ByteToint(Byte B){
String comb;
int out=0;
comb=B+"";
salida= Integer.parseInt(comb);
out=out+128;
return out;
}
first comvert byte to String
comb=B+"";
next step is comvert to a int
out= Integer.parseInt(comb);
but byte is in rage of -128 to 127 for this reasone, i think is better use rage 0 to 255 and you only need to do this:
out=out+256;
I would expect:
find the installed node version.
$ node --version
or
$ node -v
And if you want more information about installed node(i.e. node version,v8 version,platform,env variables info etc.)
then just do this.
$ node
> process
process {
title: 'node',
version: 'v6.6.0',
moduleLoadList:
[ 'Binding contextify',
'Binding natives',
'NativeModule events',
'NativeModule util',
'Binding uv',
'NativeModule buffer',
'Binding buffer',
'Binding util',
...
where The process object is a global that provides information about, and control over, the current Node.js process.
Step 1: Inject the $locationProvider service into the app config's constructor
Step 2: Add code line $locationProvider.html5Mode(true) to the app config's constructor.
Step 3: in the container (landing, master, or layout) page, add html tag such as <base href="/">
inside the tag.
Step 4: remove all '#" for routing config from all anchor tags. For examples, href="#home" becomes href="home"; href="#about" becomes herf="about"; href="#contact" becomes href="contact"
<ul class="nav navbar-nav">
<li><a href="home">Home</a></li>
<li><a href="about">About us</a></li>
<li><a href="contact">Contact us</a></li>
</ul>
>>> dictionary = {'C1' : [10,20,30],'C2' : [20,30,40]}
>>> dictionary['C1'] = [x+1 for x in dictionary['C1']]
>>> dictionary
{'C2': [20, 30, 40], 'C1': [11, 21, 31]}
I believe this would be somewhere close.
INSERT INTO Files
(FileId, FileData)
SELECT 1, * FROM OPENROWSET(BULK N'C:\Image.jpg', SINGLE_BLOB) rs
Something to note, the above runs in SQL Server 2005 and SQL Server 2008 with the data type as varbinary(max)
. It was not tested with image as data type.
JDK is not available as a portable ZIP file, unfortunately. However, you can follow these steps:
C:\JDK
in this case)jdk-7u7-windows-x64.exe
)jdk-XuXX-windows-x64.exe
into the directory C:\JDK
cmd.exe
:
cd C:\JDK\.rsrc\1033\JAVA_CAB10
extrac32 111
C:\JDK\.rsrc\1033\JAVA_CAB10\tools.zip
with 7-zipcmd.exe
:
cd C:\JDK\.rsrc\1033\JAVA_CAB10\tools\
for /r %x in (*.pack) do .\bin\unpack200 -r "%x" "%~dx%~px%~nx.jar"
(this will convert all .pack
files into .jar
files)C:\JDK\.rsrc\1033\JAVA_CAB10\tools
where you want your JDK to beJAVA_HOME
and PATH
manually to point to your JDK dir and its BIN subdirectory.You use the Python 2 docs but write your program in Python 3.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Center</title>
</head>
<body>
<div id="main_body">
some text
</div>
</body>
</html>
CSS
body
{
width: 100%;
Height: 100%;
}
#main_body
{
background: #ff3333;
width: 200px;
position: absolute;
}?
JS ( jQuery )
$(function(){
var windowHeight = $(window).height();
var windowWidth = $(window).width();
var main = $("#main_body");
$("#main_body").css({ top: ((windowHeight / 2) - (main.height() / 2)) + "px",
left:((windowWidth / 2) - (main.width() / 2)) + "px" });
});
See example here
here is the code to print only the headers or columns of the csv file.
import csv
HEADERS = next(csv.reader(open('filepath.csv')))
print (HEADERS)
Another method with pandas
import pandas as pd
HEADERS = list(pd.read_csv('filepath.csv').head(0))
print (HEADERS)
If you need to interact directly with the DOM element, why not just use document.getElementById
since, if you are trying to interact with a specific element you will probably know the id, as assuming that the classname is on only one element or some other option tends to be risky.
But, I tend to agree with the others, that in most cases you should learn to do what you need using what jQuery gives you, as it is very flexible.
UPDATE: Based on a comment: Here is a post with a nice explanation: http://www.mail-archive.com/[email protected]/msg04461.html
$(this).attr("checked") ? $(this).val() : 0
This will return the value if it's checked, or 0 if it's not.
$(this).val()
is just reaching into the dom and getting the attribute "value" of the element, whether or not it's checked.
Just make rdg2.nPhoneNumber varchar everywhere instead of int !
Well, your code is not reproducible so we will never know for sure, but this is what help('break')
says:
break breaks out of a for, while or repeat loop; control is transferred to the first statement outside the inner-most loop.
So yes, break
only breaks the current loop. You can also see it in action with e.g.:
for (i in 1:10)
{
for (j in 1:10)
{
for (k in 1:10)
{
cat(i," ",j," ",k,"\n")
if (k ==5) break
}
}
}
Download and Install package here: https://atom.io/packages/script
To execute the python command in atom use the below shortcuts:
For Windows/Linux, it's SHIFT + Ctrl + B OR Ctrl + SHIFT + B
If you're on Mac, press ? + I
I got the same issue on MacOS Catalina.
I think I identified the root cause: I have switched the default Apple ID account and the new one was not activated as a Developer account. When I ran the xcode-select --install
command, I got the same error as stated in the issue description.
After reading this post on stackoverflow, I went on https://developer.apple.com/downloads and I was asked to accept Developers terms. I think it enabled my account as a developer one. Then, I tried to run xcode-select --install
again and it worked.
You can zip the two with something like this [like jQuery does]:
function toggleMyDiv() {
if (document.getElementById("myDiv").style.display=="block"){
document.getElementById("myDiv").style.display="none"
}
else{
document.getElementById("myDiv").style.display="block";
}
}
..and use the same function in the two buttons - or generally in the page for both functions.
How about
CAST(2229.999 AS DECIMAL(6,2))
to get a decimal with 2 decimal places
Not sure why the file path is not working, I have some similar code that works fine.
But if with two "\" it works, you can always do path = path.Replace(@"\", @"\\");
Another option is to use numpy.full
, an option available in NumPy 1.8+
a = np.full([height, width, 9], np.nan)
This is pretty flexible and you can fill it with any other number that you want.
Because I know it's possible in while conditions, but I'm not sure if I'm doing it wrong for the if-statement or if it's just not possible.
HINT: what type while and if condition should be ??
If it can be done with while, it can be done with if statement as weel, as both of them expect a boolean condition.
I do it this way: 1) since there're too many files (~30k) to search thru, I generate the text file list daily for use via crontab using below command:
find /to/src/folder -type f -exec file {} \; | grep text | cut -d: -f1 > ~/.src_list &
2) create a function in .bashrc:
findex() {
cat ~/.src_list | xargs grep "$*" 2>/dev/null
}
Then I can use below command to do the search:
findex "needle text"
HTH:)
Just change +
to -
:
str = str.replace(/[^a-z0-9-]/g, "");
You can read it as:
[^ ]
: match NOT from the set[^a-z0-9-]
: match if not a-z
, 0-9
or -
/ /g
: do global matchMore information:
Expression: "Total Count: " + (DT_WSTR, 11)@[User::int32Value]
for Int32 -- (-2,147,483,648 to 2,147,483,647)
Just set java_home of 1.8 jdk version in netbeans.conf
file:
/Applications/NetBeans/NetBeans 8.2.app/Contents/Resources/NetBeans/etc/netbeans.conf
uncomment line:
netbeans_jdkhome="path/to/jdk"
and set path to your 1.8 jdk, in my case:
netbeans_jdkhome="/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home"
This approach lays you to have several jdk versions on mac os
Git- Git is a version control software that you install on your local system. For an individual working on a project alone, Git proves to be excellent software.
GitHub- As mentioned earlier, Git is a version control system that tracks code changes, while GitHub is a web-based Git version control repository hosting service. It provides all of the distributed version control and source code management (SCM) functionalities of Git while topping it with a few of its own features.
In case someone also want to dump response like me. i avoided to dump response body. following code just dump the StatusCode and Headers.
static private String dumpResponse(HttpServletResponse resp){
StringBuilder sb = new StringBuilder();
sb.append("Response Status = [" + resp.getStatus() + "], ");
String headers = resp.getHeaderNames().stream()
.map(headerName -> headerName + " : " + resp.getHeaders(headerName) )
.collect(Collectors.joining(", "));
if (headers.isEmpty()) {
sb.append("Response headers: NONE,");
} else {
sb.append("Response headers: "+headers+",");
}
return sb.toString();
}
Where the usage of a regex can be helpful to determine if the character sequence of a date is correct, it cannot be used easily to determine if the date is valid. The following examples will pass the regular expression, but are all invalid dates: 20180231, 20190229, 20190431
So if you want to validate if your date string (let's call it datestr
) is in the correct format, it is best to parse it with date
and ask date
to convert the string to the correct format. If both strings are identical, you have a valid format and valid date.
if [[ "$datestr" == $(date -d "$datestr" "+%Y%m%d" 2>/dev/null) ]]; then
echo "Valid date"
else
echo "Invalid date"
fi
Try to clean the project and rebuild it.
Run php -f /common/configs/config_templates.inc.php
to verify the validity of the PHP syntax in the file.
Considering you have already downloaded SDK platform tools. These commands are for MAC users.
This command will set ADB locally. So if you close the terminal and open it again, ADB commands won't work until you run this command again.
export PATH=~/Library/Android/sdk/platform-tools:$PATH
These commands will set ADB globally. So once you run these commands no need to set them again next time.
echo 'export PATH=$PATH:~/Library/Android/sdk/platform-tools/' >> ~/.bash_profile
source ~/.bash_profile
As @CQ says, you need to use HttpUtility.HtmlDecode, but it's not available in a non-ASP .NET project by default.
For a non-ASP .NET application, you need to add a reference to System.Web.dll
. Right-click your project in Solution Explorer, select "Add Reference", then browse the list for System.Web.dll
.
Now that the reference is added, you should be able to access the method using the fully-qualified name System.Web.HttpUtility.HtmlDecode
or insert a using
statement for System.Web
to make things easier.
First , you should know where is your config file ? where is your config file ?
IF you installed with apt-get or yum install ?
config file may appear in
/etc/mysql/my.cnf
datafile may appear in
/var/lib/mysql
and what you should do is
and then jobs done.
But if you didn't install it with apt or yum,the direcotry may not like this ,and you can find the mysql files with
whereis mysql
df['col'] = 'str' + df['col'].astype(str)
Example:
>>> df = pd.DataFrame({'col':['a',0]})
>>> df
col
0 a
1 0
>>> df['col'] = 'str' + df['col'].astype(str)
>>> df
col
0 stra
1 str0
Put them into a list
and use merge
with Reduce
Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
# id v1 v2 v3
# 1 1 1 NA NA
# 2 10 4 NA NA
# 3 2 3 4 NA
# 4 43 5 NA NA
# 5 73 2 NA NA
# 6 23 NA 2 1
# 7 57 NA 3 NA
# 8 62 NA 5 2
# 9 7 NA 1 NA
# 10 96 NA 6 NA
You can also use this more concise version:
Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))
The programming language of iOS(and Mac OS) is Objective-C and C. You have to use Xcode platform to develop iOS apps, on the next version that is now available on beta release, Xcode 4 supports also C++.
The server_name
docs directive is used to identify virtual hosts, they're not used to set the binding.
netstat
tells you that nginx listens on 0.0.0.0:80
which means that it will accept connections from any IP.
If you want to change the IP nginx binds on, you have to change the listen
docs rule.
So, if you want to set nginx to bind to localhost
, you'd change that to:
listen 127.0.0.1:80;
In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).
I've coded up a simple example for you and annotated the source. The example shows how to grab live json and parse into a JSONObject
for detail extraction:
try{
// Create a new HTTP Client
DefaultHttpClient defaultClient = new DefaultHttpClient();
// Setup the get request
HttpGet httpGetRequest = new HttpGet("http://example.json");
// Execute the request in the client
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
// Grab the response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
// Instantiate a JSON object from the request response
JSONObject jsonObject = new JSONObject(json);
} catch(Exception e){
// In your production code handle any errors and catch the individual exceptions
e.printStackTrace();
}
Once you have your JSONObject
refer to the SDK for details on how to extract the data you require.
That's my solution
<div class="main" style="width: 100%;">
<div class="container">
<div class="sizing"></div>
<div class="content"></div>
</div>
</div>
.main {
width: 100%;
}
.container {
width: 30%;
float: right;
position: relative;
}
.sizing {
width: 100%;
padding-bottom: 50%;
visibility: hidden;
}
.content {
width: 100%;
height: 100%;
background-color: red;
position: absolute;
margin-top: -50%;
}
public class Randoms {
static int z, a = 1111, b = 9999, r;
public static void main(String ... args[])
{
rand();
}
public static void rand() {
Random ran = new Random();
for (int i = 1; i == 1; i++) {
z = ran.nextInt(b - a + 1) + a;
System.out.println(z);
randcheck();
}
}
private static void randcheck() {
for (int i = 3; i >= 0; i--) {
if (z != 0) {
r = z % 10;
arr[i] = r;
z = z / 10;
}
}
for (int i = 0; i <= 3; i++) {
for (int j = i + 1; j <= 3; j++) {
if (arr[i] == arr[j]) {
rand();
}
}
}
}
}
It would really help if you'd include the code that's not working (from the 'other' file), but I suspect you could do what you want with a healthy dose of the 'eval' function.
For example:
def run():
print "this does nothing"
def chooser():
return "run"
def main():
'''works just like:
run()'''
eval(chooser())()
The chooser returns the name of the function to execute, eval then turns a string into actual code to be executed in-place, and the parentheses finish off the function call.
Another solution is to add extension method like so:
public static void CopyProperties(this object destinationObject, object sourceObject, bool overwriteAll = true)
{
try
{
if (sourceObject != null)
{
PropertyInfo[] sourceProps = sourceObject.GetType().GetProperties();
List<string> sourcePropNames = sourceProps.Select(p => p.Name).ToList();
foreach (PropertyInfo pi in destinationObject.GetType().GetProperties())
{
if (sourcePropNames.Contains(pi.Name))
{
PropertyInfo sourceProp = sourceProps.First(srcProp => srcProp.Name == pi.Name);
if (sourceProp.PropertyType == pi.PropertyType)
if (overwriteAll || pi.GetValue(destinationObject, null) == null)
{
pi.SetValue(destinationObject, sourceProp.GetValue(sourceObject, null), null);
}
}
}
}
}
catch (ApplicationException ex)
{
throw;
}
}
then have a constructor in each derived class that accepts base class:
public class DerivedClass: BaseClass
{
public DerivedClass(BaseClass baseModel)
{
this.CopyProperties(baseModel);
}
}
It will also optionally overwrite destination properties if already set (not null) or not.
Where is this info kept ("this connection is between computer
A
and serverF
")?
A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.
HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.
This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.
When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection
No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.
which is only for my session ?
Does it mean that no one else can use that connection
That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.
If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?
Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:
if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)
An typical keep-alive response looks like this:
Keep-Alive: timeout=15, max=100
See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):
A host sets the value of the timeout
parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.
The max
parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.
However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.
from sqlalchemy import desc
someselect.order_by(desc(table1.mycol))
Usage from @jpmc26
The right thing would be to use a "if defined" statement, which is used to test for the existence of a variable. For example:
IF DEFINED somevariable echo Value exists
In this particular case, the negative form should be used:
IF NOT DEFINED somevariable echo Value missing
PS: the variable name should be used without "%" caracters.
Generally speaking,
$('#startdate').data('date')
is best because
$('#startdate').val()
not work if you have a datepicker "inline"
ls -lart | tail -n +2 #argument means starting with line 2
The below code working for me on array coming from ajax call .
$form = $request->input('form');
$rules = array(
'facebook_account' => 'url',
'youtube_account' => 'url',
'twitter_account' => 'url',
'instagram_account' => 'url',
'snapchat_account' => 'url',
'website' => 'url',
);
$validation = Validator::make($form, $rules);
if ($validation->fails()) {
return Response::make(['error' => $validation->errors()], 400);
}
Others answers are great, I just wanted to add an alternative solution with ES6
Array function : filter
.
filter()
creates a new array with elements that fall under a given criteria from an existing array.
So you can easily use it to remove items that not pass the criteria. Benefits of this function is that you can use it on complex array not just string and number.
Some examples :
Remove first element :
// Not very useful but it works
function removeFirst(element, index) {
return index > 0;
}
var arr = [1,2,3,5,6].filter(removeFirst); // [2,3,4,5,6]
Remove second element :
function removeSecond(element, index) {
return index != 1;
}
var arr = [1,2,3,5,6].filter(removeSecond); // [1,3,4,5,6]
Remove odd element :
function removeOdd(element, index) {
return !(element % 2);
}
var arr = [1,2,3,5,6].filter(removeOdd); [2,4,6]
Remove items not in stock
const inventory = [
{name: 'Apple', qty: 2},
{name: 'Banana', qty: 0},
{name: 'Orange', qty: 5}
];
const res = inventory.find( product => product.qty > 0);
Use the new jQuery on function in 1.7.1 -
I just encountered this on Windows 10 and the latest NodeJS (14.15.1). In my case our admins have our profiles and true "home" folder remotely mount onto our work machine(s). Npm wanted to put its cache over on the remote server and that has worked until this release.
I was unaware that npm has a .npmrc
file available. I added one to my actual machine's C:\Users\my-id
folder and it contains:
prefix=C:\Users\my-id\nodejs\npm
cache=c:\Users\my-id\nodejs\npm-cache
I also added these paths to my PATH
environment variable.
I went to the APPDATA
folder on my work machine and the remote "home" server and deleted all the npm related Roaming folders. I deleted the node_modules
folder in my project.
I closed all open windows and reopened them. I brought up a command prompt in my project dir and re init
ed npm and reinstalled the modules I wanted.
After that everything is rolling along.
You propably have to write some JavaScript, because there is no way to estimate the height of all the users of the page.
If you want to do an executable jar file, them need set the main class too. So the full configuration should be.
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
<configuration>
<!-- ... -->
<archive>
<manifest>
<mainClass>fully.qualified.MainClass</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
I think you had the correct idea with your last example. You only got an error because you were trying to put quotes inside an already quoted string. This will fix it:
gci -path hklm:\software\microsoft\windows\currentversion\uninstall | ForEach-Object -Process { write-output ($_.GetValue("DisplayName") + "`n") }
Edit: Keith's $() operator actually creates a better syntax (I always forget about this one). You can also escape quotes inside quotes as so:
gci -path hklm:\software\microsoft\windows\currentversion\uninstall | ForEach-Object -Process { write-output "$($_.GetValue(`"DisplayName`"))`n" }
Based on all the reading and agonizing on my own sites and after having been hacked I have come up with the above list that includes permissions for a security plugin for Wordpress called Wordfence. (Not affiliated with it)
In our example, the wordpress document root is /var/www/html/example.com/public_html
Open up the permissions so that www-data can write to the document root as follows:
cd /var/www/html/example.com
sudo chown -R www-data:www-data public_html/
Now from the dashboard in your site, as an admin you can perform updates.
Secure Site after Updates are finished by following these steps:
sudo chown -R wp-user:wp-user public_html/
The above command changes permissions of everything in the wordpress install to the wordpress FTP user.
cd public_html/wp-content
sudo chown -R www-data:wp-user wflogs
sudo chown -R www-data:wp-user uploads
The above command ensures that the security plugin Wordfence has access to its logs. The uploads directory is also writeable by www-data.
cd plugins
sudo chown -R www-data:wp-user wordfence/
The above command also ensures that the security plugin has required read write access for its proper function.
Directory and Files Permissions
# Set all directories permissions to 755
find . -type d -exec chmod 755 {} \;
# Set all files permissions to 644
find . -type f -exec chmod 644 {} \;
Set the permissions for wp-config.php to 640 so that only wp-user can read this file and no one else. Permissions of 440 didn't work for me with above file ownership.
sudo chmod 640 wp-config.php
Wordpress automatic updates using SSH were working with fine with PHP5 but broke with PHP7.0 due to problems with php7.0-ssh2 bundeld with Ubuntu 16.04 and I couldn't find how to install the right version and make it work. Fortunately a very reliable plugin called ssh-sftp-updater-support (free) makes automatic updates using SFTP possible without need for libssh2. So the above permissions never have to be loosened except in rare cases as needed.
Just put "?" in your shell script. In the correct locale and on a Unicode-enabled console it'll print just fine:
$ echo ?
?
$
An ugly "workaround" would be to output the UTF-8 sequence, but that also depends on the encoding used:
$ echo -e '\xE2\x98\xA0'
?
$
gcc 7.4.0 can not compile codes as below:
#include <stdio.h>
const char * const str1 = "str1";
const char * str2 = str1;
int main() {
printf("%s - %s\n", str1, str2);
return 0;
}
constchar.c:3:21: error: initializer element is not constant const char * str2 = str1;
In fact, a "const char *" string is not a compile-time constant, so it can't be an initializer. But a "const char * const" string is a compile-time constant, it should be able to be an initializer. I think this is a small drawback of CLang.
A function name is of course a compile-time constant.So this code works:
void func(void)
{
printf("func\n");
}
typedef void (*func_type)(void);
func_type f = func;
int main() {
f();
return 0;
}
Your if
statement is always false and T
gets initialized only if a condition is met, so the code doesn't reach the point where T
gets a value (and by that, gets defined/bound). You should introduce the variable in a place that always gets executed.
Try:
def temp_sky(lreq, breq):
T = <some_default_value> # None is often a good pick
for line in tfile:
data = line.split()
if abs(float(data[0])-lreq) <= 0.1 and abs(float(data[1])-breq) <= 0.1:
T = data[2]
return T
You can do this by using HeidiSQL without generating Db dumps
Steps:
1) Select the database you need to search in from the left panel of GUI.
2) Export > Export Database as SQL
3) In Table Tools window select "FIND TEXT" tab.
4) Provide your string to search and click "FIND".
5) It will list all the tables contains our string.
6) Select the row with higher relevance %.
7) Click "SEE RESULTS"
You have two records in your json file, and json.loads()
is not able to decode more than one. You need to do it record by record.
See Python json.loads shows ValueError: Extra data
OR you need to reformat your json to contain an array:
{
"foo" : [
{"name": "XYZ", "address": "54.7168,94.0215", "country_of_residence": "PQR", "countries": "LMN;PQRST", "date": "28-AUG-2008", "type": null},
{"name": "OLMS", "address": null, "country_of_residence": null, "countries": "Not identified;No", "date": "23-FEB-2017", "type": null}
]
}
would be acceptable again. But there cannot be several top level objects.
select sum(qty), name
from (
select count(m.owner_id) as qty, o.name
from transport t,owner o,motorbike m
where t.type='motobike' and o.owner_id=m.owner_id
and t.type_id=m.motorbike_id
group by m.owner_id
union all
select count(c.owner_id) as qty, o.name,
from transport t,owner o,car c
where t.type='car' and o.owner_id=c.owner_id and t.type_id=c.car_id
group by c.owner_id
) t
group by name
Guava's ComparisonChain:
Collections.sort(list, new Comparator<ActiveAlarm>(){
@Override
public int compare(ActiveAlarm a1, ActiveAlarm a2) {
return ComparisonChain.start()
.compare(a1.timestarted, a2.timestarted)
//...
.compare(a1.timeEnded, a1.timeEnded).result();
}});
SELECT p.MEMBSHIP_ID
FROM user_payments as p
WHERE USER_ID = 1 AND PAYM_DATE = (
SELECT MAX(p2.PAYM_DATE)
FROM user_payments as p2
WHERE p2.USER_ID = p.USER_ID
)
Gooye if it's possible to use Joda Time in your project then this code works for me:
String dateStr = "2012-10-01T09:45:00.000+02:00";
String customFormat = "yyyy-MM-dd HH:mm:ss";
DateTimeFormatter dtf = ISODateTimeFormat.dateTime();
LocalDateTime parsedDate = dtf.parseLocalDateTime(dateStr);
String dateWithCustomFormat = parsedDate.toString(DateTimeFormat.forPattern(customFormat));
System.out.println(dateWithCustomFormat);
Simplest way is to add this JAVA library using Gradle:
compile 'se.simbio.encryption:library:2.0.0'
You can use it as simple as this:
Encryption encryption = Encryption.getDefault("Key", "Salt", new byte[16]);
String encrypted = encryption.encryptOrNull("top secret string");
String decrypted = encryption.decryptOrNull(encrypted);
yum -y install zlib-devel openssl-devel cpio expat-devel gettext-devel gcc
wget http://git-core.googlecode.com/files/git-1.7.11.4.tar.gz
tar zxvf git-1.7.11.4.tar.gz
cd git-1.7.11.4
./configure
make
make install
Query String: ?strID=XXXX&strName=yyyy&strDate=zzzzz
before you redirect:
string queryString = Request.QueryString.ToString();
Response.Redirect("page.aspx?"+queryString);
With TypeScript generics you can do something like this.
class Person {
constructor (public Name : string, public Age: number) {}
}
var list = new Array<Person>();
list.push(new Person("Baby", 1));
list.push(new Person("Toddler", 2));
list.push(new Person("Teen", 14));
list.push(new Person("Adult", 25));
var oldest_person = list.reduce( (a, b) => a.Age > b.Age ? a : b );
alert(oldest_person.Name);
window.location.reload(true)
seems to have been deprecated by the HTML5 standard. One way to do this without using query strings is to use the Clear-Site-Data
header, which seems to being standardized.
Be advised that Object.clone() has some major problems, and its use is discouraged in most cases. Please see Item 11, from "Effective Java" by Joshua Bloch for a complete answer. I believe you can safely use Object.clone() on primitive type arrays, but apart from that you need to be judicious about properly using and overriding clone. You are probably better off defining a copy constructor or a static factory method that explicitly clones the object according to your semantics.
When creating a custom rating bar that displays a solid gradient line running on a SeekBar-like track, rather than stars, I also encountered a problem related to the vertical centering of the background (track drawable). This is the flawed drawable code I used originally (which generated the problem), as suggested by Android developer and other StackOverflow entries:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@android:id/background"
android:drawable="@drawable/seekbar_track"/>
<item android:id="@android:id/secondaryProgress">
<scale
android:drawable="@drawable/seekbar_progress2"
android:scaleWidth="100%" />
</item>
<item android:id="@android:id/progress" >
<clip android:clipOrientation="horizontal" android:gravity="left" >
<shape>
<gradient
android:startColor="@color/ratingbar_bg_start"
android:centerColor="@color/ratingbar_bg_center"
android:centerX="0.5"
android:endColor="@color/ratingbar_bg_end"
android:angle="0"
/>
</shape>
</clip>
</item>
</layer-list>
The problem here is the first item, which relates to the background of the custom RatingBar. Many entries will tell you to set the layout_minHeight feature to some large value to avoid a vertical spatial disconnect between the thumb and its track. This was not the solution for me - when viewed on a tablet, the background was still drawing to its smaller phone-based size - so the track was consistently positioned well above the center of the RatingBar track. The solution is to remove this entry in the RatingBar drawable, so it now looks like this:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/secondaryProgress">
<scale
android:drawable="@drawable/seekbar_progress2"
android:scaleWidth="100%" />
</item>
<item android:id="@android:id/progress" >
<clip android:clipOrientation="horizontal" android:gravity="left" >
<shape>
<gradient
android:startColor="@color/ratingbar_bg_start"
android:centerColor="@color/ratingbar_bg_center"
android:centerX="0.5"
android:endColor="@color/ratingbar_bg_end"
android:angle="0"
/>
</shape>
</clip>
</item>
</layer-list>
Then, in the style definition of the custom RatingBar, set the layout_background to the the track drawable. Mine looks like this:
<style name="styleRatingBar" parent="@android:style/Widget.RatingBar">
<item name="android:indeterminateOnly">false</item>
<item name="android:background">@drawable/seekbar_track</item>
<item name="android:progressDrawable">@drawable/abratingbar</item>
<item name="android:thumb">@drawable/abseekbar_thumb</item>
<item name="android:minHeight">@dimen/base_29dp</item>
<item name="android:maxHeight">@dimen/base_29dp</item>
<item name="android:layout_marginLeft">@dimen/base_10dp</item>
<item name="android:layout_marginRight">@dimen/base_10dp</item>
<item name="android:layout_marginTop">@dimen/base_10dp</item>
<item name="android:layout_marginBottom">@dimen/base_10dp</item>
<item name="android:scaleType">fitXY</item>
</style>
(Previously, the background setting here was undefined.).
This is the entry in my layout, which uses both the style and the drawables:
<RatingBar
android:id="@+id/ratingbar_vote"
style="@style/styleRatingBar"
android:hint="@string/ratingbar_vote"
android:contentDescription="@string/ratingbar_vote"
android:numStars="5"
android:rating="5"
android:stepSize="1"
android:layout_width="match_parent"
android:layout_height="@dimen/base_29dp"
android:layout_marginLeft="@dimen/base_120dp"
android:layout_gravity="bottom|right" />
So, to summarize, do not set the background (track) feature in your custom RatingBar drawable, set it in the layout_background feature of your custom RatingBar style. This ensures the track is always vertically centered in a horizontal RatingBar. (Remember, in this custom RatingBar, instead of using stars or other isolated images as the rating, I'm using a gradient line that "grows" or "shrinks" horizontally to display the rating - this rating line uses a SeekBar-like thumb running on a SeekBar-like "track".)
I had a button where the background-image
had a shadow below it so the text alignment was off from the top. Changing the line-height
wouldn't help. I added padding-bottom
to it and it worked.
So what you have to do is determine the line-height
you want to play with. So, for example, if I have a button who's height is truly 90px
but I want the line-height to be 80px
I would have something like this:
input[type=butotn].mybutton{
background: url(my/image.png) no-repeat center top; /*Image is 90px x 150px*/
width: 150px;
height: 80px; /*shadow at the bottom is 10px (90px-10px)*/
padding-bottom: 10px; /*the padding will make up for the lost height while maintaining the line-height to the proper height */
}
I hope this helps.
EDIT: It appears that this method is not supported anymore (thx to @FernandoZamperin). Please take a look at the other answers!
Instead of subscribing to a topic you could instead make use of the condition
key and send messages to instances, that are not in a group. Your data might look something like this:
{
"data": {
"foo": "bar"
},
"condition": "!('anytopicyoudontwanttouse' in topics)"
}
See https://firebase.google.com/docs/cloud-messaging/send-message#send_messages_to_topics_2
I use HAVING for constraining a query based on the results of an aggregate function. E.G. select * in blahblahblah group by SOMETHING having count(SOMETHING)>0
SQL tables are not ordered by default, and asking for the n-th row from a non ordered set of rows has no meaning as it could potentially return a different row each time unless you specify an ORDER BY:
select * from customer order by id where row_number() = 3
(sometimes MySQL tables are shown with an internal order but you cannot rely on this behaviour). Then you can use LIMIT offset, row_count
, with a 0-based offset so row number 3 becomes offset 2:
select * from customer order by id
limit 2, 1
or you can use LIMIT row_count OFFSET offset
:
select * from customer order by id
limit 1 offset 2
If you want to create a small dots, just use icon from font awesome.
fa fa-circle
In addition to the other answers, the fmod
documentation has some interesting things to say on the subject:
math.fmod(x, y)
Return
fmod(x, y)
, as defined by the platform C library. Note that the Python expressionx % y
may not return the same result. The intent of the C standard is thatfmod(x, y)
be exactly (mathematically; to infinite precision) equal tox - n*y
for some integer n such that the result has the same sign asx
and magnitude less thanabs(y)
. Python’sx % y
returns a result with the sign ofy
instead, and may not be exactly computable for float arguments. For example,fmod(-1e-100, 1e100)
is-1e-100
, but the result of Python’s-1e-100 % 1e100
is1e100-1e-100
, which cannot be represented exactly as a float, and rounds to the surprising1e100
. For this reason, functionfmod()
is generally preferred when working with floats, while Python’sx % y
is preferred when working with integers.
Try requests instead of urllib and you don't need to bother with urlencode!
import requests
requests.get('http://youraddress.com', params=evt.fields)
EDIT:
If you need ordered name-value pairs or multiple values for a name then set params like so:
params=[('name1','value11'), ('name1','value12'), ('name2','value21'), ...]
instead of using a dictionary.
As others have mentioned... A depth first search will solve it. In general depth first search takes O(V + E) but in this case you know the graph has at most O(V) edges. So you can simply run a DFS and once you see a new edge increase a counter. When the counter has reached V you don't have to continue because the graph has certainly a cycle. Obviously this takes O(v).
It worked for me after adding the following dependency in pom,
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.0.Final</version>
</dependency>
Like this:
my_function (null, options) // for options only
my_function (content) // for content only
my_function (content, options) // for both
You can raise a notice in Postgres
as follows:
raise notice 'Value: %', deletedContactId;
Read here
Example
find <path> -name *FileName*
From manual:
find -name pattern
Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories are removed, the file names considered for a match with -name will never include a slash, so "-name a/b" will never match anything (you probably need to use -path instead). The metacharacters ("*", "?", and "[]") match a "." at the start of the base name (this is a change in find- utils-4.2.2; see section STANDARDS CONFORMANCE below). To ignore a directory and the files under it, use -prune; see an example in the description of -path. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell.
Try this command:
pip install pywin32
Note
If it gives the following error:
Could not find a version that satisfies the requirement pywin32>=223 (from pypiwin32) (from versions:)
No matching distribution found for pywin32>=223 (from pypiwin32)
upgrade 'pip', using:
pip install --upgrade pip
You can make a simple circle with white border and transparent content with shape.
// res/drawable/circle.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:innerRadius="0dp"
android:shape="ring"
android:thicknessRatio="1.9"
android:useLevel="false" >
<solid android:color="@android:color/transparent" />
<stroke
android:width="10dp"
android:color="@android:color/white" />
</shape>
Then make a layerlist drawable and put it as background to your imageview.
// res/drawable/img.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@drawable/circle"/>
<item android:drawable="@drawable/ic_launcher"/>
</layer-list>
and put it as background to your imageview.
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/img"/>
You'll have something like that.
You should be able to &&
the conditions:
ng-disabled="condition1 && condition2"
A better alternative is provided in ES6 using Sets. So, instead of declaring Arrays, it is recommended to use Sets if you need to have an array that shouldn't add duplicates.
var array = new Set();
array.add(1);
array.add(2);
array.add(3);
console.log(array);
// Prints: Set(3) {1, 2, 3}
array.add(2); // does not add any new element
console.log(array);
// Still Prints: Set(3) {1, 2, 3}
If you just want the bitmap, This too works
InputStream inputStream = mContext.getContentResolver().openInputStream(uri);
Bitmap bmp = BitmapFactory.decodeStream(inputStream);
if( inputStream != null ) inputStream.close();
sample uri : content://media/external/images/media/12345
You should use the OO interface to matplotlib, rather than the state machine interface. Almost all of the plt.*
function are thin wrappers that basically do gca().*
.
plt.subplot
returns an axes
object. Once you have a reference to the axes object you can plot directly to it, change its limits, etc.
import matplotlib.pyplot as plt
ax1 = plt.subplot(131)
ax1.scatter([1, 2], [3, 4])
ax1.set_xlim([0, 5])
ax1.set_ylim([0, 5])
ax2 = plt.subplot(132)
ax2.scatter([1, 2],[3, 4])
ax2.set_xlim([0, 5])
ax2.set_ylim([0, 5])
and so on for as many axes as you want.
or better, wrap it all up in a loop:
import matplotlib.pyplot as plt
DATA_x = ([1, 2],
[2, 3],
[3, 4])
DATA_y = DATA_x[::-1]
XLIMS = [[0, 10]] * 3
YLIMS = [[0, 10]] * 3
for j, (x, y, xlim, ylim) in enumerate(zip(DATA_x, DATA_y, XLIMS, YLIMS)):
ax = plt.subplot(1, 3, j + 1)
ax.scatter(x, y)
ax.set_xlim(xlim)
ax.set_ylim(ylim)
You can use ComboBox, then point your mouse to the upper arrow facing right, it will unfold a box called ComboBox Tasks and in there you can go ahead and edit your items or fill in the items / strings one per line. This should be the easiest.
Working. you should tryout this:
android:src="@drawable/img"
Plz Change setting.
Step 1: Go to TARGETS -> Build Settings -> No Common Blocks -> No
Step 2: Go to TARGETS -> Build Settings -> enable testability -> No
FOR MVC
-- WEB.CONFIG CODE IN APP SETTING --
<add key="PhaseLevel" value="1" />
-- ON VIEWS suppose you want to show or hide something based on web.config Value--
-- WRITE THIS ON TOP OF YOUR PAGE--
@{
var phase = System.Configuration.ConfigurationManager.AppSettings["PhaseLevel"].ToString();
}
-- USE ABOVE VALUE WHERE YOU WANT TO SHOW OR HIDE.
@if (phase != "1")
{
@Html.Partial("~/Views/Shared/_LeftSideBarPartial.cshtml")
}
This won't be suitable for everyone, but if your application is already setup to take commands via a socket, you can use netcat to issue a commands via cron proper.
echo 'mycommand' | nc -U /tmp/myapp.sock
Simple way to do this. Try this code. Put code in your htaccess
file:
Options +FollowSymLinks
RewriteEngine on
RewriteRule profile/(.*)/ profile.php?u=$1
RewriteRule profile/(.*) profile.php?u=$1
It will create this type pretty URL:
For more htaccess Pretty URL:http://www.webconfs.com/url-rewriting-tool.php
I used umake to install android studio. For me the path was
/home/user/.local/share/umake/android/android-studio/gradle/gradle-2.14.1
You will have to implement the Google Maps API projection in your language. I have the C# source code for this:
public class GoogleMapsAPIProjection
{
private readonly double PixelTileSize = 256d;
private readonly double DegreesToRadiansRatio = 180d / Math.PI;
private readonly double RadiansToDegreesRatio = Math.PI / 180d;
private readonly PointF PixelGlobeCenter;
private readonly double XPixelsToDegreesRatio;
private readonly double YPixelsToRadiansRatio;
public GoogleMapsAPIProjection(double zoomLevel)
{
var pixelGlobeSize = this.PixelTileSize * Math.Pow(2d, zoomLevel);
this.XPixelsToDegreesRatio = pixelGlobeSize / 360d;
this.YPixelsToRadiansRatio = pixelGlobeSize / (2d * Math.PI);
var halfPixelGlobeSize = Convert.ToSingle(pixelGlobeSize / 2d);
this.PixelGlobeCenter = new PointF(
halfPixelGlobeSize, halfPixelGlobeSize);
}
public PointF FromCoordinatesToPixel(PointF coordinates)
{
var x = Math.Round(this.PixelGlobeCenter.X
+ (coordinates.X * this.XPixelsToDegreesRatio));
var f = Math.Min(
Math.Max(
Math.Sin(coordinates.Y * RadiansToDegreesRatio),
-0.9999d),
0.9999d);
var y = Math.Round(this.PixelGlobeCenter.Y + .5d *
Math.Log((1d + f) / (1d - f)) * -this.YPixelsToRadiansRatio);
return new PointF(Convert.ToSingle(x), Convert.ToSingle(y));
}
public PointF FromPixelToCoordinates(PointF pixel)
{
var longitude = (pixel.X - this.PixelGlobeCenter.X) /
this.XPixelsToDegreesRatio;
var latitude = (2 * Math.Atan(Math.Exp(
(pixel.Y - this.PixelGlobeCenter.Y) / -this.YPixelsToRadiansRatio))
- Math.PI / 2) * DegreesToRadiansRatio;
return new PointF(
Convert.ToSingle(latitude),
Convert.ToSingle(longitude));
}
}
Source:
Use this function to delete specific message thread or modify according your needs:
public void delete_thread(String thread)
{
Cursor c = getApplicationContext().getContentResolver().query(
Uri.parse("content://sms/"),new String[] {
"_id", "thread_id", "address", "person", "date","body" }, null, null, null);
try {
while (c.moveToNext())
{
int id = c.getInt(0);
String address = c.getString(2);
if (address.equals(thread))
{
getApplicationContext().getContentResolver().delete(
Uri.parse("content://sms/" + id), null, null);
}
}
} catch (Exception e) {
}
}
Call this function simply below:
delete_thread("54263726");//you can pass any number or thread id here
Don't forget to add android mainfest permission below:
<uses-permission android:name="android.permission.WRITE_SMS"/>