Better Way to Provide Choice inside a django Model :
from django.db import models
class Student(models.Model):
FRESHMAN = 'FR'
SOPHOMORE = 'SO'
JUNIOR = 'JR'
SENIOR = 'SR'
GRADUATE = 'GR'
YEAR_IN_SCHOOL_CHOICES = [
(FRESHMAN, 'Freshman'),
(SOPHOMORE, 'Sophomore'),
(JUNIOR, 'Junior'),
(SENIOR, 'Senior'),
(GRADUATE, 'Graduate'),
]
year_in_school = models.CharField(
max_length=2,
choices=YEAR_IN_SCHOOL_CHOICES,
default=FRESHMAN,
)
ctrl + w, w as mentioned can be used for navigating from pane to pane.
Now you can select a particular change alone and paste it to the other pane as follows.Here I am giving an eg as if I wanted to change my piece of code from pane 1 to pane 2 and currently my cursor is in pane1
Use Shift-v to highlight a line and use up or down keys to select the piece of code you require and continue from step 3 written below to paste your changes in the other pane.
Use visual mode and then change it
1 click 'v' this will take you to visual mode 2 use up or down key to select your required code 3 click on ,Esc' escape key 4 Now use 'yy' to copy or 'dd' to cut the change 5 do 'ctrl + w, w' to navigate to pane2 6 click 'p' to paste your change where you require
I am working on Windows Vista. Even i faced the same problem but when i tried to run VS 2008 with administrative privileges, the issue resolved and my service was up and running. :)
Convert it to type Char
?
The essential idea here is to select the data you want to sum, and then sum them. This selection of data can be done in several different ways, a few of which are shown below.
Arguably the most common way to select the values is to use Boolean indexing.
With this method, you find out where column 'a' is equal to 1
and then sum the corresponding rows of column 'b'. You can use loc
to handle the indexing of rows and columns:
>>> df.loc[df['a'] == 1, 'b'].sum()
15
The Boolean indexing can be extended to other columns. For example if df
also contained a column 'c' and we wanted to sum the rows in 'b' where 'a' was 1 and 'c' was 2, we'd write:
df.loc[(df['a'] == 1) & (df['c'] == 2), 'b'].sum()
Another way to select the data is to use query
to filter the rows you're interested in, select column 'b' and then sum:
>>> df.query("a == 1")['b'].sum()
15
Again, the method can be extended to make more complicated selections of the data:
df.query("a == 1 and c == 2")['b'].sum()
Note this is a little more concise than the Boolean indexing approach.
The alternative approach is to use groupby
to split the DataFrame into parts according to the value in column 'a'. You can then sum each part and pull out the value that the 1s added up to:
>>> df.groupby('a')['b'].sum()[1]
15
This approach is likely to be slower than using Boolean indexing, but it is useful if you want check the sums for other values in column a
:
>>> df.groupby('a')['b'].sum()
a
1 15
2 8
Regular expression for number, optional decimal point, optional negative:
^-?(\d*\.)?\d+$;
works for negative integer, decimal, negative with decimal
I'm not an expert. But you can try
git fsck --full --no-reflogs | grep commit
to find the HEAD commit of deleted branch and get them back.
Just Right Click on Project
Click on Team
Click Refresh/Cleaup
this will remove all the current lock files created by SVN
hope this will help !!!!
Try the below code if you're Using Python3:
import sys
if not sys.warnoptions:
import warnings
warnings.simplefilter("ignore")
or try this...
import warnings
def fxn():
warnings.warn("deprecated", DeprecationWarning)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
fxn()
or try this...
import warnings
warnings.filterwarnings("ignore")
You can simple use ng-init like this
<select ng-init="somethingHere = options[0]" ng-model="somethingHere" ng-options="option.name for option in options"></select>
Padding by definition is a positive integer (including 0).
Negative padding would cause the border to collapse into the content (see the box-model page on w3) - this would make the content area smaller than the content, which doesn't make sense.
I had the same issue, for me this fixed the issue:
right click on the project ->maven -> update project
You can do this easily in vanilla JS:
Using find
const savedViews = [{"description":"object1","id":1},{"description":"object2","id":2},{"description":"object3","id":3},{"description":"object4","id":4}];_x000D_
_x000D_
const view = 'object2';_x000D_
_x000D_
const delete_id = savedViews.find(obj => {_x000D_
return obj.description === view;_x000D_
}).id;_x000D_
_x000D_
console.log(delete_id);
_x000D_
Using filter
(original answer)
const savedViews = [{"description":"object1","id":1},{"description":"object2","id":2},{"description":"object3","id":3},{"description":"object4","id":4}];_x000D_
_x000D_
const view = 'object2';_x000D_
_x000D_
const delete_id = savedViews.filter(function (el) {_x000D_
return el.description === view;_x000D_
})[0].id;_x000D_
_x000D_
console.log(delete_id);
_x000D_
I've used the following code a few times and it works sweet:
$("body").click(function(e){
// Check what has been clicked:
var target = $(e.target);
if(target.is("#target")){
// The target was clicked
// Do something...
}
});
Saving username and password with TortoiseGit
Saving your login details in TortoiseGit is pretty easy. Saves having to type in your username and password every time you do a pull or push.
Create a file called _netrc with the following contents:
machine github.com
login yourlogin
password yourpassword
Copy the file to C:\Users\ (or another location; this just happens to be where I’ve put it)
Go to command prompt, type setx home C:\Users\
Note: if you’re using something earlier than Windows 7, the setx command may not work for you. Use set instead and add the home environment variable to Windows using via the Advanced Settings under My Computer.
CREDIT TO: http://www.munsplace.com/blog/2012/07/27/saving-username-and-password-with-tortoisegit/
If you have php installed - you can use built-in server. Just open target dir with files and run
php -S localhost:8001
Here's a completely working and atomic version of a wildcard delete implemented in Lua. It'll run much faster than the xargs version due to much less network back-and-forth, and it's completely atomic, blocking any other requests against redis until it finishes. If you want to atomically delete keys on Redis 2.6.0 or greater, this is definitely the way to go:
redis-cli -n [some_db] -h [some_host_name] EVAL "return redis.call('DEL', unpack(redis.call('KEYS', ARGV[1] .. '*')))" 0 prefix:
This is a working version of @mcdizzle's idea in his answer to this question. Credit for the idea 100% goes to him.
EDIT: Per Kikito's comment below, if you have more keys to delete than free memory in your Redis server, you'll run into the "too many elements to unpack" error. In that case, do:
for _,k in ipairs(redis.call('keys', ARGV[1])) do
redis.call('del', k)
end
As Kikito suggested.
please refer http://complete-concrete-concise.com/web-tools/how-to-change-localhost-to-a-domain-name
this is best solution ever
Since C# version 6 you can simply call:
string currentMethodName = nameof(MyMethod);
In C# version 5 and .NET 4.5 you can use the [CallerMemberName] attribute to have the compiler auto-generate the name of the calling method in a string argument. Other useful attributes are [CallerFilePath] to have the compiler generate the source code file path and [CallerLineNumber] to get the line number in the source code file for the statement that made the call.
Before that there were still some more convoluted ways of getting the method name, but much simpler:
void MyMethod() {
string currentMethodName = "MyMethod";
//etc...
}
Albeit that a refactoring probably won't fix it automatically.
If you completely don't care about the (considerable) cost of using Reflection
then this helper method should be useful:
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Reflection;
//...
[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetMyMethodName() {
var st = new StackTrace(new StackFrame(1));
return st.GetFrame(0).GetMethod().Name;
}
3 years old topic, but I found another working solution.
If you're sure you have enough free memory, running 64 bit OS and still getting exceptions, go to Project properties
-> Build
tab and be sure to set x64
as a Platform target
.
Left joins in LINQ are possible with the DefaultIfEmpty() method. I don't have the exact syntax for your case though...
Actually I think if you just change pets to pets.DefaultIfEmpty() in the query it might work...
EDIT: I really shouldn't answer things when its late...
Maybe a syntax error in your case, you may change the line to:
directory = str(r"C:\Users\Josh\Desktop\20130216").replace('\\','\\\\')
which give you the right following output:
C:\\Users\\Josh\\Desktop\\20130216
in overloading function with same name having different parameters whereas in overridding function having same name as well as same parameters replace the base class to the derived class (inherited class)
You can now use BaseEncoding in guava
to accomplish this.
BaseEncoding.base16().decode(string);
To reverse it use
BaseEncoding.base16().encode(bytes);
Ozi, when you create a new datetime object as in datetime foo = new datetime(); foo is constructed with the time datetime.minvalue() in building a parameterized query, you could check to see if the values entered are equal to datetime.minvalue()
-Just a side thought. seems you have things working.
Well, it's a little late to reply. I have faced the same problem and my Google searches were in vain. However, I managed to find what the problem was. There might be many reasons for getting this error but I got the error due to the following and I wanted to share this with my fellow developers.
You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw()
, ensure that you binding the parameters.
Try the following:
$array = array(1,2,3); $query = DB::table('offers'); $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used'); $query->leftJoin('user_offer_collection', function ($join) use ($array) { $join->on('user_offer_collection.offers_id', '=', 'offers.id') ->whereIn('user_offer_collection.user_id', $array); }); $query->get();
I want to check tha in the following array $arr
is there 'abc' exists in sub arrays or not
$arr = array(
array(
'title' => 'abc'
)
);
Then i can use this
$res = array_search('abc', array_column($arr, 'title'));
if($res == ''){
echo 'exists';
} else {
echo 'notExists';
}
I think This is the Most simple way to define
In my case, my magic code for this pupose is this one:
git reset --hard @{u}
Test it and tell me. I have tried a few different ones, but this one was the only that helped me.
bool contains = pricePublicList.Any(p => p.Size == 200);
You could also check if the id element is used by doing so:
if(typeof $(.div).attr('id') == undefined){
//element has no id
} else {
//element has id selector
}
I use this method for global dataTables and specific ordered dataTables
You can also use
cd %localhost%
to set the directory to the folder the batch file was opened from. Your script would look like this:
@echo off
cd %localhost%
echo .> dblank.txt
Make sure you set the directory before you use the command to create the text file.
(since I ran into this today)
Be careful when using ES2015 fat arrow syntax:
This will fail :
it('accesses the network', done => {
this.timeout(500); // will not work
// *this* binding refers to parent function scope in fat arrow functions!
// i.e. the *this* object of the describe function
done();
});
EDIT: Why it fails:
As @atoth mentions in the comments, fat arrow functions do not have their own this binding. Therefore, it's not possible for the it function to bind to this of the callback and provide a timeout function.
Bottom line: Don't use arrow functions for functions that need an increased timeout.
Let me guess
Your initial declaration of class PUBLICClass
was not public, then you made it `Public', can you try to clean and rebuild your project ?
If by "Ignore Duplicate Error statments", to abort the current statement and continue to the next statement without aborting the trnsaction then just put BEGIN TRY.. END TRY around each statement:
BEGIN TRY
INSERT ...
END TRY
BEGIN CATCH /*required, but you dont have to do anything */ END CATCH
...
I just noticed that the placement option could either be a string or a function returning a string that makes the calculation each time you click on a popover-able link.
This makes it real easy to replicate what you did without the initial $.each function:
var options = {
placement: function (context, source) {
var position = $(source).position();
if (position.left > 515) {
return "left";
}
if (position.left < 515) {
return "right";
}
if (position.top < 110){
return "bottom";
}
return "top";
}
, trigger: "click"
};
$(".infopoint").popover(options);
You can use this, it works fine:
<input type="date" class="form1"
value="{{date | date:MM/dd/yyyy}}"
ng-model="date"
name="id"
validatedateformat
data-date-format="mm/dd/yyyy"
maxlength="10"
id="id"
calendar
maxdate="todays"
ng-click="openCalendar('id')">
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar" ng-click="openCalendar('id')"></span>
</span>
</input>
You can remove "JavaAppletPlugin.plugin" found in Spotlight or Finder, then re-install downloaded Java 8.
This will simply solve your problem.
You may use:
To create array of objects:
var source = ['left', 'top'];
const result = source.map(arrValue => ({[arrValue]: 0}));
Demo:
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.map(value => ({[value]: 0}));_x000D_
_x000D_
console.log(result);
_x000D_
Or if you wants to create a single object from values of arrays:
var source = ['left', 'top'];
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});
Demo:
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});_x000D_
_x000D_
console.log(result);
_x000D_
Please see the GridFS docs for details on storing such binary data.
Support for your specific language should be linked to at the bottom of the screen.
If you're a windows user, you can also delete the environment by going to: C:/Users/username/Anaconda3/envs
Here you can see a list of virtual environment and delete the one that you no longer need.
Use .prop()
:
$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);
If you're working with just one element, you can always just access the underlying HTMLInputElement
and modify its .checked
property:
$('.myCheckbox')[0].checked = true;
$('.myCheckbox')[0].checked = false;
The benefit to using the .prop()
and .attr()
methods instead of this is that they will operate on all matched elements.
The .prop()
method is not available, so you need to use .attr()
.
$('.myCheckbox').attr('checked', true);
$('.myCheckbox').attr('checked', false);
Note that this is the approach used by jQuery's unit tests prior to version 1.6 and is preferable to using $('.myCheckbox').removeAttr('checked');
since the latter will, if the box was initially checked, change the behaviour of a call to .reset()
on any form that contains it – a subtle but probably unwelcome behaviour change.
For more context, some incomplete discussion of the changes to the handling of the checked
attribute/property in the transition from 1.5.x to 1.6 can be found in the version 1.6 release notes and the Attributes vs. Properties section of the .prop()
documentation.
This topic is actually a little more complicated as described in the answers so far. This blogpost by Rob Norris explains it in more detail and gives examples on when using return will actually break your code (or at least have non-obvious effects).
At this point let me just quote the essence of the post. The most important statement is right in the beginning. Print this as a poster and put it to your wall :-)
The
return
keyword is not “optional” or “inferred”; it changes the meaning of your program, and you should never use it.
It gives one example, where it actually breaks something, when you inline a function
// Inline add and addR
def sum(ns: Int*): Int = ns.foldLeft(0)((n, m) => n + m) // inlined add
scala> sum(33, 42, 99)
res2: Int = 174 // alright
def sumR(ns: Int*): Int = ns.foldLeft(0)((n, m) => return n + m) // inlined addR
scala> sumR(33, 42, 99)
res3: Int = 33 // um.
because
A
return
expression, when evaluated, abandons the current computation and returns to the caller of the method in whichreturn
appears.
This is only one of the examples given in the linked post and it's the easiest to understand. There're more and I highly encourage you, to go there, read and understand.
When you come from imperative languages like Java, this might seem odd at first, but once you get used to this style it will make sense. Let me close with another quote:
If you find yourself in a situation where you think you want to return early, you need to re-think the way you have defined your computation.
Yes and no.
This may change in future with encrypted SNI and DNS but as of 2018 both technologies are not commonly in use.
Note for GET requests the user will still be able to cut and paste the URL out of the location bar, and you will probably not want to put confidential information in there that can be seen by anyone looking at the screen.
Using logging.basicConfig
, the following example works for me:
logging.basicConfig(
filename='HISTORYlistener.log',
level=logging.DEBUG,
format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
)
This allows you to format & config all in one line. A resulting log record looks as follows:
2014-05-26 12:22:52.376 CRITICAL historylistener - main: History log failed to start
There are two ways to use this variable:
passing it as a command line argument just like Job mentioned:
cmake -DCMAKE_INSTALL_PREFIX=< install_path > ..
assigning value to it in CMakeLists.txt
:
SET(CMAKE_INSTALL_PREFIX < install_path >)
But do remember to place it BEFORE PROJECT(< project_name>)
command, otherwise it will not work!
NSURL *url = [NSURL URLWithString:[exreciesDescription objectForKey:@"exercise_url"]];
moviePlayer =[[MPMoviePlayerController alloc] initWithContentURL: url];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doneButtonClicked) name:MPMoviePlayerWillExitFullscreenNotification object:nil];
[[moviePlayer view] setFrame: [self.view bounds]]; // frame must match parent view
[self.view addSubview: [moviePlayer view]];
[moviePlayer play];
-(void)playMediaFinished:(NSNotification*)theNotification
{
moviePlayer=[theNotification object];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:moviePlayer];
[moviePlayer.view removeFromSuperview];
}
-(void)doneButtonClicked
{
[moviePlayer stop];
[moviePlayer.view removeFromSuperview];
[self.navigationController popViewControllerAnimated:YES];//no need this if you are opening the player in same screen;
}
It worked for me.
Here is my test code. Test run follows:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
FileInfo f = new FileInfo(args[0]);
bool result = modifyFile(f, args[1],args[2]);
}
private static bool modifyFile(FileInfo file, string extractedMethod, string modifiedMethod)
{
Boolean result = false;
FileStream fs = new FileStream(file.FullName + ".tmp", FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
StreamReader streamreader = file.OpenText();
String originalPath = file.FullName;
string input = streamreader.ReadToEnd();
Console.WriteLine("input : {0}", input);
String tempString = input.Replace(extractedMethod, modifiedMethod);
Console.WriteLine("replaced String {0}", tempString);
try
{
sw.Write(tempString);
sw.Flush();
sw.Close();
sw.Dispose();
fs.Close();
fs.Dispose();
streamreader.Close();
streamreader.Dispose();
File.Copy(originalPath, originalPath + ".old", true);
FileInfo newFile = new FileInfo(originalPath + ".tmp");
File.Delete(originalPath);
File.Copy(originalPath + ".tmp", originalPath, true);
result = true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return result;
}
}
}
C:\testarea>ConsoleApplication1.exe file.txt padding testing
input : <style type="text/css">
<!--
#mytable {
border-collapse: collapse;
width: 300px;
}
#mytable th,
#mytable td
{
border: 1px solid #000;
padding: 3px;
}
#mytable tr.highlight {
background-color: #eee;
}
//-->
</style>
replaced String <style type="text/css">
<!--
#mytable {
border-collapse: collapse;
width: 300px;
}
#mytable th,
#mytable td
{
border: 1px solid #000;
testing: 3px;
}
#mytable tr.highlight {
background-color: #eee;
}
//-->
</style>
I'm pretty sure it's an Adobe standard, bearing in mind the whole PDF standard is theirs to begin with; despite being open now.
My guess would be no for all PDF viewers supporting it, as some definitely will not have a JS engine. I doubt you can rely on full support outside the most recent versions of Acrobat (Reader). So I guess it depends on how you imagine it being used, if mainly via a browser display, then the majority of the market is catered for by Acrobat (Reader) and Chrome's built-in viewer - dare say there is documentation on whether Chrome's PDF viewer supports JS fully.
changing the Selenium.WebDriver.ChromeDriver from 2.40.0 to 2.27.0 is ok for me
In the Divi Theme Documentation, it says that the theme comes with access to 'ePanel' which also has an 'Integration' section.
You should be able to add this code:
<script>
$( ".et-pb-icon" ).click(function() {
$( this ).toggleClass( "active" );
});
</script>
into the the box that says 'Add code to the head of your blog' under the 'Integration' tab, which should get the jQuery working.
Then, you should be able to style your class to what ever you need.
plastic
, for my case.Thanks for the idea of breaking down a formula Werner!
Using Alt+Enter allows one to put each bit of a complex substitute formula on separate lines: they become easier to follow and automatically line themselves up when Enter is pressed.
Just make sure you have enough end statements to match the number of substitute(
lines either side of the cell reference.
As in this example:
=
substitute(
substitute(
substitute(
substitute(
B11
,"(","")
,")","")
,"[","")
,"]","")
becomes:
=
SUBSTITUTE(
SUBSTITUTE(
SUBSTITUTE(
SUBSTITUTE(B12,"(",""),")",""),"[",""),"]","")
which works fine as is, but one can always delete the extra paragraphs manually:
=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(B12,"(",""),")",""),"[",""),"]","")
Name > substitute()
[American Samoa] > American Samoa
If you want a solution that also works in /bin/sh
try
first_arg="$1"
shift
echo First argument: "$first_arg"
echo Remaining arguments: "$@"
shift [n]
shifts the positional parameters n times. A shift
sets the value of $1
to the value of $2
, the value of $2
to the value of $3
, and so on, decreasing the value of $#
by one.
Try this:
If Len(vValue & vbNullString) > 0 Then
' we have a non-Null and non-empty String value
doSomething()
Else
' We have a Null or empty string value
doSomethingElse()
End If
Did you load jQuery in head
section? Did you load it correctly?
<head>
<script src="scripts/jquery.js"></script>
...
</head>
This code assumes jquery.js
is in scripts
directory. (You can change file name if you like)
You can also use jQuery as hosted by Google:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
...
</head>
Apparently, your web server is not configured to return jQuery-1.6.1.js
on requesting /webProject/jquery-1.6.1.js
. There may be numerous reasons for this, such as wrong file name, folder name, routing settings, etc. You need to create another question and describe your 404
in greater details (such as local file name, operation system, webserver name and settings).
Again, you can use jQuery as provided by Google (see above), however you still might want to find out why some local files don't get served on request.
I got the same error by using response.getWriter()
before a request.getRequestDispatcher(path).forward(request, response);
. So start works fine when I replace it by response.getOutputStream()
According to the Swift 2.2 Book published by apple:
“You indicate type methods by writing the static
keyword before the method’s func keyword. Classes may also use the class
keyword to allow subclasses to override the superclass’s implementation of that method.”
Two additional ideas, if you want to check if a device is root capable from your app:
Runtime.getRuntime().exec()
/system/app/Superuser.apk
locationImportant behavior changes between old and new style classes
Exception
(example below)__slots__
addedIt was mentioned in other answers, but here goes a concrete example of the difference between classic MRO and C3 MRO (used in new style classes).
The question is the order in which attributes (which include methods and member variables) are searched for in multiple inheritance.
Classic classes do a depth-first search from left to right. Stop on the first match. They do not have the __mro__
attribute.
class C: i = 0
class C1(C): pass
class C2(C): i = 2
class C12(C1, C2): pass
class C21(C2, C1): pass
assert C12().i == 0
assert C21().i == 2
try:
C12.__mro__
except AttributeError:
pass
else:
assert False
New-style classes MRO is more complicated to synthesize in a single English sentence. It is explained in detail here. One of its properties is that a base class is only searched for once all its derived classes have been. They have the __mro__
attribute which shows the search order.
class C(object): i = 0
class C1(C): pass
class C2(C): i = 2
class C12(C1, C2): pass
class C21(C2, C1): pass
assert C12().i == 2
assert C21().i == 2
assert C12.__mro__ == (C12, C1, C2, C, object)
assert C21.__mro__ == (C21, C2, C1, C, object)
Exception
Around Python 2.5 many classes could be raised, and around Python 2.6 this was removed. On Python 2.7.3:
# OK, old:
class Old: pass
try:
raise Old()
except Old:
pass
else:
assert False
# TypeError, new not derived from `Exception`.
class New(object): pass
try:
raise New()
except TypeError:
pass
else:
assert False
# OK, derived from `Exception`.
class New(Exception): pass
try:
raise New()
except New:
pass
else:
assert False
# `'str'` is a new style object, so you can't raise it:
try:
raise 'str'
except TypeError:
pass
else:
assert False
Short answer, you can't.
HTML is used for the page's structure and can't send e-mails, you will need a server side language (such as PHP) to send e-mails, you can also use a third party service and let them handle the e-mail sending for you.
If you want to pass the % as part of your function you should use the following alternative:
<script>
function fpercentStr(quantity, percentString)
{
var percent = new Number(percentString.replace("%", ""));
return fpercent(quantity, percent);
}
function fpercent(quantity, percent)
{
return quantity * percent / 100;
}
document.write("test 1: " + fpercent(10000, 35.873))
document.write("test 2: " + fpercentStr(10000, "35.873%"))
</script>
I had this same issue but found the following that works great:
The key to creating a responsive YouTube embed is with padding and a container element, which allows you to give it a fixed aspect ratio. You can also use this technique with most other iframe-based embeds, such as slideshows.
Here is what a typical YouTube embed code looks like, with fixed width and height:
<iframe width="560" height="315" src="//www.youtube.com/embed/yCOY82UdFrw"
frameborder="0" allowfullscreen></iframe>
It would be nice if we could just give it a 100% width, but it won't work as the height remains fixed. What you need to do is wrap it in a container like so (note the class names and removal of the width and height):
<div class="container">
<iframe src="//www.youtube.com/embed/yCOY82UdFrw"
frameborder="0" allowfullscreen class="video"></iframe>
</div>
And use the following CSS:
.container {
position: relative;
width: 100%;
height: 0;
padding-bottom: 56.25%;
}
.video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
Here is the page I found the solution on:
https://www.h3xed.com/web-development/how-to-make-a-responsive-100-width-youtube-iframe-embed
Depending on your aspect ratio, you will probably need to adjust the padding-bottom: 56.25%;
to get the height right.
Note that you must put this in the file ".user.ini" in Centos7 rather than "php.ini" which used to work in Centos6. You can put ".user.ini" in any subdirectory in order to affect only that directory.
.user.ini :
max_input_vars = 3000
Tested on Centos7 and PHP 5.6.33.
I had the same problem which was caused because I resetted to an older commit even though I already pushed to the remote branch.
I solved it by deleting my local branch then checking out the origin branch git checkout origin/my_branch
and then executing git checkout my_branch
new Date().toLocaleTimeString()
very simple solution for this is by using useRef
hook
const buttonRef = useRef();
const disableButton = () =>{
buttonRef.current.disabled = true; // this disables the button
}
<button
className="btn btn-primary mt-2"
ref={buttonRef}
onClick={disableButton}
>
Add
</button>
Similarly you can enable the button by using buttonRef.current.disabled = false
Hera's the function UpdateWindowsList_WindowMenu() that you must call after any operations are performed on Tabs.Here windowToolStripMenuItem is the menu item added to Window Menu to menu strip.
public void UpdateWindowsList_WindowMenu()
{
//get all tab pages from tabControl1
TabControl.TabPageCollection tabcoll = tabControl1.TabPages;
//get windowToolStripMenuItem drop down menu items count
int n = windowToolStripMenuItem.DropDownItems.Count;
//remove all menu items from of windowToolStripMenuItem
for (int i = n - 1; i >=2; i--)
{
windowToolStripMenuItem.DropDownItems.RemoveAt(i);
}
//read each tabpage from tabcoll and add each tabpage text to windowToolStripMenuItem
foreach (TabPage tabpage in tabcoll)
{
//create Toolstripmenuitem
ToolStripMenuItem menuitem = new ToolStripMenuItem();
String s = tabpage.Text;
menuitem.Text = s;
if (tabControl1.SelectedTab == tabpage)
{
menuitem.Checked = true;
}
else
{
menuitem.Checked = false;
}
//add menuitem to windowToolStripMenuItem
windowToolStripMenuItem.DropDownItems.Add(menuitem);
//add click events to each added menuitem
menuitem.Click += new System.EventHandler(WindowListEvent_Click);
}
}
private void WindowListEvent_Click(object sender, EventArgs e)
{
//casting ToolStripMenuItem to ToolStripItem
ToolStripItem toolstripitem = (ToolStripItem)sender;
//create collection of tabs of tabContro1
//check every tab text is equal to clicked menuitem then select the tab
TabControl.TabPageCollection tabcoll = tabControl1.TabPages;
foreach (TabPage tb in tabcoll)
{
if (toolstripitem.Text == tb.Text)
{
tabControl1.SelectedTab = tb;
//call UpdateWindowsList_WindowMenu() to perform changes on menuitems
UpdateWindowsList_WindowMenu();
}
}
}
Which specific index? If you want 'Add New' to be first on the dropdownlist you can add it though the code like this:
<asp:DropDownList ID="DropDownList1" AppendDataBoundItems="true" runat="server">
<asp:ListItem Text="Add New" Value="0" />
</asp:DropDownList>
If you want to add it at a different index, maybe the last then try:
ListItem lst = new ListItem ( "Add New" , "0" );
DropDownList1.Items.Insert( DropDownList1.Items.Count-1 ,lst);
I also see that the page loading (performance) takes a long time on using h:commandLink than h:link. h:link is faster compared to h:commandLink
To my understanding, when you need to train a NN, you need a large dataset involves many data items. when NN is being trained, data items go in to NN one by one, that is called an iteration; When the whole dataset goes through, it is called an epoch.
IIF is a non-standard T-SQL function. It was added to SQL SERVER 2012, so that Access could migrate to SQL Server without refactoring the IIF's to CASE before hand. Once the Access db is fully migrated into SQL Server, you can refactor.
Actually, this example helped me to understand what does (function($) {})(jQuery);
mean.
Consider this:
// Clousure declaration (aka anonymous function)
var f = function(x) { return x*x; };
// And use of it
console.log( f(2) ); // Gives: 4
// An inline version (immediately invoked)
console.log( (function(x) { return x*x; })(2) ); // Gives: 4
And now consider this:
jQuery
is a variable holding jQuery object.$
is a variable
name like any other (a
, $b
, a$b
etc.) and it doesn't have any
special meaning like in PHP.Knowing that we can take another look at our example:
var $f = function($) { return $*$; };
var jQuery = 2;
console.log( $f(jQuery) ); // Gives: 4
// An inline version (immediately invoked)
console.log( (function($) { return $*$; })(jQuery) ); // Gives: 4
How things change in a year. In addition to the header attribute in place of xhr.setRequestHeader
, current jQuery (1.7.2+) includes a username and password attribute with the $.ajax
call.
$.ajax
({
type: "GET",
url: "index1.php",
dataType: 'json',
username: username,
password: password,
data: '{ "comment" }',
success: function (){
alert('Thanks for your comment!');
}
});
EDIT from comments and other answers: To be clear - in order to preemptively send authentication without a 401 Unauthorized
response, instead of setRequestHeader
(pre -1.7) use 'headers'
:
$.ajax
({
type: "GET",
url: "index1.php",
dataType: 'json',
headers: {
"Authorization": "Basic " + btoa(USERNAME + ":" + PASSWORD)
},
data: '{ "comment" }',
success: function (){
alert('Thanks for your comment!');
}
});
List<Item> list;
Map<Key,Item> map = new HashMap<Key,Item>();
for (Item i : list) map.put(i.getKey(),i);
Assuming of course that each Item has a getKey()
method that returns a key of the proper type.
All strings meant for humans should use u"".
I found that the following mindset helps a lot when dealing with Python strings: All Python manifest strings should use the u""
syntax. The ""
syntax is for byte arrays, only.
Before the bashing begins, let me explain. Most Python programs start out with using ""
for strings. But then they need to support documentation off the Internet, so they start using "".decode
and all of a sudden they are getting exceptions everywhere about decoding this and that - all because of the use of ""
for strings. In this case, Unicode does act like a virus and will wreak havoc.
But, if you follow my rule, you won't have this infection (because you will already be infected).
I tried most of the suggestions, and none of them worked. I didn't get a chance to try /resetuserdata. Finally I reinstalled the plugin and uninstalled it again, and the windows went away.
Magic commands such as
%matplotlib qt
work in the iPython console and Notebook, but do not work within a script.
In that case, after importing:
from IPython import get_ipython
use:
get_ipython().run_line_magic('matplotlib', 'inline')
for inline plotting of the following code, and
get_ipython().run_line_magic('matplotlib', 'qt')
for plotting in an external window.
Edit: solution above does not always work, depending on your OS/Spyder version Anaconda issue on GitHub. Setting the Graphics Backend to Automatic (as indicated in another answer: Tools >> Preferences >> IPython console >> Graphics --> Automatic) solves the problem for me.
Then, after a Console restart, one can switch between Inline and External plot windows using the get_ipython() command, without having to restart the console.
I'm afraid this isn't possible with plain CSS, and won't be possible to make completely cross-browser compatible.
However, using a jQuery plugin, you could style the dropdown:
This plugin hides the select
element, and creates span
elements etc on the fly to display a custom drop down list style. I'm quite confident you'd be able to change the styles on the spans etc to center align the items.
You are inside a namespace
so you should use \Exception
to specify the global namespace:
try {
$this->buildXMLHeader();
} catch (\Exception $e) {
return $e->getMessage();
}
In your code you've used catch (Exception $e)
so Exception
is being searched in/as:
App\Services\PayUService\Exception
Since there is no Exception
class inside App\Services\PayUService
so it's not being triggered. Alternatively, you can use a use
statement at the top of your class like use Exception;
and then you can use catch (Exception $e)
.
Be sure you have C++ Redistributable for Visual Studio 2015 RC. Try to download the last version:
https://www.microsoft.com/en-us/download/details.aspx?id=52685
Obs: Credit to parsecer
IN db2warehouse I found that "owner" doesn't exist, so I describe table syscat.systables and try using CREATOR instead and it works.
db2 "select NAME from sysibm.systables where CREATOR = '[SCHEMANAME]'and type = 'T'"
In C, a string, as you know, is a character pointer (char *). If you want to swap two strings, you're swapping two char pointers, i.e. just two addresses. In order to do any swap in a function, you need to give it the addresses of the two things you're swapping. So in the case of swapping two pointers, you need a pointer to a pointer. Much like to swap an int, you just need a pointer to an int.
The reason your last code snippet doesn't work is because you're expecting it to swap two char pointers -- it's actually written to swap two characters!
Edit: In your example above, you're trying to swap two int pointers incorrectly, as R. Martinho Fernandes points out. That will swap the two ints, if you had:
int a, b;
intSwap(&a, &b);
JSON.parse is waiting for a String in parameter. You need to stringify your JSON object to solve the problem.
products = [{"name":"Pizza","price":"10","quantity":"7"}, {"name":"Cerveja","price":"12","quantity":"5"}, {"name":"Hamburguer","price":"10","quantity":"2"}, {"name":"Fraldas","price":"6","quantity":"2"}];
console.log(products);
var b = JSON.parse(JSON.stringify(products)); //solves the problem
Can also use:
find . -mindepth 1 -mtime +3 -delete
To not delete target directory
[HttpPost]
public async Task<ActionResult> Capture(string imageData)
{
if (imageData.Length > 0)
{
var imageBytes = Convert.FromBase64String(imageData);
using (var stream = new MemoryStream(imageBytes))
{
var result = (JsonResult)await IdentifyFace(stream);
var serializer = new JavaScriptSerializer();
var faceRecon = serializer.Deserialize<FaceIdentity>(serializer.Serialize(result.Data));
if (faceRecon.Success) return RedirectToAction("Index", "Auth", new { param = serializer.Serialize(result.Data) });
}
}
return Json(new { success = false, responseText = "Der opstod en fejl - Intet billede, manglede data." }, JsonRequestBehavior.AllowGet);
}
// GET: Auth
[HttpGet]
public ActionResult Index(string param)
{
var serializer = new JavaScriptSerializer();
var faceRecon = serializer.Deserialize<FaceIdentity>(param);
return View(faceRecon);
}
The posted solutions will not link any hidden files. To include them, try this:
cd /usr/lib
find /mnt/usr/lib -maxdepth 1 -print "%P\n" | while read file; do ln -s "/mnt/usr/lib/$file" "$file"; done
If you should happen to want to recursively create the directories and only link files (so that if you create a file within a directory, it really is in /usr/lib
not /mnt/usr/lib
), you could do this:
cd /usr/lib
find /mnt/usr/lib -mindepth 1 -depth -type d -printf "%P\n" | while read dir; do mkdir -p "$dir"; done
find /mnt/usr/lib -type f -printf "%P\n" | while read file; do ln -s "/mnt/usr/lib/$file" "$file"; done
Java uses user thread
and daemon tread
concepts.
JVM flow
1. If there are no `user treads` JVM starts terminating the program
2. JVM terminates all `daemon threads` automatically without waiting when they are done
3. JVM is shutdown
As you see daemon tread
is a service thread for user treads
.
daemon tread
is low priority thread.setDaemon()
method before starting it or check it via isDaemon()
On the Mac version I was getting the error when trying to run JSON-Clojure.json.clj, which is the script to export a database table to JSON. To get it to work I had to download the latest Clojure JAR from http://clojure.org/ and then right-click on PHPStorm app in the Finder and "Show Package Contents". Then go to Contents in there. Then open the lib folder, and see a bunch of .jar files. Copy the clojure-1.8.0.jar file from the unzipped archive I downloaded from clojure.org into the aforementioned lib folder inside the PHPStorm.app/Contents/lib. Restart the app. Now it freaking works.
EDIT: You also have to put the JSR-223 script engine into PHPStorm.app/Contents/lib. It can be built from https://github.com/ato/clojure-jsr223 or downloaded from https://www.dropbox.com/s/jg7s0c41t5ceu7o/clojure-jsr223-1.5.1.jar?dl=0 .
Another cause is wrong indentation which means trying to create the wrong objects. I've just fixed one in a Kubernetes Ingress definition:
Wrong
- path: /
backend:
serviceName: <service_name>
servicePort: <port>
Correct
- path: /
backend:
serviceName: <service_name>
servicePort: <port>
FragmentActivity
is part of the support library, while Activity
is the framework's default class. They are functionally equivalent.
You should always use FragmentActivity
and android.support.v4.app.Fragment
instead of the platform default Activity
and android.app.Fragment
classes. Using the platform defaults mean that you are relying on whatever implementation of fragments is used in the device you are running on. These are often multiple years old, and contain bugs that have since been fixed in the support library.
The FailedPreconditionError
arises because the program is attempting to read a variable (named "Variable_1"
) before it has been initialized. In TensorFlow, all variables must be explicitly initialized, by running their "initializer" operations. For convenience, you can run all of the variable initializers in the current session by executing the following statement before your training loop:
tf.initialize_all_variables().run()
Note that this answer assumes that, as in the question, you are using tf.InteractiveSession
, which allows you to run operations without specifying a session. For non-interactive uses, it is more common to use tf.Session
, and initialize as follows:
init_op = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init_op)
For me, I was writing to a file that is opened in Excel.
first you have to give echo to display base url. Then change below value in your autoload.php which will be inside your application/config/ folder.
$autoload['helper'] = array('url');
then your issue will be resolved.
I think you want this?
Column Name to Column Number
Sub Sample()
ColName = "C"
Debug.Print Range(ColName & 1).Column
End Sub
Edit: Also including the reverse of what you want
Column Number to Column Name
Sub Sample()
ColNo = 3
Debug.Print Split(Cells(, ColNo).Address, "$")(1)
End Sub
FOLLOW UP
Like if i have salary field at the very top lets say at cell C(1,1) now if i alter the file and shift salary column to some other place say F(1,1) then i will have to modify the code so i want the code to check for Salary and find the column number and then do rest of the operations according to that column number.
In such a case I would recommend using .FIND
See this example below
Option Explicit
Sub Sample()
Dim strSearch As String
Dim aCell As Range
strSearch = "Salary"
Set aCell = Sheet1.Rows(1).Find(What:=strSearch, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not aCell Is Nothing Then
MsgBox "Value Found in Cell " & aCell.Address & _
" and the Cell Column Number is " & aCell.Column
End If
End Sub
SNAPSHOT
Try it
<?php
$str = "33,33,56,89,56,56";
echo substr_count($str, '56');
?>
<script type="text/javascript">
var temp = "33,33,56,89,56,56";
var count = temp.match(/56/g);
alert(count.length);
</script>
it is better to use json after post your resuest like below
var clien = new RestClient("https://smple.com/");
var request = new RestRequest("index", Method.POST);
request.AddHeader("Sign", signinstance);
request.AddJsonBody(JsonConvert.SerializeObject(yourclass));
var response = client.Execute<YourReturnclassSample>(request);
if (response.StatusCode == System.Net.HttpStatusCode.Created)
{
return Ok(response.Content);
}
What you actually created with:
MyType[] list = []
Was fixed size array (not list) with size of 0. You can create fixed size array of size for example 4 with:
MyType[] array = new MyType[4]
But there's no add method of course.
If you create list with def
it's something like creating this instance with Object
(You can read more about def
here). And []
creates empty ArrayList
in this case.
So using def list = []
you can then append new items with add()
method of ArrayList
list.add(new MyType())
Or more groovy way with overloaded left shift operator:
list << new MyType()
I have faced The same problem So I used the Git directly to push the project to GitHub.
In your android studio
Go to VCS=>Git=> Push: use the Branch Name You Commit and hit Push Button
Note: tested for android studio version 3.3
To avoid doing indexing from inside lambda, like:
rval = dict(map(lambda kv : (kv[0], ' '.join(kv[1])), rval.iteritems()))
You can also do:
rval = dict(map(lambda(k,v) : (k, ' '.join(v)), rval.iteritems()))
json_decode will return the same array that was originally encoded. For instanse, if you
$array = json_decode($json, true);
echo $array['countryId'];
OR
$obj= json_decode($json);
echo $obj->countryId;
These both will echo 84. I think json_encode and json_decode function names are self-explanatory...
Just adding a default custom WebViewClient
will do. This makes the WebView handle any loaded urls itself.
mWebView.setWebViewClient(new WebViewClient());
No, but the 32-bit version runs just fine on 64-bit Windows.
This code:
from scipy.stats import linregress
linregress(x,y) #x and y are arrays or lists.
gives out a list with the following:
slope : float
slope of the regression line
intercept : float
intercept of the regression line
r-value : float
correlation coefficient
p-value : float
two-sided p-value for a hypothesis test whose null hypothesis is that the slope is zero
stderr : float
Standard error of the estimate
int Number;
bool isNumber;
isNumber = int32.TryPase(textbox1.text, out Number);
if (!isNumber)
{
(code if not an integer);
}
else
{
(code if an integer);
}
You don't import methods in Java, only types:
import Dan.Vik;
class Kab
{
public static void main(String args[])
{
Vik Sam = new Vik();
Sam.disp();
}
}
The exception is so-called "static imports", which let you import class (static
) methods from other types.
I was going out of my mind when a rule was being ignored while others weren't. Run your CSS through a validator and look for parsing errors.
I accidentally used // for a comment instead of /* */ causing odd behavior. My IDE said nothing about it. I hope it helps someone.
If you can't use the delay
method as Robert Harvey suggested, you can use setTimeout
.
Eg.
setTimeout(function() {$("#test").animate({"top":"-=80px"})} , 1500); // delays 1.5 sec
setTimeout(function() {$("#test").animate({"opacity":"0"})} , 1500 + 1000); // delays 1 sec after the previous one
Here is the link to documentation INSERT ... ON DUPLICATE Statement.
I think you should add style="background:white;" to make looks like it is writable
<input type="text" size="23" name="dateMonthly" id="dateMonthly" readonly="readonly" style="background:white;"/>
SELECT
t1.*
FROM
table_name AS t1
LEFT JOIN table_name AS t2 ON (
t2.group_by_column = t1.group_by_column
-- group_by_column is the column you would use in the GROUP BY statement
AND
t2.order_by_column < t1.order_by_column
-- order_by_column is column you would use in the ORDER BY statement
-- usually is the autoincremented key column
)
WHERE
t2.group_by_column IS NULL;
With MySQL v8+ you could use window functions
Try:
if (typeof($("#myButton").click) != "function")
{
$("#myButton").click(onButtonClicked);
}
Use the date_trunc
method to truncate off the day (or whatever else you want, e.g., week, year, day, etc..)
Example of grouping sales from orders by month:
select
SUM(amount) as sales,
date_trunc('month', created_at) as date
from orders
group by date
order by date DESC;
I'm using MVC3/EntityFramework as back-end, the front-end consumes all of my project controllers via jquery, posting directly (using $.post) doesnt requires the data encription, when you pass params directly other than URL hardcoded. I already tested several chars i even sent an URL(this one http://www.ihackforfun.eu/index.php?title=update-on-url-crazy&more=1&c=1&tb=1&pb=1) as a parameter and had no issue at all even though encodeURIComponent works great when you pass all data in within the URL (hardcoded)
Hardcoded URL i.e.>
var encodedName = encodeURIComponent(name);
var url = "ControllerName/ActionName/" + encodedName + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;; // + name + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;
Otherwise dont use encodeURIComponent and instead try passing params in within the ajax post method
var url = "ControllerName/ActionName/";
$.post(url,
{ name: nameVal, fkKeyword: keyword, description: descriptionVal, linkUrl: linkUrlVal, includeMetrics: includeMetricsVal, FKTypeTask: typeTask, FKProject: project, FKUserCreated: userCreated, FKUserModified: userModified, FKStatus: status, FKParent: parent },
function (data) {.......});
Turns out, when the table name is different than the model name, you have to change the annotations to:
@Entity
@Table(name = "table_name")
class WhateverNameYouWant {
...
Instead of simply using the @Entity annotation.
What was weird for me, is that the class it was trying to convert to didn't exist. This worked for me.
From all my searching around, I strongly say that the most practical, accurate and free data source is provided by GeoNames.
You can access their data in 2 ways:
SMTP -> FROM SERVER:
SMTP -> FROM SERVER:
SMTP -> ERROR: EHLO not accepted from server:
that's typical of trying to connect to a SSL service with a client that's not using SSL
SMTP Error: Could not authenticate.
no suprise there having failed to start an SMTP conversation authentigation is not an option,.
phpmailer doesn't do implicit SSL (aka TLS on connect, SMTPS) Short of rewriting smtp.class.php to include support for it there it no way to do what you ask.
Use port 587 with explicit SSL (aka TLS, STARTTLS) instead.
df3.set_value(1, 'B', abc)
works for any dataframe. Take care of the data type of column 'B'. Eg. a list can not be inserted into a float column, at that case df['B'] = df['B'].astype(object)
can help.
Here is a practical example of Anchor tag with different
Lambda expressions have a type of Action<parameters>
(in case they don't return a value) or Func<parameters,return>
(in case they have a return value). In your case you have two input parameters, and you need to return a value, so you should use:
Func<FullTimeJob, Student, FullTimeJob>
There is a alter way. Open the excel file in Microsoft office Excel, and save it as "Excel 97-2003 Workbook". Then, use the new saved excel file in your file connection.
public ActionResult SomeAction(string start, string end)
The framework will map the query string parameters to the method parameters.
File -> Invalidate Caches / Restart -> Invalidate and Restart
worked for me.
In System.Web.Mvc.Html ( in System.Web.Mvc.dll ) the begin form is defined like:- Details
BeginForm ( this HtmlHelper htmlHelper, string actionName, string
controllerName, object routeValues, FormMethod method, object htmlAttributes)
Means you should use like this :
Html.BeginForm( string actionName, string controllerName,object routeValues, FormMethod method, object htmlAttributes)
So, it worked in MVC 4
@using (Html.BeginForm(null, null, new { @id = string.Empty }, FormMethod.Post,
new { @id = "signupform" }))
{
<input id="TRAINER_LIST" name="TRAINER_LIST" type="hidden" value="">
<input type="submit" value="Create" id="btnSubmit" />
}
It's as simple as is:
WebView webview = (WebView) findViewById(R.id.webview);
webview.loadUrl("file:///android_asset/some.html");
And your some.html needs to contain something like:
<link rel="stylesheet" type="text/css" href="style.css" />
HTML : Pass the whole body inside on click
div class="calculate" id="calculate">
<div class="button" id="button" onclick="myCode(this.body)"> CALCULATE ! </div>
</div>
Then write the JavaScript code inside the function "myCode()"
function myCode()
{
var bill = document.getElementById("currency").value ;
var people_count = document.getElementById("number1").value;
var select_value = document.getElementById("select").value;
var calculate = document.getElementById("calculate");
calculate.addEventListener("click" ,function()
{
console.log(bill);
console.log(people_count);
console.log(select_value);
});
}
you will get your values I am using visual studio code editor
How can I roll back my previous 4 commits locally in a branch?
Which means, you are not creating new branch and going into detached state. New way of doing that is:
git switch --detach revison
Well, for just getting the filename of your batch the easiest way would be to just use %~n0
.
@echo %~n0
will output the name (without the extension) of the currently running batch file (unless executed in a subroutine called by call
). The complete list of such “special” substitutions for path names can be found with help for
, at the very end of the help:
In addition, substitution of FOR variable references has been enhanced. You can now use the following optional syntax:
%~I - expands %I removing any surrounding quotes (") %~fI - expands %I to a fully qualified path name %~dI - expands %I to a drive letter only %~pI - expands %I to a path only %~nI - expands %I to a file name only %~xI - expands %I to a file extension only %~sI - expanded path contains short names only %~aI - expands %I to file attributes of file %~tI - expands %I to date/time of file %~zI - expands %I to size of file %~$PATH:I - searches the directories listed in the PATH environment variable and expands %I to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, then this modifier expands to the empty string
The modifiers can be combined to get compound results:
%~dpI - expands %I to a drive letter and path only %~nxI - expands %I to a file name and extension only %~fsI - expands %I to a full path name with short names only
To precisely answer your question, however: Substrings are done using the :~start,length
notation:
%var:~10,5%
will extract 5 characters from position 10 in the environment variable %var%
.
NOTE: The index of the strings is zero based, so the first character is at position 0, the second at 1, etc.
To get substrings of argument variables such as %0
, %1
, etc. you have to assign them to a normal environment variable using set
first:
:: Does not work:
@echo %1:~10,5
:: Assign argument to local variable first:
set var=%1
@echo %var:~10,5%
The syntax is even more powerful:
%var:~-7%
extracts the last 7 characters from %var%
%var:~0,-4%
would extract all characters except the last four which would also rid you of the file extension (assuming three characters after the period [.
]).See help set
for details on that syntax.
What was EXTREMLY HELPFUL to me on this way are the source codes for Capture2Text project. http://sourceforge.net/projects/capture2text/files/Capture2Text/.
BTW: Kudos to it's author for sharing such a painstaking algorithm.
Pay special attention to the file Capture2Text\SourceCode\leptonica_util\leptonica_util.c - that's the essence of image preprocession for this utility.
If you will run the binaries, you can check the image transformation before/after the process in Capture2Text\Output\ folder.
P.S. mentioned solution uses Tesseract for OCR and Leptonica for preprocessing.
Please read and strongly consider my advice in the comments of your post. That being said, if you still have a good reason to do this, check out this list of crypto modules for Node. It has modules for dealing with both sha1 and base64.
I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.
Bootstrap requires a specific file structure to work. I see from your code you have this:
<link href="bootstrap.css" rel="stylesheet" media="screen">
Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.
But first, let me recommend you setup your folder structure like so:
/css <-- Bootstrap.css here
/fonts <-- Bootstrap fonts here
/img
/js <-- Bootstrap JavaScript here
index.html
If you notice, this is also how Bootstrap structures its files in its download ZIP.
You then include your Bootstrap file like so:
<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">
Depending on your server structure or what you're going for.
The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).
The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.
So, why do this?
Bootstrap.css has this specific line for Glyphfonts:
@font-face {
font-family: 'Glyphicons Halflings';
src: url('../fonts/glyphicons-halflings-regular.eot');
src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}
What you can see is that that Glyphfonts are loaded by going up one directory ../
and then looking for a folder called /fonts
and THEN loading the font file.
The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:
/fonts
Bootstrap.css
index.html
The CSS file is going one level deeper than looking for a /fonts
folder.
So, let's say the actual location of these files are:
C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html
The CSS file would technically be looking for a folder at:
C:\fonts
but your folder is actually in:
C:\www\fonts
So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.
When you get that fixed, your HTML should simply be:
<span class="glyphicon glyphicon-comment"></span>
Note, you need both classes. The first class glyphicon
sets up the basic styles while glyphicon-comment
sets the specific image.
CREATE TABLE tbl_PersonalDetail
(ID INT IDENTITY ,[Date] nvarchar(20), Name nvarchar(20), GenderID int);
INSERT INTO Tbl_PersonalDetail VALUES(N'18-4-2015', N'Monay', 2),
(N'31-3-2015', N'Monay', 2),
(N'28-12-2015', N'Monay', 2),
(N'19-4-2015', N'Monay', 2)
DECLARE @Date Nvarchar(200)
SET @Date = (SELECT [Date] FROM Tbl_PersonalDetail WHERE ID = 2)
Update Tbl_PersonalDetail SET [Date] = (REPLACE(@Date , '-','/')) WHERE ID = 2
I had the same error, with URLs containing non-ascii chars (bytes with values > 128), my solution:
url = url.decode('utf8').encode('utf-8')
Note: utf-8, utf8 are simply aliases . Using only 'utf8' or 'utf-8' should work in the same way
In my case, worked for me, in Python 2.7, I suppose this assignment changed 'something' in the str
internal representation--i.e., it forces the right decoding of the backed byte sequence in url
and finally puts the string into a utf-8 str
with all the magic in the right place.
Unicode in Python is black magic for me.
Hope useful
For the space complexity of O(1)
and time complexity of O(N)
and if the array can be modified then it could be as follows:
public int getFirstSmallestPositiveNumber(int[] arr) {
// set positions of non-positive or out of range elements as free (use 0 as marker)
for (int i = 0; i < arr.length; i++) {
if (arr[i] <= 0 || arr[i] > arr.length) {
arr[i] = 0;
}
}
//iterate through the whole array again mapping elements [1,n] to positions [0, n-1]
for (int i = 0; i < arr.length; i++) {
int prev = arr[i];
// while elements are not on their correct positions keep putting them there
while (prev > 0 && arr[prev - 1] != prev) {
int next = arr[prev - 1];
arr[prev - 1] = prev;
prev = next;
}
}
// now, the first unmapped position is the smallest element
for (int i = 0; i < arr.length; i++) {
if (arr[i] != i + 1) {
return i + 1;
}
}
return arr.length + 1;
}
@Test
public void testGetFirstSmallestPositiveNumber() {
int[][] arrays = new int[][]{{1,-1,-5,-3,3,4,2,8},
{5, 4, 3, 2, 1},
{0, 3, -2, -1, 1}};
for (int i = 0; i < arrays.length; i++) {
System.out.println(getFirstSmallestPositiveNumber(arrays[i]));
}
}
Output:
5
6
2
var lowerCaseName = "Your Name".toLowerCase();
Try this:
const scope = angular.element(document.getElementById('YourElementId')).scope();
scope.$apply(function(){
scope.myfunction('test');
});
Or using regular expressions
"rmlike" <- function(...) {
names <- sapply(
match.call(expand.dots = FALSE)$..., as.character)
names = paste(names,collapse="|")
Vars <- ls(1)
r <- Vars[grep(paste("^(",names,").*",sep=""),Vars)]
rm(list=r,pos=1)
}
rmlike(temp)
Get gcc for Windows . However, you will have to install MinGW as well.
You can use Visual Studio 2010 express edition as well. Link here
A little late to game but thought I would add my 2 cents...
To avoid adding the extra mark-up of an inner span you could change the <h1>
display property from block
to inline
(catch is you would have ensure the elements after the <h1>
are block elements.
HTML
<h1>
The Last Will and Testament of
Eric Jones</h1>
<p>Some other text</p>
CSS
h1{
display:inline;
background-color:green;
color:#fff;
}
Result
JSFIDDLE
http://jsfiddle.net/J7VBV/
I struggled with many of the suggestions here before I simple created an instance of a new 'Fake' class that implements whatever interface you are trying to Mock out. Then you can simply set the value of the out parameter with the method itself.
There are two ways, one httpCookies
element in web.config
allows you to turn on requireSSL
which only transmit all cookies including session in SSL only and also inside forms authentication, but if you turn on SSL on httpcookies you must also turn it on inside forms configuration too.
Edit for clarity:
Put this in <system.web>
<httpCookies requireSSL="true" />
This version need not math library and checked the return value of clock_gettime().
#include <time.h>
#include <stdlib.h>
#include <stdint.h>
/**
* @return milliseconds
*/
uint64_t get_now_time() {
struct timespec spec;
if (clock_gettime(1, &spec) == -1) { /* 1 is CLOCK_MONOTONIC */
abort();
}
return spec.tv_sec * 1000 + spec.tv_nsec / 1e6;
}
Mmh ... there are many ways. I answer another network discovery question, and I write a little getting started.
Some tcpip stacks reply to icmp broadcasts. So you can try a PING to your network broadcast address.
For example, you have ip 192.168.1.1 and subnet 255.255.255.0
Note : on step 3. you get the lists of the MAC-to-IP cached entries, so there are also the hosts in your subnet you exchange data to in the last minutes, even if they don't reply to icmp_get.
Note (2) : now I am on linux. I am not sure, but it can be windows doesn't reply to icm_get via broadcast.
Is it the only one device attached to your pc ? Is it a router or another simple pc ?
git checkout [branchYouWantToReceiveBranch]
- checkout branch you want to receive branchgit merge [branchYouWantToMergeIntoBranch]
The pack syntax you are using here is for an image that is contained as a Resource within your application, not for a loose file in the file system.
You simply want to pass the actual path to the UriSource:
logo.UriSource = new Uri(@"\\myserver\folder1\Customer Data\sample.png");
INSERT INTO dbo.MyTable (ID, Name)
SELECT 123, 'Timmy'
UNION ALL
SELECT 124, 'Jonny'
UNION ALL
SELECT 125, 'Sally'
For SQL Server 2008, can do it in one VALUES clause exactly as per the statement in your question (you just need to add a comma to separate each values statement)...
Classes are objects with attributes (state, characteristic) and methods (functions, capacities) that are specific for that object (like the white color and fly powers, respectively, for a duck).
When you create an instance of a class, you can give it some initial personality (state or character like the name and the color of her dress for a newborn). You do this with __init__
.
Basically __init__
sets the instance characteristics automatically when you call instance = MyClass(some_individual_traits)
.
Remove the canvas dom and add in again.
function renderChart(label,data){
$("#canvas-wrapper").html("").html('<canvas id="storeSends"></canvas>');
var lineChartData = {
labels : label,
datasets : [
{
fillColor : "rgba(49, 195, 166, 0.2)",
strokeColor : "rgba(49, 195, 166, 1)",
pointColor : "rgba(49, 195, 166, 1)",
pointStrokeColor : "#fff",
data : data
}
]
}
var canvas = document.getElementById("storeSends");
var ctx = canvas.getContext("2d");
myLine = new Chart(ctx).Line(lineChartData, {
responsive: true,
maintainAspectRatio: false
});
}
If copy assignment operator of foo and bar is cheap (eg. int, char, pointer etc), you can do the following:
foo f; bar b;
BOOST_FOREACH(boost::tie(f,b),testing)
{
cout << "Foo is " << f << " Bar is " << b;
}
There is two simples ways to do that :
1-
select("users.birthdate",
DB::raw("FLOOR(DATEDIFF(CURRENT_DATE, STR_TO_DATE(users.birthdate, '%Y-%m-%d'))/365) AS age_way_one"),
2-
select("users.birthdate",DB::raw("(YEAR(CURDATE())-YEAR(users.birthdate)) AS age_way_two"))
it is not displayed in your application... it is under your emulator's logcat
Try SuperPuTTY. It is similar to puttycm.
You can either install PostgreSQL 9.2.1 in the pg_dump
client machine or just copy the $PGHOME
from the PostgreSQL server machine to the client machine. Note that there is no need to initdb
a new cluster in the client machine.
After you have finished installing the 9.2.1 software, remember to edit some environment variables in your .bash_profile
file.
I found the smoothest way to achieve this was using Pageant as the SSH agent and plink.
You need to have a putty session configured for the hostname that is used in your remote.
You will also need plink.exe which can be downloaded from the same site as putty.
And you need Pageant running with your key loaded. I have a shortcut to pageant in my startup folder that loads my SSH key when I log in.
When you install git-scm you can then specify it to use tortoise/plink rather than OpenSSH.
The net effect is you can open git-bash whenever you like and push/pull without being challenged for passphrases.
Same applies with putty and WinSCP sessions when pageant has your key loaded. It makes life a hell of a lot easier (and secure).
You can place .; in classpath in environmental variables to overcome this problem.
3 characters before and 4 characters after
$> echo "some123_string_and_another" | grep -o -P '.{0,3}string.{0,4}'
23_string_and
The compiler won't optimise away the indexer (i.e. if you use row["value"] twice), so yes it is slightly quicker to do:
object value = row["value"];
and then use value twice; using .GetType() risks issues if it is null...
DBNull.Value
is actually a singleton, so to add a 4th option - you could perhaps use ReferenceEquals - but in reality, I think you're worrying too much here... I don't think the speed different between "is", "==" etc is going to be the cause of any performance problem you are seeing. Profile your entire code and focus on something that matters... it won't be this.
Inside Activity, you can use
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitleTextColor(getResources().getColor(android.R.color.white));
If you love to choose xml for both title color & back arrow white just add this style in style.xml .
<style name="ToolBarStyle" parent="Theme.AppCompat">
<item name="android:textColorPrimary">@android:color/white</item>
<item name="android:textColorSecondary">@android:color/white</item>
<item name="actionMenuTextColor">@android:color/white</item>
</style>
And toolbar look like :
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
app:theme="@style/ToolBarStyle"
android:layout_height="?attr/actionBarSize"
/>
If you have an abstract URL string (not from the current window.location
), you can use this trick:
let yourUrlString = "http://example.com:3000/pathname/?search=test#hash";
let parser = document.createElement('a');
parser.href = yourUrlString;
parser.protocol; // => "http:"
parser.hostname; // => "example.com"
parser.port; // => "3000"
parser.pathname; // => "/pathname/"
parser.search; // => "?search=test"
parser.hash; // => "#hash"
parser.host; // => "example.com:3000"
Thanks to jlong
That's the way I'd prefer to see if I was maintaining your code. If you manage to find a faster solution, it's going to be very esoteric, and you should really bury it inside of a method that describes what it does.
(does it still work without the ToArray)?
Shutdown Hooks are unstarted threads that are registered with Runtime.addShutdownHook().JVM does not give any guarantee on the order in which shutdown hooks are started.For more info refer http://techno-terminal.blogspot.in/2015/08/shutdown-hooks.html
if somebody wants to change the battery and text color of the status bar like the below image:
you can use the following code in the appdelegate class.
UINavigationBar.appearance().barTintColor = UIColor(red: 234.0/255.0, green: 46.0/255.0, blue: 73.0/255.0, alpha: 1.0)
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white]
since there are so many options to write a phone number, one can just test that are enough digits in it, no matter how they are separated. i found 9 to 14 digits work for me:
^\D*(\d\D*){9,14}$
true:
false:
if you do want to support those last two examples - just remove the upper limit:
(\d\D*){9,}
(the ^$
are not needed if there's no upper limit)
Use the vbcrlf
for new line in SSSR. e.g.
= First(Fields!SAPName.Value, "DataSet1") & vbcrlf & First(Fields!SAPStreet.Value, "DataSet1") & vbcrlf & First(Fields!SAPCityPostal.Value, "DataSet1") & vbcrlf & First(Fields!SAPCountry.Value, "DataSet1")
for Kotlin, you can use Anko corountines:
update
doAsync {
...
}
deprecated
async(UI) {
// Code run on UI thread
// Use ref() instead of this@MyActivity
}
select right(rtrim('94342KMR'),3)
This will fetch the last 3 right string.
select substring(rtrim('94342KMR'),1,len('94342KMR')-3)
This will fetch the remaining Characters.
Combine two answers above, I finally make it work. Just be careful that the first single quote for each string is a backtick (`) in file sendmail.mc.
#Change to your mail config directory:
cd /etc/mail
#Make a auth subdirectory
mkdir auth
chmod 700 auth #maybe not, because I cannot apply cmd "cd auth" if I do so.
#Create a file with your auth information to the smtp server
cd auth
touch client-info
#In the file, put the following, matching up to your smtp server:
AuthInfo:your.isp.net "U:root" "I:user" "P:password"
#Generate the Authentication database, make both files readable only by root
makemap hash client-info < client-info
chmod 600 client-info
cd ..
#Add the following lines to sendmail.mc. Make sure you update your smtp server
#The first single quote for each string should be changed to a backtick (`) like this:
define(`SMART_HOST',`your.isp.net')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
FEATURE(`authinfo',`hash /etc/mail/auth/client-info')dnl
#run
sudo sendmailconfig
If you are facing this issue in case of Sqlite then
. I think this is the problem with version of Sqlite,I had the same problem when I was using this versions of SqLite
Version 2.2.4:
After checking version here I changed the version then it worked.
No error after using this
Version 2.1.2:
$(function() { $("#datepicker").datepicker({ maxDate: '0'}); });
FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.
Some references:
Though you can use any other client that allows automation.
You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).
Combine WinSCP scripting capabilities with Windows Scheduler:
A typical WinSCP script for upload (with SFTP) looks like:
open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close
With FTP, just replace the sftp://
with the ftp://
and remove the -hostkey="..."
switch.
Similarly for download: How to schedule an automatic FTP download on Windows?
WinSCP can even generate a script from an imported FileZilla session.
For details, see the guide to FileZilla automation.
(I'm the author of WinSCP)
Another option, if you are using SFTP, is the psftp.exe
client from PuTTY suite.
The issue of changing the context path of a Spring application is handled very well in the post titled Spring Boot Change Context Path
Basically the post discusses multiple ways of realizing this viz.
Don't use sprintf.
It will overflow your String-Buffer and crash your Program.
Always use snprintf
DateTime dt1 = DateTime.ParseExact([YourDate], "dd-MM-yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
Note the use of HH (24-hour clock) rather than hh (12-hour clock), and the use of InvariantCulture because some cultures use separators other than slash.
For example, if the culture is de-DE, the format "dd/MM/yyyy" would expect period as a separator (31.01.2011).
If you are using the LESS or SASS Version of the Bootstrap. The most efficient way is to change the variable name, in the LESS or SASS file.
$navbar-default-color: #FFFFFF !default;
$navbar-default-bg: #36669d !default;
$navbar-default-border: $navbar-default-bg !default;
This by far the most easiest and the most efficient way to change the Bootstraps Navbar. You need not write overrides, and the code remains clean.
You should check the $GOPATH
directory. If there is an empty directory of the package name, go get
doesn't download the package from the repository.
For example, If I want to get the github.com/googollee/go-socket.io
package from it's github repository, and there is already an empty directory github.com/googollee/go-socket.io
in the $GOPATH
, go get
doesn't download the package and then complains that there is no buildable Go source file in the directory. Delete any empty directory first of all.
Use my_map.count( key )
; it can only return 0 or 1, which is essentially the Boolean result you want.
Alternately my_map.find( key ) != my_map.end()
works too.
The dialect in the Hibernate context, will take care of database data type, like in orace it is integer however in SQL it is int, so this will by known in hibernate by this property, how to map the fields internally.
Method that will work. The way it is used above will not work.
declare @str varchar(50)='79136'
select
case
when @str LIKE replicate('[0-9]',LEN(@str)) then 1
else 0
end
declare @str2 varchar(50)='79D136'
select
case
when @str2 LIKE replicate('[0-9]',LEN(@str)) then 1
else 0
end
You have to catch the error just as you're already doing for your save()
call and since you're handling multiple errors here, you can try
multiple calls sequentially in a single do-catch block, like so:
func deleteAccountDetail() {
let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
let request = NSFetchRequest()
request.entity = entityDescription
do {
let fetchedEntities = try self.Context!.executeFetchRequest(request) as! [AccountDetail]
for entity in fetchedEntities {
self.Context!.deleteObject(entity)
}
try self.Context!.save()
} catch {
print(error)
}
}
Or as @bames53 pointed out in the comments below, it is often better practice not to catch the error where it was thrown. You can mark the method as throws
then try
to call the method. For example:
func deleteAccountDetail() throws {
let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
let request = NSFetchRequest()
request.entity = entityDescription
let fetchedEntities = try Context.executeFetchRequest(request) as! [AccountDetail]
for entity in fetchedEntities {
self.Context!.deleteObject(entity)
}
try self.Context!.save()
}
You need to call $compile
on the HTML string before inserting it into the DOM so that angular gets a chance to perform the binding.
In your fiddle, it would look something like this.
$("#dynamicContent").html(
$compile(
"<button ng-click='count = count + 1' ng-init='count=0'>Increment</button><span>count: {{count}} </span>"
)(scope)
);
Obviously, $compile
must be injected into your controller for this to work.
Read more in the $compile
documentation.
If you want to see output logs from all the services in your terminal.
docker-compose logs -t -f --tail <no of lines>
Eg.: Say you would like to log output of last 5 lines from all service
docker-compose logs -t -f --tail 5
If you wish to log output from specific services then it can be done as below:
docker-compose logs -t -f --tail <no of lines> <name-of-service1> <name-of-service2> ... <name-of-service N>
Usage:
Eg. say you have API and portal services then you can do something like below :
docker-compose logs -t -f --tail 5 portal api
Where 5 represents last 5 lines from both logs.
Ref: https://docs.docker.com/v17.09/engine/admin/logging/view_container_logs/
Assuming that you only have one pair of parenthesis.
string s = "User name (sales)";
int start = s.IndexOf("(") + 1;
int end = s.IndexOf(")", start);
string result = s.Substring(start, end - start);
Actually, to query the team_name
, just add it in brackets to the last line. Apart from that, it seems to work on Python 2.7.3 on command line.
from urllib2 import urlopen
import json
url = 'http://openligadb-json.heroku.com/api/teams_by_league_saison?league_saison=2012&league_shortcut=bl1'
response = urlopen(url)
json_obj = json.load(response)
for i in json_obj['team']:
print i['team_name']
This variant is better because you could not know whether file exists or not. You should send correct header when you know for certain that you can read contents of your file. Also, if you have branches of code that does not finish with '.end()', browser will wait until it get them. In other words, your browser will wait a long time.
var fs = require("fs");
var filename = "./index.html";
function start(resp) {
fs.readFile(filename, "utf8", function(err, data) {
if (err) {
// may be filename does not exists?
resp.writeHead(404, {
'Content-Type' : 'text/html'
});
// log this error into browser
resp.write(err.toString());
resp.end();
} else {
resp.writeHead(200, {
"Content-Type": "text/html"
});
resp.write(data.toString());
resp.end();
}
});
}
Every object is linked to a prototype object. When trying to access a property that does not exist, JavaScript will look in the object's prototype object for that property and return it if it exists.
The prototype
property of a function constructor refers to the prototype object of all instances created with that function when using new
.
In your first example, you are adding a property x
to each instance created with the A
function.
var A = function () {
this.x = function () {
//do something
};
};
var a = new A(); // constructor function gets executed
// newly created object gets an 'x' property
// which is a function
a.x(); // and can be called like this
In the second example you are adding a property to the prototype object that all the instances created with A
point to.
var A = function () { };
A.prototype.x = function () {
//do something
};
var a = new A(); // constructor function gets executed
// which does nothing in this example
a.x(); // you are trying to access the 'x' property of an instance of 'A'
// which does not exist
// so JavaScript looks for that property in the prototype object
// that was defined using the 'prototype' property of the constructor
In conclusion, in the first example a copy of the function is assigned to each instance. In the second example a single copy of the function is shared by all instances.
IIS 6.0 and previous versions :
ASP.NET integrated with IIS via an ISAPI extension, a C API ( C Programming language based API ) and exposed its own application and request processing model.
This effectively exposed two separate server( request / response ) pipelines, one for native ISAPI filters and extension components, and another for managed application components. ASP.NET components would execute entirely inside the ASP.NET ISAPI extension bubble AND ONLY for requests mapped to ASP.NET in the IIS script map configuration.
Requests to non ASP.NET content types:- images, text files, HTML pages, and script-less ASP pages, were processed by IIS or other ISAPI extensions and were NOT visible to ASP.NET.
The major limitation of this model was that services provided by ASP.NET modules and custom ASP.NET application code were NOT available to non ASP.NET requests
What's a SCRIPT MAP ?
Script maps are used to associate file extensions with the ISAPI handler that executes when that file type is requested. The script map also has an optional setting that verifies that the physical file associated with the request exists before allowing the request to be processed
A good example can be seen here
IIS 7 and above
IIS 7.0 and above have been re-engineered from the ground up to provide a brand new C++ API based ISAPI.
IIS 7.0 and above integrates the ASP.NET runtime with the core functionality of the Web Server, providing a unified(single) request processing pipeline that is exposed to both native and managed components known as modules ( IHttpModules )
What this means is that IIS 7 processes requests that arrive for any content type, with both NON ASP.NET Modules / native IIS modules
and ASP.NET modules
providing request processing in all stages This is the reason why NON ASP.NET content types (.html, static files ) can be handled by .NET modules.
IHttpModule
) that have the ability to execute for all application content, and provided an enhanced set of request processing services to your application.IHttpHandler
)Delete
operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirementsInsert
for arrays is basically Set
as mentioned in the beginningYou can also try like this.
Use Carbon\Carbon;
$created_at = "2014-06-26 04:07:31";
$date = Carbon::parse($created_at);
echo $date->format("Y-m-d");
If you want to change the user at git Bash .You just need to configure particular user and email(globally) at the git bash.
$ git config --global user.name "abhi"
$ git config --global user.email "[email protected]"
Note: No need to delete the user from Keychain .
Try adding "allowSyntheticDefaultImports": true
to your tsconfig.json
.
This basically tells the TypeScript compiler that it's okay to use an ES6 import statement, i. e.
import * as moment from 'moment/moment';
on a CommonJS module like Moment.js which doesn't declare a default export. The flag only affects type checking, not the generated code.
It is necessary if you use SystemJS as your module loader. The flag will be automatically turned on if you tell your TS compiler that you use SystemJS:
"module": "system"
This will also remove any errors thrown by IDEs if they are configured to make use of the tsconfig.json
.
As @Heinzi mentioned the character set of the response should be used.
var encoding = response.CharacterSet == ""
? Encoding.UTF8
: Encoding.GetEncoding(response.CharacterSet);
using (var stream = response.GetResponseStream())
{
var reader = new StreamReader(stream, encoding);
var responseString = reader.ReadToEnd();
}
You can use parseInt()
but, as mentioned, the radix (base) should be specified:
x = parseInt(x, 10);
y = parseInt(y, 10);
10 means a base-10 number.
See this link for an explanation of why the radix is necessary.
Inline version:
<a href="http://yoursite.com/" style="text-decoration:none">yoursite</a>
However remember that you should generally separate the content of your website (which is HTML), from the presentation (which is CSS). Therefore you should generally avoid inline styles.
See John's answer to see equivalent answer using CSS.
You have to know all the directories, or be able to use wildcard ..
javac dir1/*.java dir2/*.java dir3/dir4/*.java dir3/dir5/*.java dir6/*src/*.java
a = dict(one=1, two=2, three=3)
Providing keyword arguments as in this example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used.
open cmd as Administrator then try to register in both location
Building on @P-Lapointe solution, but making it extremely easy, you could use the maximum values from your data using max()
and then you re-use those maximum values to set the legend
xy coordinates. To make sure you don't get beyond the borders, you set up ylim
slightly over the maximum values.
a=c(rnorm(1000))
b=c(rnorm(1000))
par(mfrow=c(1,2))
plot(a,ylim=c(0,max(a)+1))
legend(x=max(a)+0.5,legend="a",pch=1)
plot(a,b,ylim=c(0,max(b)+1),pch=2)
legend(x=max(b)-1.5,y=max(b)+1,legend="b",pch=2)
Well, windows doesn't really have anything quite like it. Especially since fork can be used to conceptually create a thread or a process in *nix.
So, I'd have to say:
CreateProcess()
/CreateProcessEx()
and
CreateThread()
(I've heard that for C applications, _beginthreadex()
is better).
Do you consider [1,2]
to intersect with [1, [2]]
? That is, is it only the numbers you care about, or the list structure as well?
If only the numbers, investigate how to "flatten" the lists, then use the set()
method.
function valid(id)
{
var textVal=document.getElementById(id).value;
if (!textVal.match("Tryit")
{
alert("Field says Tryit");
return false;
}
else
{
return true;
}
}
Use this for expressing things