i dont know whether it is relevant to your issue, i got similar issue which i got solved by
1) In eclipse right click server and clean
if it still didnt work
2) export the project and delete the project create the project with same name and import the project and add the project to server and run.
I assume you would need the value as string. You could use the code below. It will always return give you the two digit minutes as string.
var date = new Date(date);
var min = date.getMinutes();
if (min < 10) {
min = '0' + min;
} else {
min = min + '';
}
console.log(min);
Hope this helps.
Dumping object content as JSON can be achieved without using ngFor
. Example:
Object
export class SomeComponent implements OnInit {
public theObject: any = {
simpleProp: 1,
complexProp: {
InnerProp1: "test1",
InnerProp2: "test2"
},
arrayProp: [1, 2, 3, 4]
};
Markup
<div [innerHTML]="theObject | json"></div>
Output (ran through a beautifier for better readability, otherwise it is output in a single row)
{
"simpleProp": 1,
"complexProp": {
"InnerProp1": "test1",
"InnerProp2": "test2"
},
"arrayProp": [
1,
2,
3,
4
]
}
I have also discovered a JSON formatter and viewer that displays larger JSON data more readable (similar to JSONView Chrome extension): https://www.npmjs.com/package/ngx-json-viewer
<ngx-json-viewer [json]="someObject" [expanded]="false"></ngx-json-viewer>
The question asks which characters are allowed in GET parameters without encoding or escaping them.
According to RFC3986 (general URL syntax) and RFC7230, section 2.7.1 (HTTP/S URL syntax) the only characters you need to percent-encode are those outside of the query set, see the definition below.
However, there are additional specifications like HTML5, Web forms, and the obsolete Indexed search, W3C recommendation. Those documents add a special meaning to some characters notably, to symbols like = & + ;.
Other answers here suggest that most of the reserved characters should be encoded, including "/" "?". That's not correct. In fact, RFC3986, section 3.4 advises against percent-encoding "/" "?" characters.
it is sometimes better for usability to avoid percent- encoding those characters.
RFC3986 defines query component as:
query = *( pchar / "/" / "?" )
pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
pct-encoded = "%" HEXDIG HEXDIG
sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
A percent-encoding mechanism is used to represent a data octet in a component when that octet's corresponding character is outside the allowed set or is being used as a delimiter of, or within, the component.
The conclusion is that XYZ part should encode:
special: # % = & ;
Space
sub-delims
out of query set: [ ]
non ASCII encodable characters
Unless special symbols = & ; are key=value separators.
Encoding other characters is allowed but not necessary.
<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'th,zh-CN,zh-TW', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
You can use tuples like this: SELECT * FROM table WHERE (Col, 1) IN ((123,1),(123,1),(222,1),....)
There are no restrictions on number of these. It compares pairs.
I know this is quite an old question -
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Let's say, you want to extract the first 2 rows and first 3 columns
A_NEW = A[0:2, 0:3]
A_NEW = [[1, 2, 3],
[4, 5, 6]]
Understanding the syntax
A_NEW = A[start_index_row : stop_index_row,
start_index_column : stop_index_column)]
If one wants row 2 and column 2 and 3
A_NEW = A[1:2, 1:3]
Reference the numpy indexing and slicing article - Indexing & Slicing
This is what I'm teaching my students tomorrow. After years of looking at this stuff... ie all of the documentation above http://www.cpearson.com/excel/errorhandling.htm comes to mind as an excellent one...
I hope this summarizes it for others. There is an Err
object and an active (or inactive) ErrorHandler
. Both need to be handled and reset for new errors.
Paste this into a workbook and step through it with F8.
Sub ErrorHandlingDemonstration()
On Error GoTo ErrorHandler
'this will error
Debug.Print (1 / 0)
'this will also error
dummy = Application.WorksheetFunction.VLookup("not gonna find me", Range("A1:B2"), 2, True)
'silly error
Dummy2 = "string" * 50
Exit Sub
zeroDivisionErrorBlock:
maybeWe = "did some cleanup on variables that shouldnt have been divided!"
' moves the code execution to the line AFTER the one that errored
Resume Next
vlookupFailedErrorBlock:
maybeThisTime = "we made sure the value we were looking for was in the range!"
' moves the code execution to the line AFTER the one that errored
Resume Next
catchAllUnhandledErrors:
MsgBox(thisErrorsDescription)
Exit Sub
ErrorHandler:
thisErrorsNumberBeforeReset = Err.Number
thisErrorsDescription = Err.Description
'this will reset the error object and error handling
On Error GoTo 0
'this will tell vba where to go for new errors, ie the new ErrorHandler that was previous just reset!
On Error GoTo ErrorHandler
' 11 is the err.number for division by 0
If thisErrorsNumberBeforeReset = 11 Then
GoTo zeroDivisionErrorBlock
' 1004 is the err.number for vlookup failing
ElseIf thisErrorsNumberBeforeReset = 1004 Then
GoTo vlookupFailedErrorBlock
Else
GoTo catchAllUnhandledErrors
End If
End Sub
Hex, Linq-fu:
string.Concat(ba.Select(b => b.ToString("X2")).ToArray())
UPDATE with the times
As noted by @RubenBartelink, the code that don't have a conversion of IEnumerable<string>
to an array: ba.Select(b => b.ToString("X2"))
does not work prior to 4.0, the same code is now working on 4.0.
This code...
byte[] ba = { 1, 2, 4, 8, 16, 32 };
string s = string.Concat(ba.Select(b => b.ToString("X2")));
string t = string.Concat(ba.Select(b => b.ToString("X2")).ToArray());
Console.WriteLine (s);
Console.WriteLine (t);
...prior to .NET 4.0, the output is:
System.Linq.Enumerable+<CreateSelectIterator>c__Iterator10`2[System.Byte,System.String]
010204081020
On .NET 4.0 onwards, string.Concat has an overload that accepts IEnumerable. Hence on 4.0, the above code will have same output for both variables s and t
010204081020
010204081020
Prior to 4.0, ba.Select(b => b.ToString("X2"))
goes to overload (object arg0)
, the way for the IEnumerable<string>
to go to a proper overload, i.e. (params string[] values)
, is we need to convert the IEnumerable<string>
to string array. Prior to 4.0, string.Concat has 10 overload functions, on 4.0 it is now 12
I have few suggession for the above mentioned error.
? Check executor memory assigned as an executor might have to deal with partitions requiring more memory than what is assigned.
? Try to see if more shuffles are live as shuffles are expensive operations since they involve disk I/O, data serialization, and network I/O
? Use Broadcast Joins
? Avoid using groupByKeys and try to replace with ReduceByKey
? Avoid using huge Java Objects wherever shuffling happens
I had to put some the displayed javascripts above inside the "document.ready" code. Otherwise they didn't work. Probably obvious for many, but not for me. So if you're testing look at that option.
<script type="text/javascript">
$(document).ready(function(){
//rest of the javascript code here
});
</script>
In some cases you may want the Rails root without having to load Rails.
For example, you get a quicker feedback cycle when TDD'ing models that do not depend on Rails by requiring spec_helper
instead of rails_helper
.
# spec/spec_helper.rb
require 'pathname'
rails_root = Pathname.new('..').expand_path(File.dirname(__FILE__))
[
rails_root.join('app', 'models'),
# Add your decorators, services, etc.
].each do |path|
$LOAD_PATH.unshift path.to_s
end
Which allows you to easily load Plain Old Ruby Objects from their spec files.
# spec/models/poro_spec.rb
require 'spec_helper'
require 'poro'
RSpec.describe ...
Depending on your needs, you can probably rely on node's path
module.
You may not be able to hit the filesystem (e.g. the file hasn't been created yet) and tbh you probably want to avoid hitting the filesystem unless you really need the extra validation. If you can make the assumption that what you are checking for follows .<extname>
format, just look at the name.
Obviously if you are looking for a file without an extname you will need to hit the filesystem to be sure. But keep it simple until you need more complicated.
const path = require('path');
function isFile(pathItem) {
return !!path.extname(pathItem);
}
In my case we were setting the div id as a number and setting the href="#123", this did not work.. adding a prefix to the id helped.
Example: This did not work-
<li> <a data-toggle="tab" href="#@i"> <li/>
...
<div class="tab-pane" id="#@i">
This worked:
<li><a data-toggle="tab" href="#prefix@i"><li/>
...
<div class="tab-pane" id="#prefix@i">
Define the parent with display: table
and the element itself with vertical-align: middle
and display: table-cell
.
If you still look for a solution, here's one that combined other answers (Bart Kiers and culmat) for your reference:
import javax.swing.*;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
public class HintTextField extends JTextField implements FocusListener
{
private String hint;
public HintTextField ()
{
this("");
}
public HintTextField(final String hint)
{
setHint(hint);
super.addFocusListener(this);
}
public void setHint(String hint)
{
this.hint = hint;
setUI(new HintTextFieldUI(hint, true));
//setText(this.hint);
}
public void focusGained(FocusEvent e)
{
if(this.getText().length() == 0)
{
super.setText("");
}
}
public void focusLost(FocusEvent e)
{
if(this.getText().length() == 0)
{
setHint(hint);
}
}
public String getText()
{
String typed = super.getText();
return typed.equals(hint)?"":typed;
}
}
class HintTextFieldUI extends javax.swing.plaf.basic.BasicTextFieldUI implements FocusListener
{
private String hint;
private boolean hideOnFocus;
private Color color;
public Color getColor()
{
return color;
}
public void setColor(Color color)
{
this.color = color;
repaint();
}
private void repaint()
{
if(getComponent() != null)
{
getComponent().repaint();
}
}
public boolean isHideOnFocus()
{
return hideOnFocus;
}
public void setHideOnFocus(boolean hideOnFocus)
{
this.hideOnFocus = hideOnFocus;
repaint();
}
public String getHint()
{
return hint;
}
public void setHint(String hint)
{
this.hint = hint;
repaint();
}
public HintTextFieldUI(String hint)
{
this(hint, false);
}
public HintTextFieldUI(String hint, boolean hideOnFocus)
{
this(hint, hideOnFocus, null);
}
public HintTextFieldUI(String hint, boolean hideOnFocus, Color color)
{
this.hint = hint;
this.hideOnFocus = hideOnFocus;
this.color = color;
}
protected void paintSafely(Graphics g)
{
super.paintSafely(g);
JTextComponent comp = getComponent();
if(hint != null && comp.getText().length() == 0 && (!(hideOnFocus && comp.hasFocus())))
{
if(color != null)
{
g.setColor(color);
}
else
{
g.setColor(Color.gray);
}
int padding = (comp.getHeight() - comp.getFont().getSize()) / 2;
g.drawString(hint, 5, comp.getHeight() - padding - 1);
}
}
public void focusGained(FocusEvent e)
{
if(hideOnFocus) repaint();
}
public void focusLost(FocusEvent e)
{
if(hideOnFocus) repaint();
}
protected void installListeners()
{
super.installListeners();
getComponent().addFocusListener(this);
}
protected void uninstallListeners()
{
super.uninstallListeners();
getComponent().removeFocusListener(this);
}
}
Usage:
HintTextField field = new HintTextField();
field.setHint("Here's a hint");
In addition to Lukasz Lysik's answer - LEFT-JOIN kind of SQL.
As I understand, if have id's: 1,2,4,5 it should return 3.
SELECT u.Id + 1 AS FirstAvailableId
FROM users u
LEFT JOIN users u1 ON u1.Id = u.Id + 1
WHERE u1.Id IS NULL
ORDER BY u.Id
LIMIT 0, 1
Hope it will help some of visitors, although post are rather old.
As I happened to be poorly satisfied by dos2unix, I rolled out my own simple utility. Apart of a few advantages in speed and predictability, the syntax is also a bit simpler :
endlines unix *
And if you want it to go down into subdirectories (skipping hidden dirs and non-text files) :
endlines unix -r .
endlines
is available here https://github.com/mdolidon/endlines
Do you have an Interface that your "UserService" class implements.
Your endpoints should specify an interface for the contract attribute:
contract="UserService.IUserService"
On Linux, with NuGet CLI, the commands are similar. To install my.nupkg, run
nuget add -Source some/directory my.nupkg
Then run dotnet restore
from that directory
dotnet restore --source some/directory Project.sln
or add that directory as a NuGet source
nuget sources Add -Name MySource -Source some/directory
and then tell msbuild
to use that directory with /p:RestoreAdditionalSources=MySource
or /p:RestoreSources=MySource
. The second switch will disable all other sources, which is good for offline scenarios, for example.
I would suggest two interesting lectures:
1.
The with
statement is used to wrap the execution of a block with methods defined by a context manager. This allows common try...except...finally
usage patterns to be encapsulated for convenient reuse.
2. You could do something like:
with open("foo.txt") as foo_file:
data = foo_file.read()
OR
from contextlib import nested
with nested(A(), B(), C()) as (X, Y, Z):
do_something()
OR (Python 3.1)
with open('data') as input_file, open('result', 'w') as output_file:
for line in input_file:
output_file.write(parse(line))
OR
lock = threading.Lock()
with lock:
# Critical section of code
3.
I don't see any Antipattern here.
Quoting Dive into Python:
try..finally is good. with is better.
4.
I guess it's related to programmers's habit to use try..catch..finally
statement from other languages.
Detect swipe in four direction
private float x1,x2,y1,y2;
static final int MIN_DISTANCE = 70;
and
switch(pSceneTouchEvent.getAction())
{
case MotionEvent.ACTION_DOWN:
x1 = pSceneTouchEvent.getX();
y1 = pSceneTouchEvent.getY();
break;
case MotionEvent.ACTION_UP:
x2 = pSceneTouchEvent.getX();
y2 = pSceneTouchEvent.getY();
float deltaX = x2 - x1;
float deltaY = y2 - y1;
if (deltaX > MIN_DISTANCE)
{
swipeLeftToRight();
}
else if( Math.abs(deltaX) > MIN_DISTANCE)
{
swipeRightToLeft();
}
else if(deltaY > MIN_DISTANCE){
swipeTopToBottom();
}
else if( Math.abs(deltaY) > MIN_DISTANCE){
swipeBottopmToTop();
}
break;
}
const data = { username: 'example' };
fetch('https://example.com/profile', {
method: 'POST', // or 'PUT'
headers: {
' Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
Maybe your mobile view port is not set.
Add following meta tag inside <head></head>
to allow menu to work on mobiles.
<meta name=viewport content="width=device-width, initial-scale=1">
Try using something like Server.Transfer("~/ErrorPage.aspx");
from within the Application_Error()
method of global.asax.cs
Then from within Page_Load()
of ErrorPage.aspx.cs you should be okay to do something like: Exception exception = Server.GetLastError().GetBaseException();
Server.Transfer()
seems to keep the exception hanging around.
You can use your own function for this.
try it: http://jsfiddle.net/xstLr7aj/
function string_to_slug(str) {
str = str.replace(/^\s+|\s+$/g, ''); // trim
str = str.toLowerCase();
// remove accents, swap ñ for n, etc
var from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;";
var to = "aaaaeeeeiiiioooouuuunc------";
for (var i=0, l=from.length ; i<l ; i++) {
str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
}
str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
.replace(/\s+/g, '-') // collapse whitespace and replace by -
.replace(/-+/g, '-'); // collapse dashes
return str;
}
$(document).ready(function() {
$('#test').submit(function(){
var val = string_to_slug($('#t').val());
alert(val);
return false;
});
});
On Windows, I prefer Ctrl + Alt + Down.
It selects the lines one by one and automatically starts the multi-line editor mode. It is a bit faster this way. If you have a lot of lines to edit then selecting the text and Ctrl + Shift + L is a better choice.
import re
p = re.compile("[a-z]")
for m in p.finditer('a1b2c3d4'):
print(m.start(), m.group())
I encountered issues where Safari wasn't firing "onchange" events on a text input field. I used a jQuery 1.7.2 "change" event and it didn't work either. I ended up using ZURB's textchange event. It works with mouseevents and can fire without leaving the field:
http://www.zurb.com/playground/jquery-text-change-custom-event
$('.inputClassToBind').bind('textchange', function (event, previousText) {
alert($(this).attr('id'));
});
var output = a.substring(0, position) + b + a.substring(position);
Edit: replaced .substr
with .substring
because .substr
is now a legacy function (per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr)
$(".input1").on('keyup', function (e) {
if (e.key === 'Enter' || e.keyCode === 13) {
// Do something
}
});
// e.key is the modern way of detecting keys
// e.keyCode is deprecated (left here for for legacy browsers support)
// keyup is not compatible with Jquery select(), Keydown is.
I would do this:
std::string a("Hello ");
std::string b("World");
std::string c = a + b;
Which compiles in VS2008.
As others described, the easiest solution is to put your UIImageView into a UIScrollView. I did this in the Interface Builder .xib file.
In viewDidLoad, set the following variables. Set your controller to be a UIScrollViewDelegate.
- (void)viewDidLoad {
[super viewDidLoad];
self.scrollView.minimumZoomScale = 0.5;
self.scrollView.maximumZoomScale = 6.0;
self.scrollView.contentSize = self.imageView.frame.size;
self.scrollView.delegate = self;
}
You are required to implement the following method to return the imageView you want to zoom.
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return self.imageView;
}
In versions prior to iOS9, you may also need to add this empty delegate method:
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
}
The Apple Documentation does a good job of describing how to do this:
I suggest Oj as it is waaaaaay faster than the standard JSON library.
Here's a list of all the ways I could think of to counting unique elements:
M = randi([1 7], [1500 1]);
t = tabulate(M);
counts1 = t(t(:,2)~=0, 2);
counts2_1 = hist( M, numel(unique(M)) );
counts2_2 = histc( M, unique(M) );
counts3 = accumarray(M, ones(size(M)), [], @sum);
%# or simply: accumarray(M, 1);
[MM idx] = unique( sort(M) );
counts4 = diff([0;idx]);
counts5 = arrayfun( @(x)sum(M==x), unique(M) );
counts6 = sum( bsxfun(@eq, M, unique(M)') )';
counts7 = full(sparse(M,1,1));
If you are using posix sed
Selection for any case for a pattern (converting the searched pattern with this sed than use the converted pattern in you wanted command using regex:
echo "${MyOrgPattern} | sed "s/[aA]/[aA]/g;s/[bB]/[bB]/g;s/[cC]/[cC]/g;s/[dD]/[dD]/g;s/[eE]/[eE]/g;s/[fF]/[fF]/g;s/[gG]/[gG]/g;s/[hH]/[hH]/g;s/[iI]/[iI]/g;s/[jJ]/[jJ]/g;s/[kK]/[kK]/g;s/[lL]/[lL]/g;s/[mM]/[mM]/g;s/[nN]/[nN]/g;s/[oO]/[oO]/g;s/[pP]/[pP]/g;s/[qQ]/[qQ]/g;s/[rR]/[rR]/g;s/[sS]/[sS]/g;s/[tT]/[tT]/g;s/[uU]/[uU]/g;s/[vV]/[vV]/g;s/[wW]/[wW]/g;s/[xX]/[xX]/g;s/[yY]/[yY]/g;s/[zZ]/[zZ]/g" | read -c MyNewPattern
YourInputStreamCommand | egrep "${MyNewPattern}"
convert in lower case
sed "s/[aA]/a/g;s/[bB]/b/g;s/[cC]/c/g;s/[dD]/d/g;s/[eE]/e/g;s/[fF]/f/g;s/[gG]/g/g;s/[hH]/h/g;s/[iI]/i/g;s/j/[jJ]/g;s/[kK]/k/g;s/[lL]/l/g;s/[mM]/m/g;s/[nN]/n/g;s/[oO]/o/g;s/[pP]/p/g;s/[qQ]/q/g;s/[rR]/r/g;s/[sS]/s/g;s/[tT]/t/g;s/[uU]/u/g;s/[vV]/v/g;s/[wW]/w/g;s/[xX]/x/g;s/[yY]/y/g;s/[zZ]/z/g"
same for uppercase replace lower letter between // by upper equivalent in the sed
Have fun
Compiler knows by type cast. Given a void *x
:
x+1
adds one byte to x
, pointer goes to byte x+1
(int*)x+1
adds sizeof(int)
bytes, pointer goes to byte x + sizeof(int)
(float*)x+1
addres sizeof(float)
bytes,
etc.Althought the first item is not portable and is against the Galateo of C/C++, it is nevertheless C-language-correct, meaning it will compile to something on most compilers possibly necessitating an appropriate flag (like -Wpointer-arith)
Just to clarify, do you have JAVA_HOME set as a system variable or set in Eclipse classpath variables? I'm pretty sure (but not totally sure!) that the system variable is used by the command line compiler (and Ant), but that Eclipse modifies this accroding to the JDK used
I ran across the same issue you did but the above answers did not solve my issue. The only way I was able to resolve it - was to make a class and use specific widths to trigger the wrapping for my specific use case. As an example, I provided a snippet below - but I found you will need to adjust it for the table in question - since I typically use multiple colspans depending on the layout. The reasoning I believe Bootstrap is failing - is because it removes the wrapping constraints to get a full table for the scrollbars. THe colspan must be tripping it up.
<style>
@media (max-width: 768px) { /* use the max to specify at each container level */
.specifictd {
width:360px; /* adjust to desired wrapping */
display:table;
white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}
}
I hope this helps
Here is sample code that might help you coping Column A to Column B:
UPDATE YourTable
SET ColumnB = ColumnA
WHERE
ColumnB IS NULL
AND ColumnA IS NOT NULL;
window.location.replace
is the best way to emulate a redirect:
function ShowComments(){
var movieShareId = document.getElementById('movieId');
window.location.replace("/comments.aspx?id=" + (movieShareId.textContent || movieShareId.innerText) + "/");
}
More information about why window.location.replace
is the best javascript redirect can be found right here.
Try this query:
SELECT cast(column_name as type) as col_identifier FROM tableName WHERE 1=1
Before comparing, the cast
function will convert varchar
type value to integer
type.
Be careful of a global temp table solution as this may fail if two users use the same routine at the same time as a global temp table can be seen by all users...
For some devices, if the default language is set different (an indian can set English (US)) then
context.getResources().getConfiguration().locale.getDisplayCountry();
will give wrong value .So this method is non reliable
Also, getNetworkCountryIso() method of TelephonyManager will not work on devices which don't have SIM card (WIFI tablets).
If a device doesn't have SIM then we can use Time Zone to get the country. For countries like India, this method will work
sample code used to check the country is India or not (Time zone id : asia/calcutta)
private void checkCountry() {
TelephonyManager telMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (telMgr == null)
return;
int simState = telMgr.getSimState();
switch (simState) {
//if sim is not available then country is find out using timezone id
case TelephonyManager.SIM_STATE_ABSENT:
TimeZone tz = TimeZone.getDefault();
String timeZoneId = tz.getID();
if (timeZoneId.equalsIgnoreCase(Constants.INDIA_TIME_ZONE_ID)) {
//do something
} else {
//do something
}
break;
//if sim is available then telephony manager network country info is used
case TelephonyManager.SIM_STATE_READY:
TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
if (tm != null) {
String countryCodeValue = tm.getNetworkCountryIso();
//check if the network country code is "in"
if (countryCodeValue.equalsIgnoreCase(Constants.NETWORK_INDIA_CODE)) {
//do something
}
else {
//do something
}
}
break;
}
}
I'm surprised that the answers here got so many upvotes when none of them really answer the question. Here's how to make sure that ONLY LATIN characters are in a given string.
const hasOnlyLetters = !!value.match(/^[a-z]*$/i);
The !!
takes transforms something that's not boolean into a boolean value. (It's exactly the same as applying a !
twice, and in fact you can use as many !
as you'd like to toggle the truthiness multiple times.)
As for the RegEx, here's the breakdown.
/.../i
The delimiter is a /
and the i
means to assess the statement in a case-insensitive fashion.^...$
The ^
means to look at the very beginning of a string. The $
means to look at the end of the string, and when used together, it means to consider the entire string. You can add more to the RegEx outside of these boundaries for things like appending/prepending a required suffix or prefix.[a-z]*
This part says to look for all lowercase letters. (The case-insensitive modifier means that we don't need to look at uppercase letters, too.) The *
at the end says that we should match whats in the brackets any number of times. That way "abc" will match instead of just "a" or "b", and so forth.Just put a
List<Person>
into the ViewBag and in the View cast it back to List
Note: Posted this answer because OP later stated in comments that they need to select the last two elements, not just the second to last one.
The :nth-child
CSS3 selector is in fact more capable than you ever imagined!
For example, this will select the last 2 elements of #container
:
#container :nth-last-child(-n+2) {}
But this is just the beginning of a beautiful friendship.
#container :nth-last-child(-n+2) {
background-color: cyan;
}
_x000D_
<div id="container">
<div>a</div>
<div>b</div>
<div>SELECT THIS</div>
<div>SELECT THIS</div>
</div>
_x000D_
I want to add that when using Windows you can use require './1.rb'
if the script is run local or from a mapped network drive but when run from an UNC \\servername\sharename\folder
path you need to use require_relative './1.rb'
.
I don't mingle in the discussion which to use for other reasons.
Here is a simple elegant solution that is working for me. You can set the z position of the navigation bar to below the view:
self.navigationController.navigationBar.layer.zPosition = -1;
Just remember to set it back to 0 when done.
This regex is very short and sweet for working.
/^([+]\d{2})?\d{10}$/
Ex: +910123456789 or 0123456789
-> /^ and $/ is for starting and ending
-> The ? mark is used for conditional formatting where before question mark is available or not it will work
-> ([+]\d{2}) this indicates that the + sign with two digits '\d{2}' here you can place digit as per country
-> after the ? mark '\d{10}' this says that the digits must be 10 of length change as per your country mobile number length
This is how this regex for mobile number is working.
+ sign is used for world wide matching of number.
if you want to add the space between than you can use the
[ ]
here the square bracket represents the character sequence and a space is character for searching in regex.
for the space separated digit you can use this regex
/^([+]\d{2}[ ])?\d{10}$/
Ex: +91 0123456789
Thanks ask any question if you have.
You can use the OfType
operator. It ignores null values in the source sequence. Just use the same type as MyProperty
and it won't filter out anything else.
// given:
// public T MyProperty { get; }
var nonNullItems = list.Select(x => x.MyProperty).OfType<T>();
I would advise against this though. If you want to pick non-null values, what can be more explicit than saying you want "the MyProperties from the list that are not null"?
Two ways
1)instantiate the first class
and getter for arrayList
or
2)Make arraylist as static
And finally
Use $_GET['email']
for parameters in URL.
Use $_POST['email']
for posted data to script.
Or use _$REQUEST
for both.
Also, as mentioned, you can use parse_url()
function that returns all parts of URL. Use a part called 'query' - there you can find your email parameter. More info: http://php.net/manual/en/function.parse-url.php
use this code it is working
// index.jsp or login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="login" method="post">
Username : <input type="text" name="username"><br>
Password : <input type="password" name="pass"><br>
<input type="submit"><br>
</form>
</body>
</html>
// authentication servlet class
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class auth extends HttpServlet {
private static final long serialVersionUID = 1L;
public auth() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String username = request.getParameter("username");
String pass = request.getParameter("pass");
String sql = "select * from reg where username='" + username + "'";
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/Exam",
"root", "");
Statement s = conn.createStatement();
java.sql.ResultSet rs = s.executeQuery(sql);
String un = null;
String pw = null;
String name = null;
/* Need to put some condition in case the above query does not return any row, else code will throw Null Pointer exception */
PrintWriter prwr1 = response.getWriter();
if(!rs.isBeforeFirst()){
prwr1.write("<h1> No Such User in Database<h1>");
} else {
/* Conditions to be executed after at least one row is returned by query execution */
while (rs.next()) {
un = rs.getString("username");
pw = rs.getString("password");
name = rs.getString("name");
}
PrintWriter pww = response.getWriter();
if (un.equalsIgnoreCase(username) && pw.equals(pass)) {
// use this or create request dispatcher
response.setContentType("text/html");
pww.write("<h1>Welcome, " + name + "</h1>");
} else {
pww.write("wrong username or password\n");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Angular will automatically update a component when it detects a variable change .
So all you have to do for it to "refresh" is ensure that the header has a reference to the new data. This could be via a subscription within header.component.ts
or via an @Input
variable...
an example...
main.html
<app-header [header-data]="headerData"></app-header>
main.component.ts
public headerData:int = 0;
ngOnInit(){
setInterval(()=>{this.headerData++;}, 250);
}
header.html
<p>{{data}}</p>
header.ts
@Input('header-data') data;
In the above example, the header will recieve the new data every 250ms and thus update the component.
For more information about Angular's lifecycle hooks, see: https://angular.io/guide/lifecycle-hooks
Open below mention path on your system and delete all your avd's (Virtual devices: Emulator)
C:\Users{Username}.android\avd
Note: - Deleting Emulator only from android studio will not delete all the spaces grab by their avd's. So delete all avd's from above given path and then create new emulator, if you needed.
\n
is a line break. /n
is not.
use of \n
with
Now if you are trying to echo string to the page:
echo "kings \n garden";
output will be:
kings garden
you won't get garden
in new line because PHP is a server-side language, and you are sending output as HTML, you need to create line breaks in HTML. HTML doesn't understand \n
. You need to use the nl2br()
function for that.
What it does is:
Returns string with
<br />
or<br>
inserted before all newlines (\r\n, \n\r, \n and \r).
echo nl2br ("kings \n garden");
kings
garden
Note Make sure you're echoing/printing
\n
in double quotes, else it will be rendered literally as \n. because php interpreter parse string in single quote with concept of as is
so "\n" not '\n'
Now if you echo to text file you can use just \n
and it will echo to a new line, like:
$myfile = fopen("test.txt", "w+") ;
$txt = "kings \n garden";
fwrite($myfile, $txt);
fclose($myfile);
output will be:
kings
garden
Unlike some browsers, Java follows the HTTPS specification strictly when it comes to the server identity verification (RFC 2818, Section 3.1) and IP addresses.
When using a host name, it's possible to fall back to the Common Name in the Subject DN of the server certificate, instead of using the Subject Alternative Name.
When using an IP address, there must be a Subject Alternative Name entry (of type IP address, not DNS name) in the certificate.
You'll find more details about the specification and how to generate such a certificate in this answer.
You can use ng-class
to add conditional classes.
HTML
<button id="button1" ng-click="alpha = true" ng-class="{alpha: alpha}">Button</button>
In your controller (to make sure the class is not shown by default)
$scope.alpha = false;
Now, when you click the button, the $scope.alpha variable is updated and ng-class will add the 'alpha' class to your button.
I solved the error by changing the port for the project.
I did the following steps:
1 - Right click on the project.
2 - Go to properties.
3 - Go to Server tab.
4 - On tab section, change the project URL for other port, like 8080 or 3000.
Good luck!
One simple way to get rid of the overwriting issue is to use File.AppendText
to append line at the end of the file as
void Main()
{
using (System.IO.StreamWriter sw = System.IO.File.AppendText("file.txt"))
{
string first = reader[0].ToString();
string second=image.ToString();
string csv = string.Format("{0},{1}\n", first, second);
sw.WriteLine(csv);
}
}
If you want PHP file caching only, you can use eAccelerator directly. Very easy to install and configure, and give great results.
But too bad, they removed the eaccelerator_put and eaccelerator_put from the latest version 0.9.6.
var exec = require('child_process').exec;
exec('pwd', function callback(error, stdout, stderr){
// result
});
In your service, add the following code.
@Override
public void onTaskRemoved(Intent rootIntent){
Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
restartServiceIntent.setPackage(getPackageName());
PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartServicePendingIntent);
super.onTaskRemoved(rootIntent);
}
If you are running your application just on localhost and it is not yet live, I believe it is very difficult to send mail using this.
Once you put your application online, I believe that this problem should be automatically solved. By the way,ini_set() helps you to change the values in php.ini during run time.
This is the same question as Failed to connect to mailserver at "localhost" port 25
also check this php mail function not working
The whole creating and dispatching events works, but since you are using the onchange
attribute, your life can be a little simpler:
http://jsfiddle.net/xwywvd1a/3/
var selEl = document.getElementById("sel");
selEl.options[1].selected = true;
selEl.onchange();
If you use the browser's event API (addEventListener, IE's AttachEvent, etc), then you will need to create and dispatch events as others have pointed out already.
Open in new Tab Solution:
"workbench.editor.showTabs": true
Since you are creating a markup as a string you don't have convert it into json. Just send it as it is combining all the array elements using implode
method. Try this.
PHP change
$response = array();
$response[] = "<a href=''>link</a>";
$response[] = 1;
echo implode("", $response);//<-----Combine array items into single string
JS (Change the dataType from json to html or just don't set it jQuery will figure it out)
$.ajax({
type: "POST",
dataType: "html",
url: "main.php",
data: "action=loadall&id=" + id,
success: function(response){
$('#main').html(response);
}
});
The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND
command on another connection, but it apparently was "not opening [it] up in sync with the client side".
Well, the main reason would be there was no synchronisation whatsoever. Calling:
cs.send("SEND " + FILE)
cs.close()
would just place the data into a OS buffer; close
would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep
after close
might mitigate the problem, but this is not synchronisation.
The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK
, or better PORT 36250
to indicate where to connect). This would make sure the server is already listening.
The other thing is you must check the return values of send
to make sure how many bytes was taken from your buffer. Or use sendall
.
(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)
In order for a percentage value to work for height, the parent's height must be determined. The only exception is the root element <html>
, which can be a percentage height. .
So, you've given all of your elements height, except for the <html>
, so what you should do is add this:
html {
height: 100%;
}
And your code should work fine.
* { padding: 0; margin: 0; }_x000D_
html, body, #fullheight {_x000D_
min-height: 100% !important;_x000D_
height: 100%;_x000D_
}_x000D_
#fullheight {_x000D_
width: 250px;_x000D_
background: blue;_x000D_
}
_x000D_
<div id=fullheight>_x000D_
Lorem Ipsum _x000D_
</div>
_x000D_
netstat will work (at the top something like this) tcp 0 0 10.x.xx.xx:ssh someipaddress.or.domainame:9379 ESTABLISHED
SWIFT 3
let VC1 = self.storyboard!.instantiateViewController(withIdentifier: "MyViewController") as! MyViewController
let navController = UINavigationController(rootViewController: VC1)
self.present(navController, animated:true, completion: nil)
Your Comparator would look like this:
public class GraduationCeremonyComparator implements Comparator<GraduationCeremony> {
public int compare(GraduationCeremony o1, GraduationCeremony o2) {
int value1 = o1.campus.compareTo(o2.campus);
if (value1 == 0) {
int value2 = o1.faculty.compareTo(o2.faculty);
if (value2 == 0) {
return o1.building.compareTo(o2.building);
} else {
return value2;
}
}
return value1;
}
}
Basically it continues comparing each successive attribute of your class whenever the compared attributes so far are equal (== 0
).
There is a better answer to this problem, though I could just break this down step-by-step.
You will need to fetch and checkout the latest upstream changes like so, e.g.:
git fetch upstream
git checkout upstream/master -b revert/john/foo_and_bar
Taking a look at the commit log, you should find something similar to this:
commit b76a5f1f5d3b323679e466a1a1d5f93c8828b269 Merge: 9271e6e a507888 Author: Tim Tom <[email protected]> Date: Mon Apr 29 06:12:38 2013 -0700 Merge pull request #123 from john/foo_and_bar Add foo and bar commit a507888e9fcc9e08b658c0b25414d1aeb1eef45e Author: John Doe <[email protected]> Date: Mon Apr 29 12:13:29 2013 +0000 Add bar commit 470ee0f407198057d5cb1d6427bb8371eab6157e Author: John Doe <[email protected]> Date: Mon Apr 29 10:29:10 2013 +0000 Add foo
Now you want to revert the entire pull request with the ability to unrevert later. To do so, you will need to take the ID of the merge commit.
In the above example the merge commit is the top one where it says "Merged pull request #123...".
Do this to revert the both changes ("Add bar" and "Add foo") and you will end up with in one commit reverting the entire pull request which you can unrevert later on and keep the history of changes clean:
git revert -m 1 b76a5f1f5d3b323679e466a1a1d5f93c8828b269
I'd do it this way:
@if (Request::path() == '/view')
// code
@endif
where '/view' is view name in routes.php.
A not perfect but one of the best and closest alternative to UDID (in Swift using iOS 8.1 and Xcode 6.1):
Generating a random UUID
let strUUID: String = NSUUID().UUIDString
And use KeychainWrapper library:
Add a string value to keychain:
let saveSuccessful: Bool = KeychainWrapper.setString("Some String", forKey: "myKey")
Retrieve a string value from keychain:
let retrievedString: String? = KeychainWrapper.stringForKey("myKey")
Remove a string value from keychain:
let removeSuccessful: Bool = KeychainWrapper.removeObjectForKey("myKey")
This solution uses the keychain, thus the record stored in the keychain will be persisted, even after the app is uninstalled and reinstalled. The only way of deleting this record is to Reset all contents and settings of the device. That is why I mentioned that this solution of substitution is not perfect but stays one of the best solution of replacement for UDID on iOS 8.1 using Swift.
lets suppose you need to place different rows of radio buttons in a form, each with separate attribute names ('option1','option2' etc) but the same class name. Perhaps you need them in multiple rows where they will each submit a value based on a scale of 1 to 5 pertaining to a question. you can write your javascript like so:
<script type="text/javascript">
var ratings = document.getElementsByClassName('ratings'); // we access all our radio buttons elements by class name
var radios="";
var i;
for(i=0;i<ratings.length;i++){
ratings[i].onclick=function(){
var result = 0;
radios = document.querySelectorAll("input[class=ratings]:checked");
for(j=0;j<radios.length;j++){
result = result + + radios[j].value;
}
console.log(result);
document.getElementById('overall-average-rating').innerHTML = result; // this row displays your total rating
}
}
</script>
I would also insert the final output into a hidden form element to be submitted together with the form.
You should use style instead of background color. Try searching holoeverywhere then I think this one will help you solve your problem
just change some of the 9patch resources to customize the edittext look and feel.
CREATE TABLE table_temp_list_objects AS
SELECT o.owner, o.object_name FROM sys.all_objects o WHERE o.object_type ='TABLE';
Solved, just use select method for the dataframe to select columns:
val df=spark.read.csv("C:\\Users\\Ahmed\\Desktop\\cabs_trajectories\\cabs_trajectories\\green\\2014\\green_tripdata_2014-09.csv")
val df1=df.select("_c0")
this would subset the first column of the dataframe
You can just create a new branch and switch onto it. Commit your changes then:
git branch dirty
git checkout dirty
// And your commit follows ...
Alternatively, you can also checkout an existing branch (just git checkout <name>
). But only, if there are no collisions (the base of all edited files is the same as in your current branch). Otherwise you will get a message.
You may try adding an additional argument of type HttpServletRequest
to the getUrlValue()
method:
@RequestMapping(value ="/",produces = "application/json")
public String getURLValue(HttpServletRequest request){
String test = request.getRequestURI();
return test;
}
cd /usr/local
git status
git status
til it's cleanbrew update
I've solved this issue by making use of the AddOrGetExisting method on the MemoryCache and the use of Lazy initialization.
Essentially, my code looks something like this:
static string GetCachedData(string key, DateTimeOffset offset)
{
Lazy<String> lazyObject = new Lazy<String>(() => SomeHeavyAndExpensiveCalculationThatReturnsAString());
var returnedLazyObject = MemoryCache.Default.AddOrGetExisting(key, lazyObject, offset);
if (returnedLazyObject == null)
return lazyObject.Value;
return ((Lazy<String>) returnedLazyObject).Value;
}
Worst case scenario here is that you create the same Lazy
object twice. But that is pretty trivial. The use of AddOrGetExisting
guarantees that you'll only ever get one instance of the Lazy
object, and so you're also guaranteed to only call the expensive initialization method once.
I hope this will help reloading/refreshing directive on value from parent scope
<html>
<head>
<!-- version 1.4.5 -->
<script src="angular.js"></script>
</head>
<body ng-app="app" ng-controller="Ctrl">
<my-test reload-on="update"></my-test><br>
<button ng-click="update = update+1;">update {{update}}</button>
</body>
<script>
var app = angular.module('app', [])
app.controller('Ctrl', function($scope) {
$scope.update = 0;
});
app.directive('myTest', function() {
return {
restrict: 'AE',
scope: {
reloadOn: '='
},
controller: function($scope) {
$scope.$watch('reloadOn', function(newVal, oldVal) {
// all directive code here
console.log("Reloaded successfully......" + $scope.reloadOn);
});
},
template: '<span> {{reloadOn}} </span>'
}
});
</script>
</html>
This is what I had to do:
ANDROID_HOME=C:\...\android-sdk
GRADLE_HOME=C:\...\gradle-1.6
PATH=...;%GRADLE_HOME%\bin;%ANDROID_HOME%\tools;%ANDROID_HOME%\platform-tools
syntax is of objective c is
returnObj = [object functionName: parameters];
Where object is the object which has the method you're calling. If you're calling it from the same object, you'll use 'self'. This tutorial might help you out in learning Obj-C.
In your case it is simply
[self score];
If you want to pass a parameter then it is like that
- (void)score(int x) {
// some code
}
and I have tried to call it in an other method like this:
- (void)score2 {
[self score:x];
}
Since you already have notepad++.exe
in your path. Create a shortcut in that folder named np
and point it to notepad++.exe
.
System.Reflection.Assembly.GetEntryAssembly().Location;
I'd like to add another reason that "catalina.sh" won't be able to connect to port 8005, apart from a firewall or a change in "server.xml": It takes Tomcat time to start listening on port 8005.
It's easy to reproduce this scenario If you start Tomcat and try to stop it immediately. Wait a few minutes and you'll see that the problem disappears because the port has opened.
A lot of users recommend selecting both the html and body tags for cross-browser compatibility, like so:
$('html, body').animate({ scrollTop: 0 }, callback);
This can trip you up though if you're counting on your callback running only once. It will in fact run twice because you've selected two elements.
If that is a problem for you, you can do something like this:
function scrollToTop(callback) {
if ($('html').scrollTop()) {
$('html').animate({ scrollTop: 0 }, callback);
return;
}
$('body').animate({ scrollTop: 0 }, callback);
}
The reason this works is in Chrome $('html').scrollTop()
returns 0, but not in other browsers such as Firefox.
If you don't want to wait for the animation to complete in the case that the scrollbar is already at the top, try this:
function scrollToTop(callback) {
if ($('html').scrollTop()) {
$('html').animate({ scrollTop: 0 }, callback);
return;
}
if ($('body').scrollTop()) {
$('body').animate({ scrollTop: 0 }, callback);
return;
}
callback();
}
From the composer site (it's clear enough)
require#
Lists packages required by this package. The package will not be installed unless those requirements can be met.
require-dev (root-only)#
Lists packages required for developing this package, or running tests, etc. The dev requirements of the root package are installed by default. Both install or update support the --no-dev option that prevents dev dependencies from being installed.
Using require-dev in Composer you can declare the dependencies you need for development/testing the project but don't need in production. When you upload the project to your production server (using git) require-dev
part would be ignored.
Also check this answer posted by the author and this post as well.
You answered your own question---unsrt
is to be used when you want references to ne listed in the order of appeareance.
But you might also want to have a look at natbib, an extremely flexible citation package. I can not imagine living without it.
EDIT 2
After three months we can say: no more official Google Apps in Genymotion and CyanogenMod-like method is only way to get Google Apps. However, you can still use the previous project of the Genymotion team: AndroVM (download mirror).
EDIT
Google apps will be removed from Genymotion in November. You can find more information on the Genymotion Google Plus page.
Choose virtual device with Google Apps:
Done:
Please check this - http://plnkr.co/edit/5Sx4k8tbWaO1qsdMEWYI?p=preview
Controller-
var app= angular.module('app', []);
app.controller('TestController', function($scope) {
this.arrayText = [{text:'Hello',},{text: 'world'}];
this.addText = function(text) {
if(text) {
var obj = {
text: text
};
this.arrayText.push(obj);
this.myText = '';
console.log(this.arrayText);
}
}
});
HTML
<form ng-controller="TestController as testCtrl" ng-submit="testCtrl.addText(testCtrl.myText)">
<input type="text" ng-model="testCtrl.myText" value="Lets go">
<button type="submit">Add</button>
<div ng-repeat="item in testCtrl.arrayText">
<span>{{item}}</span>
</div>
</form>
Simply follow the instructions given here:
Example install:
sudo apt-get install python-software-properties python g++ make sudo add-apt-repository ppa:chris-lea/node.js sudo apt-get update sudo apt-get install nodejs
It installs current stable Node on the current stable Ubuntu. Quantal (12.10) users may need to install the software-properties-common package for the
add-apt-repository
command to work:sudo apt-get install software-properties-common
As of Node.js v0.10.0, the nodejs package from Chris Lea's repo includes both npm and nodejs-dev.
Don't give sudo apt-get install nodejs npm
. Just sudo apt-get install nodejs
.
As a friend did for me today, here is what helped me (I am using Windows):
Press 'Setting' -> 'Project' -> 'Project Interpreter'. Here in the window on the right, there is a line with the title 'Project Interpreter' on it's left. Click this line and it will open several additional lines.
Now press the 'Show All' line. A window will open. In this window press the small '+' sign in the upper right corner.
A new window will open. On the left there are 4 tabs, press the most upper one, which says 'Virtualenv Environment'. Now, in the window on the right, mark the 'Existing Environment' option. The 'Interpreter' line will become well visible. Press the '...' button on the right of the line.
Now, a browsing window will open. Browse to the directory that you installed Python itself in. Not the one with PyCharm. When you get there, choose the 'python.exe' file and press OK (the window will disappear).
Press OK again (this window will disappear too).
Now in this window make sure the new line you created is marked, and press OK again.
Now, all the installed packages should be visible in the project interpreter, and are read by your program.
Get days between Current date to destination Date
SELECT DATEDIFF('2019-04-12', CURDATE()) AS days;
output
335
probably graded as a non-pythonic way to do this but this'll give the result you want in a line:
new_df = pd.DataFrame(zip(email,list))
Result:
email list
0 [email protected] [1.0, 0.0, 0.0]
1 [email protected] [2.0, 0.0, 0.0]
2 [email protected] [1.0, 0.0, 0.0]
3 [email protected] [4.0, 0.0, 3.0]
4 [email protected] [1.0, 5.0, 0.0]
I met this problem with TortoiseGit and TortoiseSVN. DropBox renamed its registry entry with more white spaces as prefix " " than I did for Tortoise.
Tortoise directly can open the registry editor by TortoiseGit > Settings > Icon Overlays > Overlay Handlers there click Start registry editor and rename entries so that the first in alphabetical order to be what you want.
same issue...resolved by dong the following
1.) close pm manager 2.) close Visual Studio 3.) Open Visual Studio 4.) Open pm manager
seems the trick is to close PM Manager before closing VS
If you want blanks and NULLS to be displayed as other text, such as "Uncategorized" you can simply say...
SELECT ISNULL(NULLIF([PropertyValue], ''), 'Uncategorized') FROM UserProfile
The above answers the main question very well. This answer is an extension of that and is of value to readers.
Simply you cannot do it with FF3.
The other option could be using applet or other controls to select and upload files.
Same problem happened with me . I started eclipse after many days , but it was not starting.just eclipse window flashing , no error nothing. After many trials , i just re-installed my jdk
. It worked for me, i think some of my java files were missing or damaged . Try by reinstalling your jdk version it may work as it worked for me.
String input = "2,1,3,4,5,10,100";
String[] strings = input.split(",");
int[] numbers = new int[strings.length];
for (int i = 0; i < numbers.length; i++)
{
numbers[i] = Integer.parseInt(strings[i]);
}
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
::
is used to link something ( a variable, a function, a class, a typedef etc...) to a namespace, or to a class.
if there is no left hand side before ::
, then it underlines the fact you are using the global namespace.
e.g.:
::doMyGlobalFunction();
This should do the trick:
df[- grep("REVERSE", df$Name),]
Or a safer version would be:
df[!grepl("REVERSE", df$Name),]
A simple way to achieve this is by using np.convolve
.
The idea behind this is to leverage the way the discrete convolution is computed and use it to return a rolling mean. This can be done by convolving with a sequence of np.ones
of a length equal to the sliding window length we want.
In order to do so we could define the following function:
def moving_average(x, w):
return np.convolve(x, np.ones(w), 'valid') / w
This function will be taking the convolution of the sequence x
and a sequence of ones of length w
. Note that the chosen mode
is valid
so that the convolution product is only given for points where the sequences overlap completely.
Some examples:
x = np.array([5,3,8,10,2,1,5,1,0,2])
For a moving average with a window of length 2
we would have:
moving_average(x, 2)
# array([4. , 5.5, 9. , 6. , 1.5, 3. , 3. , 0.5, 1. ])
And for a window of length 4
:
moving_average(x, 4)
# array([6.5 , 5.75, 5.25, 4.5 , 2.25, 1.75, 2. ])
convolve
work?Lets have a more in depth look at the way the discrete convolution is being computed.
The following function aims to replicate the way np.convolve
is computing the output values:
def mov_avg(x, w):
for m in range(len(x)-(w-1)):
yield sum(np.ones(w) * x[m:m+w]) / w
Which, for the same example above would also yield:
list(mov_avg(x, 2))
# [4.0, 5.5, 9.0, 6.0, 1.5, 3.0, 3.0, 0.5, 1.0]
So what is being done at each step is to take the inner product between the array of ones and the current window. In this case the multiplication by np.ones(w)
is superfluous given that we are directly taking the sum
of the sequence.
Bellow is an example of how the first outputs are computed so that it is a little clearer. Lets suppose we want a window of w=4
:
[1,1,1,1]
[5,3,8,10,2,1,5,1,0,2]
= (1*5 + 1*3 + 1*8 + 1*10) / w = 6.5
And the following output would be computed as:
[1,1,1,1]
[5,3,8,10,2,1,5,1,0,2]
= (1*3 + 1*8 + 1*10 + 1*2) / w = 5.75
And so on, returning a moving average of the sequence once all overlaps have been performed.
Basically the same solution as provided by Rutger Kassies, but using a more pythonic syntax:
fig, axs = plt.subplots(2,5, figsize=(15, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)
data = np.arange(250, 260)
for ax, d in zip(axs.ravel(), data):
ax.contourf(np.random.rand(10,10), 5, cmap=plt.cm.Oranges)
ax.set_title(str(d))
Git just stores the contents of the link (i.e. the path of the file system object that it links to) in a 'blob' just like it would for a normal file. It then stores the name, mode and type (including the fact that it is a symlink) in the tree object that represents its containing directory.
When you checkout a tree containing the link, it restores the object as a symlink regardless of whether the target file system object exists or not.
If you delete the file that the symlink references it doesn't affect the Git-controlled symlink in any way. You will have a dangling reference. It is up to the user to either remove or change the link to point to something valid if needed.
Opposite up is children(), but opposite in position is prepend(). Here a very good tutorial.
private void ClearFolder(string FolderName)
{
DirectoryInfo dir = new DirectoryInfo(FolderName);
foreach(FileInfo fi in dir.GetFiles())
{
try
{
fi.Delete();
}
catch(Exception) { } // Ignore all exceptions
}
foreach(DirectoryInfo di in dir.GetDirectories())
{
ClearFolder(di.FullName);
try
{
di.Delete();
}
catch(Exception) { } // Ignore all exceptions
}
}
If you know there are no sub-folders, something like this may be the easiest:
Directory.GetFiles(folderName).ForEach(File.Delete)
If you (or a helpful admin) runs Set-ExecutionPolicy
as administrator, the policy will be set for all users. (I would suggest "remoteSigned" rather than "unrestricted" as a safety measure.)
NB.: On a 64-bit OS you need to run Set-ExecutionPolicy
for 32-bit and 64-bit PowerShell separately.
For BIFF .xls files
application/vnd.ms-excel
For Excel2007 and above .xlsx files
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
This is how I do. I have added explanation to understand what the heck is going on.
Initialize Local Repository
first initialize Git with
git init
Add all Files for version control with
git add .
Create a commit with message of your choice
git commit -m 'AddingBaseCode'
Initialize Remote Repository
Link Remote repo with Local repo
Now use copied URL to link your local repo with remote GitHub repo. When you clone a repository with git clone, it automatically creates a remote connection called origin pointing back to the cloned repository. The command remote is used to manage set of tracked repositories.
git remote add origin https://github.com/hiteshsahu/Hassium-Word.git
Synchronize
Now we need to merge local code with remote code. This step is critical otherwise we won't be able to push code on GitHub. You must call 'git pull' before pushing your code.
git pull origin master --allow-unrelated-histories
Commit your code
Finally push all changes on GitHub
git push -u origin master
To Read from Keyboard (Standard Input) You can use Scanner is a class in java.util
package.
Scanner
package used for obtaining the input of the primitive types like int, double
etc. and strings
. It is the easiest way to read input in a Java program, though not very efficient.
object
of Scanner
class, we usually pass the
predefined object System.in
, which represents the standard input
stream (Keyboard).For example, this code allows a user to read a number from System.in:
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
Some Public methods in Scanner
class.
hasNext()
Returns true if this scanner has another token in its
input.nextInt()
Scans the next token of the input as an int.nextFloat()
Scans the next token of the input as a float.nextLine()
Advances this scanner past the current line and returns the input that was skipped. nextDouble()
Scans the next token of the input as a double.close()
Closes this scanner.For more details of Public methods in Scanner class.
Example:-
import java.util.Scanner; //importing class
class ScannerTest {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in); // Scanner object
System.out.println("Enter your rollno");
int rollno = sc.nextInt();
System.out.println("Enter your name");
String name = sc.next();
System.out.println("Enter your fee");
double fee = sc.nextDouble();
System.out.println("Rollno:" + rollno + " name:" + name + " fee:" + fee);
sc.close(); // closing object
}
}
Maybe silly, but check that you inline script is AFTER you include the script tags.
You can find if the textbox is disabled using is
method by passing :disabled
selector to it. Try this.
if($('textbox').is(':disabled')){
//textbox is disabled
}
One reason to always include a character set specification on every page containing text is to avoid cross site scripting vulnerabilities. In most cases the UTF-8 character set is the best choice for text, including HTML pages.
In the VSCode file tasks.json
, the "command": "tsc"
will try to find the tsc windows command script in some folder that it deems to be your modules folder.
If you know where the command npm install -g typescript
or npm install typescript
is saving to, I would recommend replacing:
"command": "tsc"
with
"command": "D:\\Projects\\TS\\Tutorial\\node_modules\\.bin\\tsc"
where D:\\...\\bin
is the folder that contains my tsc windows executable
Will determine where my vscode is natively pointing to right now to find the tsc and fix it I guess.
Use .rfind()
:
>>> s = 'hello'
>>> s.rfind('l')
3
Also don't use str
as variable name or you'll shadow the built-in str()
.
While a lot of others should be mentioned, Apache Wicket should be preferred.
Wicket doesn't just reduce lots of boilerplate code, it actually removes it entirely and you can work with excellent separation of business code and markup without mixing the two and a wide variety of other things you can read about from the website.
We can write directly too...
DECLARE @SearchLetter CHAR(1)
SET @SearchLetter = 'A'
SELECT *
FROM CUSTOMERS
WHERE CONTACTNAME LIKE @SearchLetter + '%'
AND REGION = 'WY'
or the following way as well if we have to append all the search characters then,
DECLARE @SearchLetter CHAR(1)
SET @SearchLetter = 'A' + '%'
SELECT *
FROM CUSTOMERS
WHERE CONTACTNAME LIKE @SearchLetter
AND REGION = 'WY'
Both these will work
Make sure your source file is saved in .csv format. I tried all the steps of adding the full path to the file, including and deleting the header=0, adding skiprows=0 but nothing works as I saved the excel file(data file) in workbook format and not in CSV format. so keep in mind to first check your file extension.
This code works:
$(".ui-button-text").live(
'hover',
function (ev) {
if (ev.type == 'mouseover') {
$(this).addClass("ui-state-hover");
}
if (ev.type == 'mouseout') {
$(this).removeClass("ui-state-hover");
}
});
may be to access this folder you need administrative rights.
so you have two options:-
p.s. : if you are using any of above two options you can access this folder by following these steps
open DDMS perspective -> your device ->(Select File Explorer from right window options) select package -> data -> data -> package name ->files
and from there you can pull up your file
Html.ActionLink
generates an <a href=".."></a>
tag automatically.
Url.Action
generates only an url.
For example:
@Html.ActionLink("link text", "actionName", "controllerName", new { id = "<id>" }, null)
generates:
<a href="/controllerName/actionName/<id>">link text</a>
and
@Url.Action("actionName", "controllerName", new { id = "<id>" })
generates:
/controllerName/actionName/<id>
Best plus point which I like is using Url.Action(...)
You are creating anchor tag by your own where you can set your own linked text easily even with some other html tag.
<a href="@Url.Action("actionName", "controllerName", new { id = "<id>" })">
<img src="<ImageUrl>" style"width:<somewidth>;height:<someheight> />
@Html.DisplayFor(model => model.<SomeModelField>)
</a>
The CONTINUE
statement is a new feature in 11g.
Here is a related question: 'CONTINUE' keyword in Oracle 10g PL/SQL
Your issue is, that you have an apache webserver already running that is already using port 80. So, you can either:
Kill apache: You should probably do this via /etc/init.d/apache2 stop
, rather than simply killing them.
Deploy your flask app in your apache process, as flask in apache describes.
To check if a particular key in the map exists, use the count
member function in one of the following ways:
m.count(key) > 0
m.count(key) == 1
m.count(key) != 0
The documentation for map::find
says: "Another member function, map::count
, can be used to just check whether a particular key exists."
The documentation for map::count
says: "Because all elements in a map container are unique, the function can only return 1 (if the element is found) or zero (otherwise)."
To retrieve a value from the map via a key that you know to exist, use map::at:
value = m.at(key)
Unlike map::operator[], map::at
will not create a new key in the map if the specified key does not exist.
For everyone still searching for a nice way to achieve this, the recommended way is the dump()
function from symfony/var-dumper
.
It is added to documentation since version 5.2: https://laravel.com/docs/5.2/helpers#method-dd
Checkout: What is a good pattern for using a Global Mutex in C#?
// unique id for global mutex - Global prefix means it is global to the machine
const string mutex_id = "Global\\{B1E7934A-F688-417f-8FCB-65C3985E9E27}";
static void Main(string[] args)
{
using (var mutex = new Mutex(false, mutex_id))
{
// edited by Jeremy Wiebe to add example of setting up security for multi-user usage
// edited by 'Marc' to work also on localized systems (don't use just "Everyone")
var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
var securitySettings = new MutexSecurity();
securitySettings.AddAccessRule(allowEveryoneRule);
mutex.SetAccessControl(securitySettings);
//edited by acidzombie24
var hasHandle = false;
try
{
try
{
// note, you may want to time out here instead of waiting forever
//edited by acidzombie24
//mutex.WaitOne(Timeout.Infinite, false);
hasHandle = mutex.WaitOne(5000, false);
if (hasHandle == false) return;//another instance exist
}
catch (AbandonedMutexException)
{
// Log the fact the mutex was abandoned in another process, it will still get aquired
}
// Perform your work here.
}
finally
{
//edit by acidzombie24, added if statemnet
if (hasHandle)
mutex.ReleaseMutex();
}
}
}
I think Traps are caused by the execution of current instruction and thus they are called as synchronous events. where as interrupts are caused by an independent instruction that is running in the processor which are related to external events and thus are known as asynchronous ones.
In Rails 2, I would have written:
validates_uniqueness_of :zipcode, :scope => :recorded_at
In Rails 3:
validates :zipcode, :uniqueness => {:scope => :recorded_at}
For multiple attributes:
validates :zipcode, :uniqueness => {:scope => [:recorded_at, :something_else]}
You can use a deadlock graph
and gather the information you require from the log file.
The only other way I could suggest is digging through the information by using EXEC SP_LOCK
(Soon to be deprecated), EXEC SP_WHO2
or the sys.dm_tran_locks
table.
SELECT L.request_session_id AS SPID,
DB_NAME(L.resource_database_id) AS DatabaseName,
O.Name AS LockedObjectName,
P.object_id AS LockedObjectId,
L.resource_type AS LockedResource,
L.request_mode AS LockType,
ST.text AS SqlStatementText,
ES.login_name AS LoginName,
ES.host_name AS HostName,
TST.is_user_transaction as IsUserTransaction,
AT.name as TransactionName,
CN.auth_scheme as AuthenticationMethod
FROM sys.dm_tran_locks L
JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
JOIN sys.objects O ON O.object_id = P.object_id
JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE resource_database_id = db_id()
ORDER BY L.request_session_id
http://www.sqlmag.com/article/sql-server-profiler/gathering-deadlock-information-with-deadlock-graph
You can find what you're looking for in the information schema: SQL Server 2005 System Tables and Views I think you need SQL Server 2005 or higher to use the approach described in this article, but a similar method can be used for earlier versions.
If you just need to insert a new row with a data from another row,
insert into ORDER_ITEM select * from ORDER_ITEM where ITEM_NUMBER =123;
.m2 directory on linux box usually would be $HOME/.m2
you could get the $HOME :
echo $HOME
or simply:
cd <enter>
to go to your home directory.
other information from maven site: http://maven.apache.org/download.html#Installation
This is what worked for me:
$.get({
method: 'GET',
url: 'api.php',
headers: {
'Content-Type': 'application/json',
},
// query parameters go under "data" as an Object
data: {
client: 'mikescafe'
}
});
will make a REST/AJAX call - > GET http://localhost:3000/api.php?client=mikescafe
Good Luck.
If using Newtonsoft.Json:
using Newtonsoft.Json;
using System.Net.Http;
using System.Text;
public static class Extensions
{
public static StringContent AsJson(this object o)
=> new StringContent(JsonConvert.SerializeObject(o), Encoding.UTF8, "application/json");
}
Example:
var httpClient = new HttpClient();
var url = "https://www.duolingo.com/2016-04-13/login?fields=";
var data = new { identifier = "username", password = "password" };
var result = await httpClient.PostAsync(url, data.AsJson())
The file basically contain data for two new tables.
Then you may find it simpler to just DTS (or SSIS, if this is SQL Server 2005+) the data over, if the two servers are on the same network.
If the two servers are not on the same network, you can backup the source database and restore it to a new database on the destination server. Then you can use DTS/SSIS, or even a simple INSERT INTO SELECT
, to transfer the two tables to the destination database.
.btn{
font-size: 20px;
color:black;
}
To summarize @larowlan, @VMTrooper, and @vahid chakoshy solutions:
#!/usr/bin/env bash
if [ "$#" -eq 2 ]; then
echo "$(echo "scale=2; $(curl https://api.github.com/repos/$1/$2 2>/dev/null \
| grep size | head -1 | tr -dc '[:digit:]') / 1024" | bc)MB"
elif [ "$#" -eq 3 ] && [ "$1" == "-z" ]; then
# For some reason Content-Length header is returned only on second try
curl -I https://codeload.github.com/$2/$3/zip/master &>/dev/null
echo "$(echo "scale=2; $(curl -I https://codeload.github.com/$2/$3/zip/master \
2>/dev/null | grep Content-Length | cut -d' ' -f2 | tr -d '\r') / 1024 / 1024" \
| bc)MB"
else
printf "Usage: $(basename $0) [-z] OWNER REPO\n\n"
printf "Get github repository size or, optionally [-z], the size of the zipped\n"
printf "master branch (`Download ZIP` link on repo page).\n"
exit 1
fi
Your connection string was probably overriden when you copied your new website version on the server. Please check the connection string in web.config and see if it is valid.
This works for me...
#region AddressOf
/// <summary>
/// Provides the current address of the given object.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static System.IntPtr AddressOf(object obj)
{
if (obj == null) return System.IntPtr.Zero;
System.TypedReference reference = __makeref(obj);
System.TypedReference* pRef = &reference;
return (System.IntPtr)pRef; //(&pRef)
}
/// <summary>
/// Provides the current address of the given element
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static System.IntPtr AddressOf<T>(T t)
//refember ReferenceTypes are references to the CLRHeader
//where TOriginal : struct
{
System.TypedReference reference = __makeref(t);
return *(System.IntPtr*)(&reference);
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
static System.IntPtr AddressOfRef<T>(ref T t)
//refember ReferenceTypes are references to the CLRHeader
//where TOriginal : struct
{
System.TypedReference reference = __makeref(t);
System.TypedReference* pRef = &reference;
return (System.IntPtr)pRef; //(&pRef)
}
/// <summary>
/// Returns the unmanaged address of the given array.
/// </summary>
/// <param name="array"></param>
/// <returns><see cref="IntPtr.Zero"/> if null, otherwise the address of the array</returns>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static System.IntPtr AddressOfByteArray(byte[] array)
{
if (array == null) return System.IntPtr.Zero;
fixed (byte* ptr = array)
return (System.IntPtr)(ptr - 2 * sizeof(void*)); //Todo staticaly determine size of void?
}
#endregion
I think that the problem is that you put #ifdef
instead of #ifndef
at the top of your header.h
file.
Save your workbook. If this code doesn't do what you want, the only way to go back is to close without saving and reopen.
Select the data you want to list in one column. Must be contiguous columns. May contain blank cells.
Press Alt+F11 to open the VBE
Press Control+R to view the Project Explorer
Navigate to the project for your workbook and choose Insert - Module
Paste this code in the code pane
Sub MakeOneColumn()
Dim vaCells As Variant
Dim vOutput() As Variant
Dim i As Long, j As Long
Dim lRow As Long
If TypeName(Selection) = "Range" Then
If Selection.Count > 1 Then
If Selection.Count <= Selection.Parent.Rows.Count Then
vaCells = Selection.Value
ReDim vOutput(1 To UBound(vaCells, 1) * UBound(vaCells, 2), 1 To 1)
For j = LBound(vaCells, 2) To UBound(vaCells, 2)
For i = LBound(vaCells, 1) To UBound(vaCells, 1)
If Len(vaCells(i, j)) > 0 Then
lRow = lRow + 1
vOutput(lRow, 1) = vaCells(i, j)
End If
Next i
Next j
Selection.ClearContents
Selection.Cells(1).Resize(lRow).Value = vOutput
End If
End If
End If
End Sub
Press F5 to run the code
Move your map variable into a scope where the event listener can use it. You are creating the map inside your initialize() function and nothing else can use it when created that way.
var map; //<-- This is now available to both event listeners and the initialize() function
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(40.5472,12.282715),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
I overcome this issue with if anybody interested. In myMain method i called my readasync method like
Dispatcher.BeginInvoke(new ThreadStart(() => ReadData()));
Everything is fine for me now.
You can use:
return (dateTocheck >= startDate && dateToCheck <= endDate);
Try replacing your movie param line with
<param name="movie" value="untitled_skin.swf&autoStart=false">
In the first case you are simply starting a new thread while in the second case you are entering in the thread pool.
The thread pool job is to share and recycle threads. It allows to avoid losing a few millisecond every time we need to create a new thread.
There are a several ways to enter the thread pool:
I'm assuming you want the new record to have a new primarykey
? If primarykey
is AUTO_INCREMENT
then just do this:
INSERT INTO table (col1, col2, col3, ...)
SELECT col1, col2, col3, ... FROM table
WHERE primarykey = 1
...where col1, col2, col3, ...
is all of the columns in the table except for primarykey
.
If it's not an AUTO_INCREMENT
column and you want to be able to choose the new value for primarykey
it's similar:
INSERT INTO table (primarykey, col2, col3, ...)
SELECT 567, col2, col3, ... FROM table
WHERE primarykey = 1
...where 567
is the new value for primarykey
.
I Got AutoFlash light with below simple Three Steps.
<uses-permission android:name="android.permission.CAMERA" /> <uses-feature android:name="android.hardware.camera" /> <uses-permission android:name="android.permission.FLASHLIGHT"/> <uses-feature android:name="android.hardware.camera.flash" android:required="false" />
In your Camera Code do this way.
//Open Camera
Camera mCamera = Camera.open();
//Get Camera Params for customisation
Camera.Parameters parameters = mCamera.getParameters();
//Check Whether device supports AutoFlash, If you YES then set AutoFlash
List<String> flashModes = parameters.getSupportedFlashModes();
if (flashModes.contains(android.hardware.Camera.Parameters.FLASH_MODE_AUTO))
{
parameters.setFlashMode(Parameters.FLASH_MODE_AUTO);
}
mCamera.setParameters(parameters);
mCamera.startPreview();
Build + Run —> Now Go to Dim light area and Snap photo, you should get auto flash light if device supports.
1: Prototype.observe
uses Element.addEventListener (see the source code)
2: You can override Element.addEventListener
to remember the added listeners (handy property EventListenerList
was removed from DOM3 spec proposal). Run this code before any event is attached:
(function() {
Element.prototype._addEventListener = Element.prototype.addEventListener;
Element.prototype.addEventListener = function(a,b,c) {
this._addEventListener(a,b,c);
if(!this.eventListenerList) this.eventListenerList = {};
if(!this.eventListenerList[a]) this.eventListenerList[a] = [];
this.eventListenerList[a].push(b);
};
})();
Read all the events by:
var clicks = someElement.eventListenerList.click;
if(clicks) clicks.forEach(function(f) {
alert("I listen to this function: "+f.toString());
});
And don't forget to override Element.removeEventListener
to remove the event from the custom Element.eventListenerList
.
3: the Element.onclick
property needs special care here:
if(someElement.onclick)
alert("I also listen tho this: "+someElement.onclick.toString());
4: don't forget the Element.onclick
content attribute: these are two different things:
someElement.onclick = someHandler; // IDL attribute
someElement.setAttribute("onclick","otherHandler(event)"); // content attribute
So you need to handle it, too:
var click = someElement.getAttribute("onclick");
if(click) alert("I even listen to this: "+click);
The Visual Event bookmarklet (mentioned in the most popular answer) only steals the custom library handler cache:
It turns out that there is no standard method provided by the W3C recommended DOM interface to find out what event listeners are attached to a particular element. While this may appear to be an oversight, there was a proposal to include a property called eventListenerList to the level 3 DOM specification, but was unfortunately been removed in later drafts. As such we are forced to looked at the individual Javascript libraries, which typically maintain a cache of attached events (so they can later be removed and perform other useful abstractions).
As such, in order for Visual Event to show events, it must be able to parse the event information out of a Javascript library.
Element overriding may be questionable (i.e. because there are some DOM specific features like live collections, which can not be coded in JS), but it gives the eventListenerList support natively and it works in Chrome, Firefox and Opera (doesn't work in IE7).
Try an LL
suffix on the number, the compiler may be casting it to an intermediate type as part of the parse. See http://gcc.gnu.org/onlinedocs/gcc/Long-Long.html
long long int i2 = 0x0000444400004444LL;
Additionally, the the compiler is discarding the leading zeros, so 0x000044440000
is becoming 0x44440000
, which is a perfectly acceptable 32-bit integer (which is why you aren't seeing any warnings prior to f2
).
Let's say you have these lines of code:
test line one
test line two
test line three
test line four
Using Search and Replace Ctrl+H with Regex let's find this: ^
and replace it with "
, we'll have this:
"test line one
"test line two
"test line three
"test line four
Now let's search this: $
and replace it with "
, now we'll have this:
"test line one"
"test line two"
"test line three"
"test line four"
Simple Alternative
Just use a query string.
Routing
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Controller
public class TestController : ApiController
{
public IEnumerable<SomeViewModel> Get()
{
}
public SomeViewModel GetById(int objectId)
{
}
}
Requests
GET /Test
GET /Test?objectId=1
Note
Keep in mind that the query string param should not be "id" or whatever the parameter is in the configured route.
git log ..otherbranch
git diff ...otherbranch
gitk ...otherbranch
Empty string implies HEAD
, so that's why just ..otherbranch
instead of HEAD..otherbranch
.
The two vs. three dots have slightly different meaning for diff than for the commands that list revisions (log, gitk etc.). For log and others two dots (a..b
) means everything that is in b
but not a
and three dots (a...b
) means everything that is in only one of a
or b
. But diff works with two revisions and there the simpler case represented by two dots (a..b
) is simple difference from a
to b
and three dots (a...b
) mean difference between common ancestor and b
(git diff $(git merge-base a b)..b
).
Remove the date()
part
SELECT name, datum
FROM tasks
WHERE datum >= NOW()
and if you use a specific date, don't forget the quotes around it and use the proper format with :
SELECT name, datum
FROM tasks
WHERE datum >= '2014-05-18 15:00:00'
You can use the .rows
property and check it's .length
, like this:
var rowCount = document.getElementById('myTableID').rows.length;
The git diff
command typically expects one or more commit hashes to generate your diff. You seem to be supplying the name of a remote.
If you had a branch named origin
, the commit hash at tip of the branch would have been used if you supplied origin
to the diff command, but currently (with no corresponding branch) the command will produce the error you're seeing. It may be the case that you were previously working with a branch named origin
.
An alternative, if you're trying to view the difference between your local branch, and a branch on a remote would be something along the lines of:
git diff origin/<branchname>
git diff <branchname> origin/<branchname>
Edit: Having read further, I realise I'm slightly wrong, git diff origin
is shorthand for diffing against the head of the specified remote, so git diff origin
= git diff origin/HEAD
(compare local git branch with remote branch?, Why is "origin/HEAD" shown when running "git branch -r"?)
It sounds like your origin does not have a HEAD, in my case this is because my remote is a bare repository that has never had a HEAD set.
Running git branch -r
will show you if origin/HEAD
is set, and if so, which branch it points at (e.g. origin/HEAD -> origin/<branchname>
).
Or you just put the variable in parenthesis
DECLARE @top INT = 10;
SELECT TOP (@Top) *
FROM <table_name>;
Handling polymorphism is either model-bound or requires lots of code with various custom deserializers. I'm a co-author of a JSON Dynamic Deserialization Library that allows for model-independent json deserialization library. The solution to OP's problem can be found below. Note that the rules are declared in a very brief manner.
public class SOAnswer {
@ToString @Getter @Setter
@AllArgsConstructor @NoArgsConstructor
public static abstract class Animal {
private String name;
}
@ToString(callSuper = true) @Getter @Setter
@AllArgsConstructor @NoArgsConstructor
public static class Dog extends Animal {
private String breed;
}
@ToString(callSuper = true) @Getter @Setter
@AllArgsConstructor @NoArgsConstructor
public static class Cat extends Animal {
private String favoriteToy;
}
public static void main(String[] args) {
String json = "[{"
+ " \"name\": \"pluto\","
+ " \"breed\": \"dalmatian\""
+ "},{"
+ " \"name\": \"whiskers\","
+ " \"favoriteToy\": \"mouse\""
+ "}]";
// create a deserializer instance
DynamicObjectDeserializer deserializer = new DynamicObjectDeserializer();
// runtime-configure deserialization rules;
// condition is bound to the existence of a field, but it could be any Predicate
deserializer.addRule(DeserializationRuleFactory.newRule(1,
(e) -> e.getJsonNode().has("breed"),
DeserializationActionFactory.objectToType(Dog.class)));
deserializer.addRule(DeserializationRuleFactory.newRule(1,
(e) -> e.getJsonNode().has("favoriteToy"),
DeserializationActionFactory.objectToType(Cat.class)));
List<Animal> deserializedAnimals = deserializer.deserializeArray(json, Animal.class);
for (Animal animal : deserializedAnimals) {
System.out.println("Deserialized Animal Class: " + animal.getClass().getSimpleName()+";\t value: "+animal.toString());
}
}
}
Maven depenendency for pretius-jddl (check newest version at maven.org/jddl:
<dependency>
<groupId>com.pretius</groupId>
<artifactId>jddl</artifactId>
<version>1.0.0</version>
</dependency>
update-alternatives
is problematic in this case as it forces you to update all the elements depending on the JDK.
For this specific purpose, the package java-common
contains a tool called update-java-alternatives
.
It's straightforward to use it. First list the JDK installs available on your machine:
root@mylaptop:~# update-java-alternatives -l
java-1.7.0-openjdk-amd64 1071 /usr/lib/jvm/java-1.7.0-openjdk-amd64
java-1.8.0-openjdk-amd64 1069 /usr/lib/jvm/java-1.8.0-openjdk-amd64
And then pick one up:
root@mylaptop:~# update-java-alternatives -s java-1.7.0-openjdk-amd64
The simplest manner of defining custom behavior for individual routes would be fairly easy:
1) routes.js
: create a new property (like requireAuth
) for any desired route
angular.module('yourApp').config(function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'templates/home.html',
requireAuth: true // our custom property
})
.when('/login', {
templateUrl: 'templates/login.html',
})
.otherwise({
redirectTo: '/home'
});
})
2) In a top-tier controller that isn't bound to an element inside the ng-view
(to avoid conflict with angular $routeProvider
), check if the newUrl
has the requireAuth
property and act accordingly
angular.module('YourApp').controller('YourController', function ($scope, $location, session) {
// intercept the route change event
$scope.$on('$routeChangeStart', function (angularEvent, newUrl) {
// check if the custom property exist
if (newUrl.requireAuth && !session.user) {
// user isn’t authenticated
$location.path("/login");
}
});
});
I was trying to instantiate the generic from within a base class. None of the above examples worked for me as they required a concrete type in order to call the factory method.
After researching for awhile on this and unable to find a solution online, I discovered that this appears to work.
protected activeRow: T = {} as T;
The pieces:
activeRow: T = {} <-- activeRow now equals a new object...
...
as T; <-- As the type I specified.
All together
export abstract class GridRowEditDialogBase<T extends DataRow> extends DialogBase{
protected activeRow: T = {} as T;
}
That said, if you need an actual instance you should use:
export function getInstance<T extends Object>(type: (new (...args: any[]) => T), ...args: any[]): T {
return new type(...args);
}
export class Foo {
bar() {
console.log("Hello World")
}
}
getInstance(Foo).bar();
If you have arguments, you can use.
export class Foo2 {
constructor(public arg1: string, public arg2: number) {
}
bar() {
console.log(this.arg1);
console.log(this.arg2);
}
}
getInstance(Foo, "Hello World", 2).bar();
With php 5.3
$date = new DateTime();
$interval = new DateInterval('P1D');
echo $date->format('Y-m-d') , PHP_EOL;
$date->add($interval);
echo $date->format('Y-m-d'), PHP_EOL;
$date->add($interval);
echo $date->format('Y-m-d'), PHP_EOL;
will output
2012-12-24
2012-12-25
2012-12-26
After a lot of searching I could not find an exact example of a single SQL Server trigger that handles all (3) three conditions of the trigger actions INSERT, UPDATE, and DELETE. I finally found a line of text that talked about the fact that when a DELETE or UPDATE occurs, the common DELETED table will contain a record for these two actions. Based upon that information, I then created a small Action routine which determines why the trigger has been activated. This type of interface is sometimes needed when there is both a common configuration and a specific action to occur on an INSERT vs. UPDATE trigger. In these cases, to create a separate trigger for the UPDATE and the INSERT would become maintenance problem. (i.e. were both triggers updated properly for the necessary common data algorithm fix?)
To that end, I would like to give the following multi-trigger event code snippet for handling INSERT, UPDATE, DELETE in one trigger for an Microsoft SQL Server.
CREATE TRIGGER [dbo].[INSUPDDEL_MyDataTable]
ON [dbo].[MyDataTable] FOR INSERT, UPDATE, DELETE
AS
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with caller queries SELECT statements.
-- If an update/insert/delete occurs on the main table, the number of records affected
-- should only be based on that table and not what records the triggers may/may not
-- select.
SET NOCOUNT ON;
--
-- Variables Needed for this Trigger
--
DECLARE @PACKLIST_ID varchar(15)
DECLARE @LINE_NO smallint
DECLARE @SHIPPED_QTY decimal(14,4)
DECLARE @CUST_ORDER_ID varchar(15)
--
-- Determine if this is an INSERT,UPDATE, or DELETE Action
--
DECLARE @Action as char(1)
DECLARE @Count as int
SET @Action = 'I' -- Set Action to 'I'nsert by default.
SELECT @Count = COUNT(*) FROM DELETED
if @Count > 0
BEGIN
SET @Action = 'D' -- Set Action to 'D'eleted.
SELECT @Count = COUNT(*) FROM INSERTED
IF @Count > 0
SET @Action = 'U' -- Set Action to 'U'pdated.
END
if @Action = 'D'
-- This is a DELETE Record Action
--
BEGIN
SELECT @PACKLIST_ID =[PACKLIST_ID]
,@LINE_NO = [LINE_NO]
FROM DELETED
DELETE [dbo].[MyDataTable]
WHERE [PACKLIST_ID]=@PACKLIST_ID AND [LINE_NO]=@LINE_NO
END
Else
BEGIN
--
-- Table INSERTED is common to both the INSERT, UPDATE trigger
--
SELECT @PACKLIST_ID =[PACKLIST_ID]
,@LINE_NO = [LINE_NO]
,@SHIPPED_QTY =[SHIPPED_QTY]
,@CUST_ORDER_ID = [CUST_ORDER_ID]
FROM INSERTED
if @Action = 'I'
-- This is an Insert Record Action
--
BEGIN
INSERT INTO [MyChildTable]
(([PACKLIST_ID]
,[LINE_NO]
,[STATUS]
VALUES
(@PACKLIST_ID
,@LINE_NO
,'New Record'
)
END
else
-- This is an Update Record Action
--
BEGIN
UPDATE [MyChildTable]
SET [PACKLIST_ID] = @PACKLIST_ID
,[LINE_NO] = @LINE_NO
,[STATUS]='Update Record'
WHERE [PACKLIST_ID]=@PACKLIST_ID AND [LINE_NO]=@LINE_NO
END
END
You would need to have an instance of ClassA within ClassB or have ClassB inherit ClassA
class ClassA {
public function getName() {
echo $this->name;
}
}
class ClassB extends ClassA {
public function getName() {
parent::getName();
}
}
Without inheritance or an instance method, you'd need ClassA to have a static method
class ClassA {
public static function getName() {
echo "Rawkode";
}
}
--- other file ---
echo ClassA::getName();
If you're just looking to call the method from an instance of the class:
class ClassA {
public function getName() {
echo "Rawkode";
}
}
--- other file ---
$a = new ClassA();
echo $a->getName();
Regardless of the solution you choose, require 'ClassA.php
is needed.
today is 2020-12-25, my VSC is 1.52.1, tried all above not very successful. Here is complete steps I did to add my existing local project to GitHub using VSC (Note: Do not create a corresponding repository at GitHub):
<your username>/<your new repository name>
. For example, my username is "myname" and my local folder is named "HelloWorld". So, it will be myname/HelloWorld
in the type-in box.Your rows
object holds an Item
attribute where you can find the values for each of your columns. You can not expect the columns to concatenate themselves when you do a .ToString()
on the row.
You should access each column from the row separately, use a for
or a foreach
to walk the array of columns.
Here, take a look at the class:
http://msdn.microsoft.com/en-us/library/system.data.datarow.aspx
A trick I often use when I just need "a little" shadow (read: contour must not be super-precise) is placing a DIV with a radial fill 100%-black-to-100%-transparent under the image. The CSS for the DIV looks something like:
.shadow320x320{
background: -moz-radial-gradient(center, ellipse cover, rgba(0,0,0,0.58) 0%, rgba(0,0,0,0.58) 1%, rgba(0,0,0,0) 43%, rgba(0,0,0,0) 100%); /* FF3.6+ */
background: -webkit-gradient(radial, center center, 0px, center center, 100%, color-stop(0%,rgba(0,0,0,0.58)), color-stop(1%,rgba(0,0,0,0.58)), color-stop(43%,rgba(0,0,0,0)), color-stop(100%,rgba(0,0,0,0))); /* Chrome,Safari4+ */
background: -webkit-radial-gradient(center, ellipse cover, rgba(0,0,0,0.58) 0%,rgba(0,0,0,0.58) 1%,rgba(0,0,0,0) 43%,rgba(0,0,0,0) 100%); /* Chrome10+,Safari5.1+ */
background: -o-radial-gradient(center, ellipse cover, rgba(0,0,0,0.58) 0%,rgba(0,0,0,0.58) 1%,rgba(0,0,0,0) 43%,rgba(0,0,0,0) 100%); /* Opera 12+ */
background: -ms-radial-gradient(center, ellipse cover, rgba(0,0,0,0.58) 0%,rgba(0,0,0,0.58) 1%,rgba(0,0,0,0) 43%,rgba(0,0,0,0) 100%); /* IE10+ */
background: radial-gradient(ellipse at center, rgba(0,0,0,0.58) 0%,rgba(0,0,0,0.58) 1%,rgba(0,0,0,0) 43%,rgba(0,0,0,0) 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#94000000', endColorstr='#00000000',GradientType=1 ); /* IE6-9 fallback on horizontal gradient */
}
This will create a circular black faded-out 'dot' on a 320x320 DIV. If you scale the height or width of the DIV you get a corresponding oval. Very nice to create eg shadows under bottles or other cylinder-like shapes.
There is an absolute incredible, super-excellent tool to create CSS gradients here:
http://www.colorzilla.com/gradient-editor/
ps: Do a courtesy ad-click when you use it. (And, no,I'm not affiliated with it. But courtesy clicking should become a bit of a habit, especially for tool you use often... just sayin... since we're all working on the net...)
An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them.
There are different types of joins available in SQL:
INNER JOIN: returns rows when there is a match in both tables.
LEFT JOIN: returns all rows from the left table, even if there are no matches in the right table.
RIGHT JOIN: returns all rows from the right table, even if there are no matches in the left table.
FULL JOIN: It combines the results of both left and right outer joins.
The joined table will contain all records from both the tables and fill in NULLs for missing matches on either side.
SELF JOIN: is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement.
CARTESIAN JOIN: returns the Cartesian product of the sets of records from the two or more joined tables.
WE can take each first four joins in Details :
We have two tables with the following values.
TableA
id firstName lastName
.......................................
1 arun prasanth
2 ann antony
3 sruthy abc
6 new abc
TableB
id2 age Place
................
1 24 kerala
2 24 usa
3 25 ekm
5 24 chennai
....................................................................
INNER JOIN
Note :it gives the intersection of the two tables, i.e. rows they have common in TableA and TableB
Syntax
SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2
ON table1.common_field = table2.common_field;
Apply it in our sample table :
SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
FROM TableA
INNER JOIN TableB
ON TableA.id = TableB.id2;
Result Will Be
firstName lastName age Place
..............................................
arun prasanth 24 kerala
ann antony 24 usa
sruthy abc 25 ekm
LEFT JOIN
Note : will give all selected rows in TableA, plus any common selected rows in TableB.
Syntax
SELECT table1.column1, table2.column2...
FROM table1
LEFT JOIN table2
ON table1.common_field = table2.common_field;
Apply it in our sample table :
SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
FROM TableA
LEFT JOIN TableB
ON TableA.id = TableB.id2;
Result
firstName lastName age Place
...............................................................................
arun prasanth 24 kerala
ann antony 24 usa
sruthy abc 25 ekm
new abc NULL NULL
RIGHT JOIN
Note : will give all selected rows in TableB, plus any common selected rows in TableA.
Syntax
SELECT table1.column1, table2.column2...
FROM table1
RIGHT JOIN table2
ON table1.common_field = table2.common_field;
Apply it in our sample table :
SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
FROM TableA
RIGHT JOIN TableB
ON TableA.id = TableB.id2;
Result
firstName lastName age Place
...............................................................................
arun prasanth 24 kerala
ann antony 24 usa
sruthy abc 25 ekm
NULL NULL 24 chennai
FULL JOIN
Note :It will return all selected values from both tables.
Syntax
SELECT table1.column1, table2.column2...
FROM table1
FULL JOIN table2
ON table1.common_field = table2.common_field;
Apply it in our sample table :
SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
FROM TableA
FULL JOIN TableB
ON TableA.id = TableB.id2;
Result
firstName lastName age Place
...............................................................................
arun prasanth 24 kerala
ann antony 24 usa
sruthy abc 25 ekm
new abc NULL NULL
NULL NULL 24 chennai
Interesting Fact
For INNER joins the order doesn't matter
For (LEFT, RIGHT or FULL) OUTER joins,the order matter
Better to go check this Link it will give you interesting details about join order
To answer your first question... .format
just seems more sophisticated in many ways. An annoying thing about %
is also how it can either take a variable or a tuple. You'd think the following would always work:
"hi there %s" % name
yet, if name
happens to be (1, 2, 3)
, it will throw a TypeError
. To guarantee that it always prints, you'd need to do
"hi there %s" % (name,) # supply the single argument as a single-item tuple
which is just ugly. .format
doesn't have those issues. Also in the second example you gave, the .format
example is much cleaner looking.
Why would you not use it?
To answer your second question, string formatting happens at the same time as any other operation - when the string formatting expression is evaluated. And Python, not being a lazy language, evaluates expressions before calling functions, so in your log.debug
example, the expression "some debug info: %s"%some_info
will first evaluate to, e.g. "some debug info: roflcopters are active"
, then that string will be passed to log.debug()
.
Open .eclipseproduct
in the product installation folder. Or open Configuration\config.ini
and check property eclipse.buildId
if exist.
Add a word boundary \b
at the end of the regex:
/^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}\b/
if the space after )
is optional:
/^(\([0-9]{3}\)\s*|[0-9]{3}-)[0-9]{3}-[0-9]{4}\b/
I found This simpler yet powerful tutorial which uses the fileReader
Object. It simply creates an img element and, using the fileReader object, assigns its source attribute as the value of the form input
function previewFile() {_x000D_
var preview = document.querySelector('img');_x000D_
var file = document.querySelector('input[type=file]').files[0];_x000D_
var reader = new FileReader();_x000D_
_x000D_
reader.onloadend = function () {_x000D_
preview.src = reader.result;_x000D_
}_x000D_
_x000D_
if (file) {_x000D_
reader.readAsDataURL(file);_x000D_
} else {_x000D_
preview.src = "";_x000D_
}_x000D_
}
_x000D_
<input type="file" onchange="previewFile()"><br>_x000D_
<img src="" height="200" alt="Image preview...">
_x000D_
use it :
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
langData.removeAtIndex(indexPath.row) //langData is array from i delete values
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
hope it helps you
I find myself referencing this post a lot, and found that the documentation defines a slightly less hacky way to override default widgets.
(No need to override the ModelForm's __init__ method)
However, you still need to wire your JS and CSS appropriately as Carl mentions.
forms.py
from django import forms
from my_app.models import Product
from django.contrib.admin import widgets
class ProductForm(forms.ModelForm):
mydate = forms.DateField(widget=widgets.AdminDateWidget)
mytime = forms.TimeField(widget=widgets.AdminTimeWidget)
mydatetime = forms.SplitDateTimeField(widget=widgets.AdminSplitDateTime)
class Meta:
model = Product
Reference Field Types to find the default form fields.
In Simple Rails terms:
h
remove html tags into number characters so that rendering won't break your html
html_safe
sets a boolean in string so that the string is considered as html save
raw
It converts to html_safe to string
Nowadays, animating text color is included in the jQuery UI Effects Core. It's pretty small. You can make a custom download here: http://jqueryui.com/download - but you don't actually need anything but the effects core itself (not even the UI core), and it brings with it different easing functions as well.
What about:
git reset
back to the last commit before you started making changes.git pull
to re-pull just the remote changes you threw away with the reset.Or will that explode when you try to re-merge the branch?
function initialize() {
var location = new google.maps.LatLng(44.5403, -78.5463);
var mapCanvas = document.getElementById('map_canvas');
var map_options = {
center: location,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(map_canvas, map_options);
new google.maps.Marker({
position: location,
map: map
});
}
google.maps.event.addDomListener(window, 'load', initialize);
http://skeletoncoder.blogspot.com/2006/09/java-tutorials-why-no-unsigned.html
This guy says because the C standard defines operations involving unsigned and signed ints to be treated as unsigned. This could cause negative signed integers to roll around into a large unsigned int, potentially causing bugs.
$(".first").addClass("second");
If you'd like to add it on an event, you can do so easily as well. An example with the click event:
$(".first").click(function() {
$(this).addClass("second");
});
I had a similar issue with an integer that could be legitimately assigned 0 in Access VBA. None of the above solutions worked for me.
At first I just used a boolean var and IF statement:
Dim i as integer, bol as boolean
If bol = false then
i = ValueIWantToAssign
bol = True
End If
In my case, my integer variable assignment was within a for loop and another IF statement, so I ended up using "Exit For" instead as it was more concise.
Like so:
Dim i as integer
ForLoopStart
If ConditionIsMet Then
i = ValueIWantToAssign
Exit For
End If
ForLoopEnd
i do your code .i can run but i need modify two places:
name="android:indeterminateDrawable"
instead of android:progressDrawable
modify name attrs.xml ---> styles.xml
so I had same problem here. Found out that my domain instance was getting detached from the hibernate session. I used isAttached()
to check and attached the domain using d.attach()
get_woocommerce_term_meta is depricated since Woo 3.6.0.
so change
$thumbnail_id = get_woocommerce_term_meta($value->term_id, 'thumbnail_id', true );
into: ($value->term_id should be woo category id)
get_term_meta($value->term_id, 'thumbnail_id', true)
see docs for details: https://docs.woocommerce.com/wc-apidocs/function-get_woocommerce_term_meta.html
You have two pythons installed on your machine, one is the standard python that comes with Mac OSX and the second is the one you installed with ports (this is the one that has matplotlib
installed in its library, the one that comes with macosx does not).
/usr/bin/python
Is the standard mac python and since it doesn't have matplotlib
you should always start your script with the one installed with ports.
If python your_script.py
works then change the #!
to:
#!/usr/bin/env python
Or put the full path to the python interpreter that has the matplotlib
installed in its library.
You need to click on the MinGW compiler when running the code. Failure to do this will cause the launch failed binary not found error.
Use sprintf()
:
int someInt = 368;
char str[12];
sprintf(str, "%d", someInt);
All numbers that are representable by int
will fit in a 12-char-array without overflow, unless your compiler is somehow using more than 32-bits for int
. When using numbers with greater bitsize, e.g. long
with most 64-bit compilers, you need to increase the array size—at least 21 characters for 64-bit types.
replace this
printf("%c",word[i]);
by
printf("%02X",word[i]);
What about:
if (urldecode(trim($url)) == trim($url)) { $url_form = 'decoded'; }
else { $url_form = 'encoded'; }
Will not work with double encoding but this is out of scope anyway I suppose?
In iOS7 the following matches UITextField border perfectly (to my eye at least):
textField.layer.borderColor = [[[UIColor grayColor] colorWithAlphaComponent:0.5] CGColor];
textField.layer.borderWidth = 0.5;
textField.layer.cornerRadius = 5;
textField.clipsToBounds = YES;
There is no need to import anything special.
Thanks to @uvieere and @hanumanDev whose answers go me almost there :)
Actually there is a freeware version of EMS's SQL Manager which is quite powerful
The purpose of the nameof
operator is to provide the source name of the artifacts.
Usually the source name is the same name as the metadata name:
public void M(string p)
{
if (p == null)
{
throw new ArgumentNullException(nameof(p));
}
...
}
public int P
{
get
{
return p;
}
set
{
p = value;
NotifyPropertyChanged(nameof(P));
}
}
But this may not always be the case:
using i = System.Int32;
...
Console.WriteLine(nameof(i)); // prints "i"
Or:
public static string Extension<T>(this T t)
{
return nameof(T); returns "T"
}
One use I've been giving to it is for naming resources:
[Display(
ResourceType = typeof(Resources),
Name = nameof(Resources.Title_Name),
ShortName = nameof(Resources.Title_ShortName),
Description = nameof(Resources.Title_Description),
Prompt = nameof(Resources.Title_Prompt))]
The fact is that, in this case, I didn't even need the generated properties to access the resources, but now I have a compile time check that the resources exist.
This tool creates the folders with the images in them automatically for you. All you have to do is supply your image then drag the generated folders to your res folder. http://romannurik.github.io/AndroidAssetStudio/
All the best.
The range of char is 127 to -128. If you assign 212, ch stores -44 (212-128-128) not 212.So if you try to print a negative number as unsigned you get (MAX value of unsigned int)-abs(number) which in this case is 4294967252
So if you want to store 212 as it is in ch the only thing you can do is declare ch as
unsigned char ch;
now the range of ch is 0 to 255.