This can happen when invoking a method that doesn't exist.
Well ya you can do that in this way.
<input type="text" name="address" id="address">
<div id="map_canvas" style="width: 500px; height: 300px"></div>
<input type="button" onclick="showAddress(address.value)" value="ShowMap"/>
Java Script
function showAddress(address){
alert("This is address :"+address)
}
That is one example for the same. and that will run.
The basic idea of using ICollection
is a provide an interface to readonly-access to some finite amount of data. In fact you have a ICollection.Count property. IEnumerable
is more suitable for some chain of the data where you read till some logical point, some condition esplicitly specified by consumer or till the end of the enumeration.
First set in the following path Tools->Options->Text Editor->All Languages->Tabs if still didn't work modify as mentioned below Go to Edit->Advanced->Set Indentation ->Spaces
For anyone who doesn't have the guarantee that the list will not be null, you can use the null-conditional operator to safely check for null and empty lists in a single conditional statement:
if (list?.Any() != true)
{
// Handle null or empty list
}
I believe the problem is that codecs.BOM_UTF8
is a byte string, not a Unicode string. I suspect the file handler is trying to guess what you really mean based on "I'm meant to be writing Unicode as UTF-8-encoded text, but you've given me a byte string!"
Try writing the Unicode string for the byte order mark (i.e. Unicode U+FEFF) directly, so that the file just encodes that as UTF-8:
import codecs
file = codecs.open("lol", "w", "utf-8")
file.write(u'\ufeff')
file.close()
(That seems to give the right answer - a file with bytes EF BB BF.)
EDIT: S. Lott's suggestion of using "utf-8-sig" as the encoding is a better one than explicitly writing the BOM yourself, but I'll leave this answer here as it explains what was going wrong before.
I had the similar problem. This is the stack trace:
Traceback (most recent call last):
File "/usr/local/bin/aws", line 19, in <module> import awscli.clidriver
File "/usr/local/lib/python2.7/dist-packages/awscli/clidriver.py", line 17, in <module> import botocore.session
File "/usr/local/lib/python2.7/dist-packages/botocore/session.py", line 30, in <module> import botocore.credentials
File "/usr/local/lib/python2.7/dist-packages/botocore/credentials.py", line 27, in <module> from dateutil.parser import parse
ImportError: No module named dateutil.parser
I tried to (re-)install dateutil.parser
through all possible ways. It was unsuccessful.
I solved it with
pip3 uninstall awscli
pip3 install awscli
For @Joe above, "This is giving me a redirect loop. Before I added the code it worked fine. Any suggestions? – Joe Nov 8 '11 at 4:13"
This was happening to me as well and what I believe was happening is that there was a load balancer terminating the SSL request in front of the Web server. So, my Web site was always thinking the request was "http", even if the original browser requested it to be "https".
I admit this is a bit hacky, but what worked for me was to implement a "JustRedirected" property that I could leverage to figure out the person was already redirected once. So, I test for specific conditions that warrant the redirect and, if they are met, I set this property (value stored in session) prior to the redirection. Even if the http/https conditions for redirection are met the second time, I bypass the redirection logic and reset the "JustRedirected" session value to false. You'll need your own conditional test logic, but here's a simple implementation of the property:
public bool JustRedirected
{
get
{
if (Session[RosadaConst.JUSTREDIRECTED] == null)
return false;
return (bool)Session[RosadaConst.JUSTREDIRECTED];
}
set
{
Session[RosadaConst.JUSTREDIRECTED] = value;
}
}
Lots of answers so far, which are all excellent pointers to API's and tutorials. One thing I'd like to add is that I work out how far the markers are from my location using something like:
float distance = (float) loc.distanceTo(loc2);
Hope this helps refine the detail for your problem. It returns a rough estimate of distance (in m) between points, and is useful for getting rid of POI that might be too far away - good to declutter your map?
Hashmaps can only use classes
, not primitives
. This page from programmerinterview.com might be of use in guiding you to finding the answer. To be honest, I haven't figured out the answer to this problem in detail myself.
This might work for you:
cat <<! | sed '/aaa=\(bbb\|ccc\|ddd\)/!s/\(aaa=\).*/\1xxx/'
> aaa=bbb
> aaa=ccc
> aaa=ddd
> aaa=[something else]
!
aaa=bbb
aaa=ccc
aaa=ddd
aaa=xxx
If you are looking for the folder such as brushes, curves, etc. you can try:
/home/<username>/.gimp-2.8
This folder will contain all the gimp folders
.
Good Luck.
I solve this problem by always using the [h]
option on floats (such as figures) so that they (mostly) go where I place them. Then when I look at the final draft, I adjust the location of the float by moving it in the LaTeX source. Usually that means moving it around the paragraph where it is referenced. Sometimes I need to add a page break at an appropriate spot.
I've found that the default placement of floats is reasonable in LaTeX, but manual adjustments are almost always needed to get things like this just right. (And sometimes it isn't possible for everything to be perfect when there are lots of floats and footnotes.)
The manual for the memoir
class has some good information about how LaTeX places floats and some advice for manipulating the algorithm.
var bottom = $('#bottom').position().top + $('#bottom').height();
Here's my quick and dirty version, basically its splitting up the URL parameters separated by '&' into array elements, and then iterates over that array adding key/value pairs separated by '=' into an object. I'm using decodeURIComponent() to translate the encoded characters to their normal string equivalents (so %20 becomes a space, %26 becomes '&', etc):
function deparam(paramStr) {
let paramArr = paramStr.split('&');
let paramObj = {};
paramArr.forEach(e=>{
let param = e.split('=');
paramObj[param[0]] = decodeURIComponent(param[1]);
});
return paramObj;
}
example:
deparam('abc=foo&def=%5Basf%5D&xyz=5')
returns
{
abc: "foo"
def:"[asf]"
xyz :"5"
}
The only issue is that xyz is a string and not a number (due to using decodeURIComponent()), but beyond that its not a bad starting point.
Both SHA256 and MDA5 are hashing algorithms. They take your input data, in this case your file, and output a 256/128-bit number. This number is a checksum. There is no encryption taking place because an infinite number of inputs can result in the same hash value, although in reality collisions are rare.
SHA256 takes somewhat more time to calculate than MD5, according to this answer.
Offhand, I'd say that MD5 would be probably be suitable for what you need.
Here is a basic example that explains the callback()
function in JavaScript:
var x = 0;_x000D_
_x000D_
function testCallBack(param1, param2, callback) {_x000D_
alert('param1= ' + param1 + ', param2= ' + param2 + ' X=' + x);_x000D_
if (callback && typeof(callback) === "function") {_x000D_
x += 1;_x000D_
alert("Calla Back x= " + x);_x000D_
x += 1;_x000D_
callback();_x000D_
}_x000D_
}_x000D_
_x000D_
testCallBack('ham', 'cheese', function() {_x000D_
alert("Function X= " + x);_x000D_
});
_x000D_
Bind the button, this is done with jQuery:
$("#my-table input[type='button']").click(function(){
var parameter = $(this).val();
window.location = "http://yoursite.com/page?variable=" + parameter;
});
I assume that the text "username1" is just a placeholder for what will eventually be an actual username. Assuming that,
span
tag server-side, before sending it to the client, and then just working with the span tags.you need to do an ajax HEAD request to get the filesize. with jquery it's something like this
var req = $.ajax({
type: "HEAD",
url: yoururl,
success: function () {
alert("Size is " + request.getResponseHeader("Content-Length"));
}
});
Check out the DirectoryIterator class.
From one of the comments on that page:
// output all files and directories except for '.' and '..'
foreach (new DirectoryIterator('../moodle') as $fileInfo) {
if($fileInfo->isDot()) continue;
echo $fileInfo->getFilename() . "<br>\n";
}
The recursive version is RecursiveDirectoryIterator.
As I parse it, those words are wrong. It should read "If the function modifies that value, the modifications appear also within the scope of the calling function when passing by reference, but not when passing by value."
its happen when you try to delete the same object and then again update the same object use this after delete
session.clear();
<html>
<body>
<video width="600" height="400" controls>
<source src="index.m3u8" type="application/x-mpegURL">
</video>
</body>
Stream HLS or m3u8 files using above code. it works for desktop: ms edge browser (not working with desktop chrome) and mobile: chrome,opera mini browser.
To play on all browser use flash based media player. media player to support all browser
I would vouch for using the opacity-method if you do not want to remove the component from your page, e.g. hiding a WebView.
<WebView
style={{opacity: 0}} // Hide component
source={{uri: 'https://www.google.com/'}}
/>
This is useful if you need to submit a form to a 3rd party website.
Get COLUMN INDEX on click:
$(this).closest("td").index();
Get ROW INDEX on click:
$(this).closest("tr").index();
I don't think you can make a control look like anything other than a control with CSS.
Your best bet it to make a PRINT button goes to a new page with a graphic in place of the selected radio button, then do a window.print() from there.
You need to set figure
properties.
At the very beginning of the script, call
figure('name','something else')
Calling figure
is a good thing, anyway, because without it, you always plot into the same window, and sometimes you may want to compare two windows side-by-side.
Alternatively, you can store the figure's handle by calling
figH = figure;
so that you can later change the figure properties to your liking (the 'numberTitle'
property setting eliminates the "figure X" text)
set(figH,'Name','something else','NumberTitle','off')
Have a look at the figure properties in the MATLAB documentation to see what else you can change if you want.
Another (crude) option is to utilize netcat for dumping the full request:
nc -l -p 8000 -w 3 | tee curldbg.txt
And of course sending the failing request to it:
curl_setup(CURLOPT_URL, "http://localhost/testytest");
Notably that will always hang+fail, since netcat won't ever construct a valid HTTP response. It's really just for inspecting what really got sent. The better option, of course, is using a http request debugging service.
Here's a slghtly different take using javascript's native confirm functionality and a custom Angular directive. It's super flexible and pretty lightweight:
Usage:
<button (hrsAreYouSure) (then)="confirm(arg1)" (else)="cancel(arg2)">
This will execute confirm if user presses Ok on the confirmation dialog, or cancel if they
hit Cancel
</button>
Directive:
import {Directive, ElementRef, EventEmitter, Inject, OnInit, Output} from '@angular/core';
@Directive({
selector: '[hrsAreYouSure]'
})
export class AreYouSureDirective implements OnInit {
@Output() then = new EventEmitter<boolean>();
@Output() else = new EventEmitter<boolean>();
constructor(@Inject(ElementRef) private element: ElementRef) { }
ngOnInit(): void {
const directive = this;
this.element.nativeElement.onclick = function() {
const result = confirm('Are you sure?');
if (result) {
directive.then.emit(true);
} else {
directive.else.emit(true);
}
};
}
}
You can use: Request::url()
to obtain the current URL, here is an example:
@if(Request::url() === 'your url here')
// code
@endif
Laravel offers a method to find out, whether the URL matches a pattern or not
if (Request::is('admin/*'))
{
// code
}
Check the related documentation to obtain different request information: http://laravel.com/docs/requests#request-information
You can link directly with Media Fragments URI, just change the filename to file.webm#t=50
This is pretty cool, you can do all sorts of things. But I don't know the current state of browser support.
Try:
from p in db.Products
where !theBadCategories.Contains(p.Category)
select p;
What's the SQL query you want to translate into a Linq query?
you should change cr_date(str) to datetime object then you 'll change the date to the specific format:
cr_date = '2013-10-31 18:23:29.000227'
cr_date = datetime.datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
cr_date = cr_date.strftime("%m/%d/%Y")
Put into the Button-Control the Attribute "UseSubmitBehavior=false".
With Eclipse 3.7 Indigo, I found the link at http://www.eclipse.org/mpc/ which told me the download location and plugin was http://download.eclipse.org/mpc/indigo/ Which made the "Eclipse Marketplace Client" available in my Software updates after I added that address as a repository. Didn't seem to be in the core list on a fresh install.
The quickest way is:
>>> import time
>>> time.strftime("%Y%m%d")
'20130924'
If you can use jquery then its simple
$("#txt").text()
java.util.Date constructor with parameters like
new Date(int year, int month, int date, int hrs, int min).
is deprecated and preferably do not use it any more. Oracle docs prefers the way over java.util.Calendar. So you can set any date and instantiate Date object through the getTime() method.
Calendar calendar = Calendar.getInstance();
calendar.set(2018, 11, 31, 59, 59, 59);
Date happyNewYearDate = calendar.getTime();
Notice that month number starts from 0
Angular: 8.2.11
<td>{{ data.DateofBirth | date }}</td>
Output: Jun 9, 1973
<td>{{ data.DateofBirth | date: 'dd/MM/yyyy' }}</td>
Output: 09/06/1973
<td>{{ data.DateofBirth | date: 'dd/MM/yyyy hh:mm a' }}</td>
Output: 09/06/1973 12:00 AM
pandas >= 0.25.0
Since pandas version 0.25.0 we have named aggregations where we can groupby, aggregate and at the same time assign new names to our columns. This way we won't get the MultiIndex columns, and the column names make more sense given the data they contain:
aggregate and get a list of strings
grp = df.groupby('A').agg(B_sum=('B','sum'),
C=('C', list)).reset_index()
print(grp)
A B_sum C
0 1 1.615586 [This, string]
1 2 0.421821 [is, !]
2 3 0.463468 [a]
3 4 0.643961 [random]
aggregate and join the strings
grp = df.groupby('A').agg(B_sum=('B','sum'),
C=('C', ', '.join)).reset_index()
print(grp)
A B_sum C
0 1 1.615586 This, string
1 2 0.421821 is, !
2 3 0.463468 a
3 4 0.643961 random
If you are using maven include the following tag in pom.xml (update versions as needed) inside plugins tag.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
bin/kafka-topics.sh –delete –zookeeper localhost:2181 –topic <topic-name>
The answers above are great. If you are in need of parsing all numbers out of a string that are nonconsecutive then the following may be of some help:
string input = "1-205-330-2342";
string result = Regex.Replace(input, @"[^\d]", "");
Console.WriteLine(result); // >> 12053302342
Another way is using a ResourceBundle. Basically you get the bundle using its name without the '.properties'
private static final ResourceBundle resource = ResourceBundle.getBundle("config");
And you recover any value using this:
private final String prop = resource.getString("propName");
Read more about Array and ArrayList
List<String> aList = new ArrayList<String>();
aList.add("apple");
aList.add("banana");
aList.add("orange");
String result = alist.get(1); //this will retrieve banana
Note: Index starts from 0 i.e. Zero
There are predefined macros that are used by most compilers, you can find the list here. GCC compiler predefined macros can be found here. Here is an example for gcc:
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
//define something for Windows (32-bit and 64-bit, this part is common)
#ifdef _WIN64
//define something for Windows (64-bit only)
#else
//define something for Windows (32-bit only)
#endif
#elif __APPLE__
#include <TargetConditionals.h>
#if TARGET_IPHONE_SIMULATOR
// iOS Simulator
#elif TARGET_OS_IPHONE
// iOS device
#elif TARGET_OS_MAC
// Other kinds of Mac OS
#else
# error "Unknown Apple platform"
#endif
#elif __linux__
// linux
#elif __unix__ // all unices not caught above
// Unix
#elif defined(_POSIX_VERSION)
// POSIX
#else
# error "Unknown compiler"
#endif
The defined macros depend on the compiler that you are going to use.
The _WIN64
#ifdef
can be nested into the _WIN32
#ifdef
because _WIN32
is even defined when targeting the Windows x64 version. This prevents code duplication if some header includes are common to both
(also WIN32
without underscore allows IDE to highlight the right partition of code).
SUBSTR
will be better than FLOOR
in some cases because FLOOR has a "bug" as follow:
SELECT 25 * 9.54 + 0.5 -> 239.00
SELECT FLOOR(25 * 9.54 + 0.5) -> 238 (oops!)
SELECT SUBSTR((25*9.54+0.5),1,LOCATE('.',(25*9.54+0.5)) - 1) -> 239
You can use unionByName to make this:
df = df_1.unionByName(df_2)
unionByName is available since Spark 2.3.0.
Georg have already mentioned ES6 have Array.findIndex for this. And some other answers are workaround for ES5 using Array.some method.
One more elegant approach can be
var index;
for(index = yourArray.length; index-- > 0 && yourArray[index].prop2 !== "yutu";);
At the same time I will like to emphasize, Array.some may be implemented with binary or other efficient searching technique. So, it might perform better over for loop in some browser.
You can use the Free version of HTTP Debugger.
It is not a proxy and you needn't make any changes in web.config.
Also, it can show both; incoming and outgoing HTTP requests. HTTP Debugger Free
On Windows:
Find : Ctrl+F
Find And Replace In Single Class: Ctrl+R
Find And Replace In Whole Project: Ctrl+Shift+R
on OS X ,it is similar, just replace Ctrl with Command
As others have already pointed out, the reason you are not getting the results you expect is because your JSON does not match the class structure that you are trying to deserialize into. You either need to change your JSON or change your classes. Since others have already shown how to change the JSON, I will take the opposite approach here.
To match the JSON you posted in your question, your classes should be defined like those below. Notice I've made the following changes:
Wrapper
class corresponding to the outer object in your JSON.Values
property of the ValueSet
class from a List<Value>
to a Dictionary<string, Value>
since the values
property in your JSON contains an object, not an array.[JsonProperty]
attributes to match the property names in your JSON objects.Class definitions:
class Wrapper
{
[JsonProperty("JsonValues")]
public ValueSet ValueSet { get; set; }
}
class ValueSet
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("values")]
public Dictionary<string, Value> Values { get; set; }
}
class Value
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("diaplayName")]
public string DisplayName { get; set; }
}
You need to deserialize into the Wrapper
class, not the ValueSet
class. You can then get the ValueSet
from the Wrapper
.
var valueSet = JsonConvert.DeserializeObject<Wrapper>(jsonString).ValueSet;
Here is a working program to demonstrate:
class Program
{
static void Main(string[] args)
{
string jsonString = @"
{
""JsonValues"": {
""id"": ""MyID"",
""values"": {
""value1"": {
""id"": ""100"",
""diaplayName"": ""MyValue1""
},
""value2"": {
""id"": ""200"",
""diaplayName"": ""MyValue2""
}
}
}
}";
var valueSet = JsonConvert.DeserializeObject<Wrapper>(jsonString).ValueSet;
Console.WriteLine("id: " + valueSet.Id);
foreach (KeyValuePair<string, Value> kvp in valueSet.Values)
{
Console.WriteLine(kvp.Key + " id: " + kvp.Value.Id);
Console.WriteLine(kvp.Key + " name: " + kvp.Value.DisplayName);
}
}
}
And here is the output:
id: MyID
value1 id: 100
value1 name: MyValue1
value2 id: 200
value2 name: MyValue2
Instead of
php composer.phar create-project --repository-url="http://packages.zendframework.com" zendframework/skeleton-application path/to/install
use
php composer.phar create-project --repository-url="https://packages.zendframework.com" zendframework/skeleton-application path/to/install
Just add https
instead of http
in the URL. Though it's not a permanent solution, it does work.
// Save search term state to React Hooks with spread operator and wrapper function
// Using .concat(), no wrapper function (not recommended)
setSearches(searches.concat(query))
// Using .concat(), wrapper function (recommended)
setSearches(searches => searches.concat(query))
// Spread operator, no wrapper function (not recommended)
setSearches([...searches, query])
// Spread operator, wrapper function (recommended)
setSearches(searches => [...searches, query])
https://medium.com/javascript-in-plain-english/how-to-add-to-an-array-in-react-state-3d08ddb2e1dc
The quickselect algorithm, O(n) cousin to quicksort, will do what you want. Quickselect has average performance O(n). Worst case performance is O(n^2) just like quicksort but that's rare, and modifications to quickselect reduce the worst case performance to O(n).
The idea of quickselect is to use the same pivot, lower, higher idea of quicksort, but to then ignore the lower part and to further order just the higher part.
As other people have answered, tuples in python are immutable and the only way to 'modify' one is to create a new one with the appended elements included.
But the best solution is a list. When whatever function or method that requires a tuple needs to be called, create a tuple by using tuple(list).
Go to project>clean
and select the project which display error from check box and click ok , it will clear the error for you.
Click the tab which display build automatically in the project menu
And if this also does not work than restart the eclipse and try again it will work.
Could be short as:
LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
df = df_try
for i in range(4):
df = df.append(df_try)
# Here, we have df_try times 5
df = df.append(df)
# Here, we have df_try times 10
I did it like this
func showAlert() {
let alert = UIAlertController(title: "Thanks!", message: "We'll get back to you as soon as posible.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
self.dismissView()
}))
self.present(alert, animated: true)
}
func dismissView() {
navigationController?.popViewController(animated: true)
dismiss(animated: true, completion: nil)
}
I suggest using jQuery. What you are doing right now is easy to achieve without jQuery, but as you will want new features and more functionality, jQuery will save you a lot of time. I would also like to mention that you shouldn't have multiple DOM elements with the same ID in one document. In such case use class attribute.
html:
<table id="dsTable">
<tr>
<td> Relationship Type </td>
<td> Date of Birth </td>
<td> Gender </td>
</tr>
<tr>
<td> Spouse </td>
<td> 1980-22-03 </td>
<td> female </td>
<td> <input type="button" class="addDep" value="Add"/></td>
<td> <input type="button" class="deleteDep" value="Delete"/></td>
</tr>
<tr>
<td> Child </td>
<td> 2008-23-06 </td>
<td> female </td>
<td> <input type="button" class="addDep" value="Add"/></td>
<td> <input type="button" class="deleteDep" value="Delete"/></td>
</tr>
</table>
javascript:
$('body').on('click', 'input.deleteDep', function() {
$(this).parents('tr').remove();
});
Remember that you need to reference jQuery:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
Here a working jsfiddle example: http://jsfiddle.net/p9dey/1/
def _create_type(meta, name, attrs):
type_name = f'{name}Type'
type_attrs = {}
for k, v in attrs.items():
if type(v) is _ClassPropertyDescriptor:
type_attrs[k] = v
return type(type_name, (meta,), type_attrs)
class ClassPropertyType(type):
def __new__(meta, name, bases, attrs):
Type = _create_type(meta, name, attrs)
cls = super().__new__(meta, name, bases, attrs)
cls.__class__ = Type
return cls
class _ClassPropertyDescriptor(object):
def __init__(self, fget, fset=None):
self.fget = fget
self.fset = fset
def __get__(self, obj, owner):
if self in obj.__dict__.values():
return self.fget(obj)
return self.fget(owner)
def __set__(self, obj, value):
if not self.fset:
raise AttributeError("can't set attribute")
return self.fset(obj, value)
def setter(self, func):
self.fset = func
return self
def classproperty(func):
return _ClassPropertyDescriptor(func)
class Bar(metaclass=ClassPropertyType):
__bar = 1
@classproperty
def bar(cls):
return cls.__bar
@bar.setter
def bar(cls, value):
cls.__bar = value
bar = Bar()
assert Bar.bar==1
Bar.bar=2
assert bar.bar==2
nbar = Bar()
assert nbar.bar==2
Why should I use it instead of optparse? Are their new features I should know about?
@Nicholas's answer covers this well, I think, but not the more "meta" question you start with:
Why has yet another command-line parsing module been created?
That's the dilemma number one when any useful module is added to the standard library: what do you do when a substantially better, but backwards-incompatible, way to provide the same kind of functionality emerges?
Either you stick with the old and admittedly surpassed way (typically when we're talking about complicated packages: asyncore vs twisted, tkinter vs wx or Qt, ...) or you end up with multiple incompatible ways to do the same thing (XML parsers, IMHO, are an even better example of this than command-line parsers -- but the email
package vs the myriad old ways to deal with similar issues isn't too far away either;-).
You may make threatening grumbles in the docs about the old ways being "deprecated", but (as long as you need to keep backwards compatibility) you can't really take them away without stopping large, important applications from moving to newer Python releases.
(Dilemma number two, not directly related to your question, is summarized in the old saying "the standard library is where good packages go to die"... with releases every year and a half or so, packages that aren't very, very stable, not needing releases any more often than that, can actually suffer substantially by being "frozen" in the standard library... but, that's really a different issue).
If you are using Spring container and you want to initialize non-nullable bean field, lateinit
is better suited.
@Autowired
lateinit var myBean: MyBean
I needed clean and lightweight solution (so no jQuery and alike), which will look exactly like plain HTML, would also continue working when only plain HTML is preset (so javascript will only enhance it), and which will allow searching by starting letters (including national UTF-8 letters) if possible where it does not add extra weight. It also must work fast on very slow browsers (think rPi - so preferably no javascript executing after page load).
In firefox it uses CSS identing and thus allow searching by letters, and in other browsers it will use
prepending (but there it does not support quick search by letters). Anyway, I'm quite happy with results.
You can try it in action here
It goes like this:
CSS:
.i0 { }
.i1 { margin-left: 1em; }
.i2 { margin-left: 2em; }
.i3 { margin-left: 3em; }
.i4 { margin-left: 4em; }
.i5 { margin-left: 5em; }
HTML (class "i1", "i2" etc denote identation level):
<form action="/filter/" method="get">
<select name="gdje" id="gdje">
<option value=1 class="i0">Svugdje</option>
<option value=177 class="i1">Bosna i Hercegovina</option>
<option value=190 class="i2">Babin Do</option>
<option value=258 class="i2">Banja Luka</option>
<option value=181 class="i2">Tuzla</option>
<option value=307 class="i1">Crna Gora</option>
<option value=308 class="i2">Podgorica</option>
<option value=2 SELECTED class="i1">Hrvatska</option>
<option value=5 class="i2">Bjelovarsko-bilogorska županija</option>
<option value=147 class="i3">Bjelovar</option>
<option value=79 class="i3">Daruvar</option>
<option value=94 class="i3">Garešnica</option>
<option value=329 class="i3">Grubišno Polje</option>
<option value=368 class="i3">Cazma</option>
<option value=6 class="i2">Brodsko-posavska županija</option>
<option value=342 class="i3">Gornji Bogicevci</option>
<option value=158 class="i3">Klakar</option>
<option value=140 class="i3">Nova Gradiška</option>
</select>
</form>
<script>
<!--
window.onload = loadFilter;
// -->
</script>
JavaScript:
function loadFilter() {
'use strict';
// indents all options depending on "i" CSS class
function add_nbsp() {
var opt = document.getElementsByTagName("option");
for (var i = 0; i < opt.length; i++) {
if (opt[i].className[0] === 'i') {
opt[i].innerHTML = Array(3*opt[i].className[1]+1).join(" ") + opt[i].innerHTML; // this means " " x (3*$indent)
}
}
}
// detects browser
navigator.sayswho= (function() {
var ua= navigator.userAgent, tem,
M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*([\d\.]+)/i) || [];
if(/trident/i.test(M[1])){
tem= /\brv[ :]+(\d+(\.\d+)?)/g.exec(ua) || [];
return 'IE '+(tem[1] || '');
}
M= M[2]? [M[1], M[2]]:[navigator.appName, navigator.appVersion, '-?'];
if((tem= ua.match(/version\/([\.\d]+)/i))!= null) M[2]= tem[1];
return M.join(' ');
})();
// quick detection if browser is firefox
function isFirefox() {
var ua= navigator.userAgent,
M= ua.match(/firefox\//i);
return M;
}
// indented select options support for non-firefox browsers
if (!isFirefox()) {
add_nbsp();
}
}
In Django, a one-to-many relationship is called ForeignKey. It only works in one direction, however, so rather than having a number
attribute of class Dude
you will need
class Dude(models.Model):
...
class PhoneNumber(models.Model):
dude = models.ForeignKey(Dude)
Many models can have a ForeignKey
to one other model, so it would be valid to have a second attribute of PhoneNumber
such that
class Business(models.Model):
...
class Dude(models.Model):
...
class PhoneNumber(models.Model):
dude = models.ForeignKey(Dude)
business = models.ForeignKey(Business)
You can access the PhoneNumber
s for a Dude
object d
with d.phonenumber_set.objects.all()
, and then do similarly for a Business
object.
SELECT COUNT(col1 OR col2) FROM [table_name] GROUP BY col1,col2;
display: inline-block;
won't work in any of IE browsers. Here is what I used.
// change the width of #boxContainer to
// 1-2 pixels higher than total width of the boxes inside:
#boxContainer {
width: 800px;
height: auto;
text-align: center;
margin-left: auto;
margin-right: auto;
}
#Box{
width: 240px;
height: 90px;
background-color: #FFF;
float: left;
margin-left: 10px;
margin-right: 10px;
}
Python 3.4 and later offer pathlib in the standard library. You could do:
from pathlib import Path
asm_pths = [pth for pth in Path.cwd().iterdir()
if pth.suffix == '.asm']
Or if you don't like list comprehensions:
asm_paths = []
for pth in Path.cwd().iterdir():
if pth.suffix == '.asm':
asm_pths.append(pth)
Path
objects can easily be converted to strings.
As with everything that seems scarier at first than it was later, the best way to get over the initial fear is to immerse yourself into the discomfort of the unknown! It is at times like that which we learn the most, after all.
Unfortunately, there are limitations. While you're still learning to use a function, you shouldn't assume the role of a teacher, for example. I often read answers from those who seemingly don't know how to use realloc
(i.e. the currently accepted answer!) telling others how to use it incorrectly, occasionally under the guise that they've omitted error handling, even though this is a common pitfall which needs mention. Here's an answer explaining how to use realloc
correctly. Take note that the answer is storing the return value into a different variable in order to perform error checking.
Every time you call a function, and every time you use an array, you are using a pointer. The conversions are occurring implicitly, which if anything should be even scarier, as it's the things we don't see which often cause the most problems. For example, memory leaks...
Array operators are pointer operators. array[x]
is really a shortcut for *(array + x)
, which can be broken down into: *
and (array + x)
. It's most likely that the *
is what confuses you. We can further eliminate the addition from the problem by assuming x
to be 0
, thus, array[0]
becomes *array
because adding 0
won't change the value...
... and thus we can see that *array
is equivalent to array[0]
. You can use one where you want to use the other, and vice versa. Array operators are pointer operators.
malloc
, realloc
and friends don't invent the concept of a pointer which you've been using all along; they merely use this to implement some other feature, which is a different form of storage duration, most suitable when you desire drastic, dynamic changes in size.
It is a shame that the currently accepted answer also goes against the grain of some other very well-founded advice on StackOverflow, and at the same time, misses an opportunity to introduce a little-known feature which shines for exactly this usecase: flexible array members! That's actually a pretty broken answer... :(
When you define your struct
, declare your array at the end of the structure, without any upper bound. For example:
struct int_list {
size_t size;
int value[];
};
This will allow you to unite your array of int
into the same allocation as your count
, and having them bound like this can be very handy!
sizeof (struct int_list)
will act as though value
has a size of 0, so it'll tell you the size of the structure with an empty list. You still need to add to the size passed to realloc
to specify the size of your list.
Another handy tip is to remember that realloc(NULL, x)
is equivalent to malloc(x)
, and we can use this to simplify our code. For example:
int push_back(struct int_list **fubar, int value) {
size_t x = *fubar ? fubar[0]->size : 0
, y = x + 1;
if ((x & y) == 0) {
void *temp = realloc(*fubar, sizeof **fubar
+ (x + y) * sizeof fubar[0]->value[0]);
if (!temp) { return 1; }
*fubar = temp; // or, if you like, `fubar[0] = temp;`
}
fubar[0]->value[x] = value;
fubar[0]->size = y;
return 0;
}
struct int_list *array = NULL;
The reason I chose to use struct int_list **
as the first argument may not seem immediately obvious, but if you think about the second argument, any changes made to value
from within push_back
would not be visible to the function we're calling from, right? The same goes for the first argument, and we need to be able to modify our array
, not just here but possibly also in any other function/s we pass it to...
array
starts off pointing at nothing; it is an empty list. Initialising it is the same as adding to it. For example:
struct int_list *array = NULL;
if (!push_back(&array, 42)) {
// success!
}
P.S. Remember to free(array);
when you're done with it!
Why cant I do this:
List<Object> object = new List<Object>();
You can't do this because List
is an interface, and interfaces cannot be instantiated. Only (concrete) classes can be. Examples of concrete classes implementing List
include ArrayList
, LinkedList
etc.
Here is how one would create an instance of ArrayList
:
List<Object> object = new ArrayList<Object>();
I have a method that returns a
List<?>
, how would I turn that into aList<Object>
Show us the relevant code and I'll update the answer.
Just do not include a background color for that div and it will be transparent.
To find an ancestor of a given type from code, you can use:
[CanBeNull]
public static T FindAncestor<T>(DependencyObject d) where T : DependencyObject
{
while (true)
{
d = VisualTreeHelper.GetParent(d);
if (d == null)
return null;
var t = d as T;
if (t != null)
return t;
}
}
This implementation uses iteration instead of recursion which can be slightly faster.
If you're using C# 7, this can be made slightly shorter:
[CanBeNull]
public static T FindAncestor<T>(DependencyObject d) where T : DependencyObject
{
while (true)
{
d = VisualTreeHelper.GetParent(d);
if (d == null)
return null;
if (d is T t)
return t;
}
}
In [34]: a=np.arange(-10,10)
In [35]: a
Out[35]:
array([-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9])
In [36]: np.where(a>5)
Out[36]: (array([16, 17, 18, 19]),)
In [37]: np.where(a>5)[0][0]
Out[37]: 16
Turing Complete means that it is at least as powerful as a Turing Machine.
I believe this is incorrect, a system is Turing complete if it's exactly as powerful as the Turing Machine, i.e. every computation done by the machine can be done by the system, but also every computation done by the system can be done by the Turing machine.
I will put a small comparison table here (just to have it somewhere):
Servlet is mapped as /test%3F/*
and the application is deployed under /app
.
http://30thh.loc:8480/app/test%3F/a%3F+b;jsessionid=S%3F+ID?p+1=c+d&p+2=e+f#a
Method URL-Decoded Result
----------------------------------------------------
getContextPath() no /app
getLocalAddr() 127.0.0.1
getLocalName() 30thh.loc
getLocalPort() 8480
getMethod() GET
getPathInfo() yes /a?+b
getProtocol() HTTP/1.1
getQueryString() no p+1=c+d&p+2=e+f
getRequestedSessionId() no S%3F+ID
getRequestURI() no /app/test%3F/a%3F+b;jsessionid=S+ID
getRequestURL() no http://30thh.loc:8480/app/test%3F/a%3F+b;jsessionid=S+ID
getScheme() http
getServerName() 30thh.loc
getServerPort() 8480
getServletPath() yes /test?
getParameterNames() yes [p 2, p 1]
getParameter("p 1") yes c d
In the example above the server is running on the localhost:8480
and the name 30thh.loc
was put into OS hosts
file.
Comments
"+" is handled as space only in the query string
Anchor "#a" is not transferred to the server. Only the browser can work with it.
If the url-pattern
in the servlet mapping does not end with *
(for example /test
or *.jsp
), getPathInfo()
returns null
.
If Spring MVC is used
Method getPathInfo()
returns null
.
Method getServletPath()
returns the part between the context path and the session ID. In the example above the value would be /test?/a?+b
Be careful with URL encoded parts of @RequestMapping
and @RequestParam
in Spring. It is buggy (current version 3.2.4) and is usually not working as expected.
I also had the issue of the Eclipse Tomcat Server timing out and tried every suggestion including:
Nothing worked until I read a comment on a related issue and realized that I had added a breakpoint in an interceptor class after a big code change and had forgotten to toggle it off. I removed it and all other breakpoints and Tomcat started right up as it usually did.
In here:
if (ValidationUtils.isNullOrEmpty(lastName)) {
registrationErrors.add(ValidationErrors.LAST_NAME);
}
if (!ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
you check for null or empty value on lastname, but in isEmailValid you don't check for empty value. Something like this should do
if (ValidationUtils.isNullOrEmpty(email) || !ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
or better yet, fix your ValidationUtils.isEmailValid() to cope with null email values. It shouldn't crash, it should just return false.
Use window.open
instead of window.location
to open a new window or tab (depending on browser settings).
Your fiddle does not work because there is no button
element to select. Try input[type=button]
or give the button an id
and use #buttonId
.
I solved changing
readable_json['firstName']
by
readable_json[0]['firstName']
You could look into the PDO Library. You can use prepared statements with PDO, which will automatically escape any bad characters in your strings if you do the prepared statements correctly. This is for PHP 5 only I think.
As others have noted, golang does not have a ternary operator or any equivalent. This is a deliberate decision thought to intend readability.
This recently lead me to a scenario constructing a bit-mask in a very efficient manner became hard to read when written idiomatically because it took up a lot of lines of screen, very inefficient when encapsulated as a function, or both, as the code produces branches:
package lib
func maskIfTrue(mask uint64, predicate bool) uint64 {
if predicate {
return mask
}
return 0
}
producing:
text "".maskIfTrue(SB), NOSPLIT|ABIInternal, $0-24
funcdata $0, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB)
funcdata $1, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB)
movblzx "".predicate+16(SP), AX
testb AL, AL
jeq maskIfTrue_pc20
movq "".mask+8(SP), AX
movq AX, "".~r2+24(SP)
ret
maskIfTrue_pc20:
movq $0, "".~r2+24(SP)
ret
What I learned from this was to leverage a little more Go; using a named result in the function (result int)
saves me a line declaring it in the function (and you can do the same with captures), but the compiler also recognizes this idiom (only assign a value IF) and replaces it - if possible - with a conditional instruction.
func zeroOrOne(predicate bool) (result int) {
if predicate {
result = 1
}
return
}
producing a branch-free result:
movblzx "".predicate+8(SP), AX
movq AX, "".result+16(SP)
ret
which go then freely inlines.
package lib
func zeroOrOne(predicate bool) (result int) {
if predicate {
result = 1
}
return
}
type Vendor1 struct {
Property1 int
Property2 float32
Property3 bool
}
// Vendor2 bit positions.
const (
Property1Bit = 2
Property2Bit = 3
Property3Bit = 5
)
func Convert1To2(v1 Vendor1) (result int) {
result |= zeroOrOne(v1.Property1 == 1) << Property1Bit
result |= zeroOrOne(v1.Property2 < 0.0) << Property2Bit
result |= zeroOrOne(v1.Property3) << Property3Bit
return
}
produces https://go.godbolt.org/z/eKbK17
movq "".v1+8(SP), AX
cmpq AX, $1
seteq AL
xorps X0, X0
movss "".v1+16(SP), X1
ucomiss X1, X0
sethi CL
movblzx AL, AX
shlq $2, AX
movblzx CL, CX
shlq $3, CX
orq CX, AX
movblzx "".v1+20(SP), CX
shlq $5, CX
orq AX, CX
movq CX, "".result+24(SP)
ret
This will return longest palindrome string from given string
-(BOOL)isPalindromString:(NSString *)strInput
{
if(strInput.length<=1){
return NO;
}
int halfLenth = (int)strInput.length/2;
BOOL isPalindrom = YES;
for(NSInteger i=0; i<halfLenth; i++){
char a = [strInput characterAtIndex:i];
char b = [strInput characterAtIndex:(strInput.length-1)-i];
if(a != b){
isPalindrom = NO;
break;
}
}
NSLog(@"-%@- IS Plaindrom %@",strInput,(isPalindrom ? @"YES" : @"NO"));
return isPalindrom;
}
-(NSString *)longestPalindrom:(NSString *)strInput
{
if(strInput.length<=1){
return @"";
}
NSString *strMaxPalindrom = @"";
for(int i = 0; i<strInput.length ; i++){
for(int j = i; j<strInput.length ; j++){
NSString *strSub = [strInput substringWithRange:NSMakeRange(i, strInput.length-j)];
if([self isPalindromString:strSub]){
if(strSub.length>strMaxPalindrom.length){
strMaxPalindrom = strSub;
}
}
}
}
NSLog(@"-Max - %@",strMaxPalindrom);
return strMaxPalindrom;
}
-(void)test
{
[self longestPalindrom:@"abcccbadeed"];
}
== OUTPUT ===
Input: abcccde Output: ccc
Input: abcccbd Output: bcccb
Input: abedccde Output: edccde
Input: abcccdeed Output: deed
Input: abcccbadeed Output: abcccba
int indexOf(Object o)
This method returns the index in this list of the first occurrence of the specified element, or -1 if this list does not contain this element.
PHP - curl:
$username = 'myusername';
$password = 'mypassword';
...
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
...
PHP - POST in WordPress:
$username = 'myusername';
$password = 'mypassword';
...
wp_remote_post('https://...some...api...endpoint...', array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode("$username:$password")
)
));
...
You can try this, but second dimension values will be equals to indexes:
$array = array_fill_keys(range(0,5), range(0,5));
a little more complicated for empty array:
$array = array_fill_keys(range(0, 5), array_fill_keys(range(0, 5), null));
Yes, but it's not a div
, it's a fieldset
fieldset {
border: 1px solid #000;
}
_x000D_
<fieldset>
<legend>AAA</legend>
</fieldset>
_x000D_
In addition to the still very relevant answer of jujule, I find it quite important to also be aware of the implications of order_by()
on distinct("field_name")
queries. This is, however, a Postgres only feature!
If you are using Postgres and if you define a field name that the query should be distinct for, then order_by()
needs to begin with the same field name (or field names) in the same sequence (there may be more fields afterward).
Note
When you specify field names, you must provide an order_by() in the QuerySet, and the fields in order_by() must start with the fields in distinct(), in the same order.
For example, SELECT DISTINCT ON (a) gives you the first row for each value in column a. If you don’t specify an order, you’ll get some arbitrary row.
If you want to e-g- extract a list of cities that you know shops in , the example of jujule would have to be adapted to this:
# returns an iterable Queryset of cities.
models.Shop.objects.order_by('city').values_list('city', flat=True).distinct('city')
Like this:
people = []
begin
info = gets.chomp
people += [Person.new(info)] if not info.empty?
end while not info.empty?
Reference: Ruby's Hidden do {} while () Loop
Sub LoopRange()
Dim rCell As Range
Dim rRng As Range
Set rRng = Sheet1.Range("A1:A6")
For Each rCell In rRng.Cells
Debug.Print rCell.Address, rCell.Value
Next rCell
End Sub
This can be an efficient way of performing different tests on a single statement
select
case colour_txt
when 'red' then 5
when 'green' then 4
when 'orange' then 3
else 0
end as Pass_Flag
this only works on equality comparisons!
http://www.jstott.me.uk/jcoord/ - use this library
LatLng lld1 = new LatLng(40.718119, -73.995667);
LatLng lld2 = new LatLng(51.499981, -0.125313);
Double distance = lld1.distance(lld2);
Log.d(TAG, "Distance in kilometers " + distance);
You can do this by providing in class numbers
:
By the way, there is a strong convention that Java class names are uppercased.
Case 1 (simple getter):
public class Numbers {
private List<Integer> list;
public List<Integer> getList() { return list; }
...
}
Case 2 (non-modifiable wrapper):
public class Numbers {
private List<Integer> list;
public List<Integer> getList() { return Collections.unmodifiableList( list ); }
...
}
Case 3 (specific methods):
public class Numbers {
private List<Integer> list;
public void addToList( int i ) { list.add(i); }
public int getValueAtIndex( int index ) { return list.get( index ); }
...
}
To clarify which command to use based on the situation
exec()
- Execute an external program
system()
- Execute an external program and display the output
passthru()
- Execute an external program and display raw output
How about using underscorejs
str = "There are so many places on earth that I want to go, i just dont have time. :("
firstWord = _.first( str.split(" ") )
DateFormat.format
only works on Date
values.
You should use two SimpleDateFormat objects: one for parsing, and one for formatting. For example:
// Note, MM is months, not mm
DateFormat outputFormat = new SimpleDateFormat("MM/yyyy", Locale.US);
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.US);
String inputText = "2012-11-17T00:00:00.000-05:00";
Date date = inputFormat.parse(inputText);
String outputText = outputFormat.format(date);
EDIT: Note that you may well want to specify the time zone and/or locale in your formats, and you should also consider using Joda Time instead of all of this to start with - it's a much better date/time API.
Install redis on your system first -
brew install redis
then start the redis server -
redis-server
I looked for a long time for a decent, and preferably free, tool for linux and found this java application that is quite good (finally!!):
http://sqldeveloper.solyp.com/
Being Java it is cross-platform (I run it on Linux with no issues) and it will connect to any database you can get a JDBC driver for. ie: pretty much any database.
It is quite easy to import your database and get a visual (ERM) of the database schema. The auto-layout feature is good as well, but note that it is not done automatically and you need to click the "automatic layout" button after importing your objects into the diagram.
The application is also a pretty good generic database administration/browsing tool. As one small example, I use it instead of pgadmin for some base development work because of simple niceties like the column width of SQL query results automatically sizing to fit content (which drives me crazy in pgadmin).
You are most likely getting the TypeError because you need quotes around the datecolumn value.
Try:
now = datetime.datetime(2009, 5, 5)
cursor.execute("INSERT INTO table (name, id, datecolumn) VALUES (%s, %s, '%s')",
("name", 4, now))
With regards to the format, I had success with the above command (which includes the milliseconds) and with:
now.strftime('%Y-%m-%d %H:%M:%S')
Hope this helps.
Are you working with a @Service
too? Because if you are, then you can @Autowired
your PersonRepository
to the @Service
and then in the service just invoke the Name
class and use the form that @CuriosMind... proposed:
@Query(select p from Person p where p.forename = :forename and p.surname = :surname)
User findByForenameAndSurname(@Param("surname") String lastname,
@Param("forename") String firstname);
}
and when invoking the method from the repository in the service, you can then pass those parameters.
Use SHOW OPEN TABLES
:
http://dev.mysql.com/doc/refman/5.1/en/show-open-tables.html
You can do something like this
SHOW OPEN TABLES WHERE `Table` LIKE '%[TABLE_NAME]%' AND `Database` LIKE '[DBNAME]' AND In_use > 0;
to check any locked tables in a database.
Doing this inline, I set the margin to 0 (ul style="margin:-0px"). The bullets align with paragraph with no overhang.
svn:// doesn't talk http, therefor there's nothing a http proxy could do.
Any reason why http doesn't work? Have you considered https? If you really need it, you probably have to have port 3690 opened in your firewall.
"Where should I copy ICSharpCode.SharpZipLib.dll to see that namespace in Visual Studio?"
You need to add the dll file as a reference in your project. Right click on References in the Solution Explorer->Add Reference->Browse and then select the dll.
Finally you'll need to add it as a using statement in whatever files you want to use it in.
from urllib.request import Request, urlopen
url="https://svnweb.freebsd.org/csrg/share/dict/words?revision=61569&view=co"
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
web_byte = urlopen(req).read()
webpage = web_byte.decode('utf-8')
print(webpage)
Randomizing the first 500 words
from urllib.request import Request, urlopen
import random
url="https://svnweb.freebsd.org/csrg/share/dict/words?revision=61569&view=co"
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
web_byte = urlopen(req).read()
webpage = web_byte.decode('utf-8')
first500 = webpage[:500].split("\n")
random.shuffle(first500)
print(first500)
Output
['abnegation', 'able', 'aborning', 'Abigail', 'Abidjan', 'ablaze', 'abolish', 'abbe', 'above', 'abort', 'aberrant', 'aboriginal', 'aborigine', 'Aberdeen', 'Abbott', 'Abernathy', 'aback', 'abate', 'abominate', 'AAA', 'abc', 'abed', 'abhorred', 'abolition', 'ablate', 'abbey', 'abbot', 'Abelson', 'ABA', 'Abner', 'abduct', 'aboard', 'Abo', 'abalone', 'a', 'abhorrent', 'Abelian', 'aardvark', 'Aarhus', 'Abe', 'abjure', 'abeyance', 'Abel', 'abetting', 'abash', 'AAAS', 'abdicate', 'abbreviate', 'abnormal', 'abject', 'abacus', 'abide', 'abominable', 'abode', 'abandon', 'abase', 'Ababa', 'abdominal', 'abet', 'abbas', 'aberrate', 'abdomen', 'abetted', 'abound', 'Aaron', 'abhor', 'ablution', 'abeyant', 'about']
There is currently no way to do this out of the box, but there is a User Voice suggestion for adding it: http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2037649-implement-indexed-full-text-search-of-work-items
While I doubt it is as simple as flipping a switch, if everyone that has viewed this question voted for it, MS would probably implement something.
Update: Just read Brian Harry's blog, which shows this request as being on their radar, and the Online version of Visual Studio has limited support for searching where git is used as the vcs: http://blogs.msdn.com/b/visualstudioalm/archive/2015/02/13/announcing-limited-preview-for-visual-studio-online-code-search.aspx. From this I think it's fair to say it is just a matter of time...
Update 2: There is now a Microsoft provided extension,Code Search which enables searching in code as well as in work items.
You can't do this, which is by design. The Django framework authors intended a strict separation of presentation code from data logic. Filtering models is data logic, and outputting HTML is presentation logic.
So you have several options. The easiest is to do the filtering, then pass the result to render_to_response
. Or you could write a method in your model so that you can say {% for object in data.filtered_set %}
. Finally, you could write your own template tag, although in this specific case I would advise against that.
Here is a real world example:
String hallostring = "hallo";
String asubstring = hallostring.substring(0, 1);
In the example asubstring would return: h
Probably not exactly your issue..
Do you have any spaces in your package path? You should wrap it up in double quotes to be safe, otherwise it can be taken as two separate arguments
sudo installer -store -pkg "/User/MyName/Desktop/helloWorld.pkg" -target /
One issue I came up with that prevented these two files from working correctly was with my php.ini
file for the website. Make sure this property is properly set, as follows:
allow_url_fopen =
PHP complains because end()
expects a reference to something that it wants to change (which can be a variable only). You however pass the result of explode()
directly to end()
without saving it to a variable first. At the moment when explode()
returns your value, it exists only in memory and no variable points to it. You cannot create a reference to something (or to something unknown in the memory), that does not exists.
Or in other words: PHP does not know, if the value you give him is the direct value or just a pointer to the value (a pointer is also a variable (integer), which stores the offset of the memory, where the actual value resides). So PHP expects here a pointer (reference) always.
But since this is still just a notice (not even deprecated) in PHP 7, you can savely ignore notices and use the ignore-operator instead of completely deactivating error reporting for notices:
$file_extension = @end(explode('.', $file_name));
I just solved this exact issue for myself; even referenced this question.
I'm assuming you haven't written the "all" rule that Eclipse is complaining about. If this is the case, take these steps:
This lets Eclipse know you aren't trying to use a make target called "all". For some reason, that is the default.
On parent div you can add
overflow-y: scroll;
overflow-x: hidden;
When I had this issue the cause was a relative reference to template files when using the ui.bootstrap.modal module.
templateUrl: 'js/templates/modal.html'
This works from a root domain (www.example.com) but when a path is added (www.example.com/path/) the reference breaks. The answer in my case was simply to making the reference absolute (js/ -> /js/).
templateUrl: '/js/templates/modal.html'
In some cases (like in my case) you may be trying to delete an image by specifying the image id that has multiple tags that you don't realize exist, some of which may be used by other images. In which case, you may not want to remove the image.
If you have a case of redundant tags as described here, instead of docker rmi <image_id>
use docker rmi <repo:tag>
on the redundant tag you wish to remove.
Open the properties of the solution and click publish. Then, reclick application files. Change prerequisite to include.
Try something like this:
<input type="text" name="idtest" value="<?php echo htmlspecialchars($name); ?>" />
That is, the same as what thirtydot suggested, except preventing XSS attacks as well.
You could also use the <?=
syntax (see the note), although that might not work on all servers. (It's enabled by a configuration option.)
There's the short tag version of your code, which is now completely acceptable to use despite antiquated recommendations otherwise:
<input type="hidden" name="type" value="<?= $var ?>" >
which (prior to PHP 5.4) requires short tags be enabled in your php configuration. It functions exactly as the code you typed; these lines are literally identical in their internal implementation:
<?= $var1, $var2 ?>
<?php echo $var1, $var2 ?>
That's about it for built-in solutions. There are plenty of 3rd party template libraries that make it easier to embed data in your output, smarty is a good place to start.
backdrop-filter
Unfortunately Mozilla has really dropped the ball and taken it's time with the feature. I'm personally hoping it makes it in to the next Firefox ESR as that is what the next major version of Waterfox will use.
MDN (Mozilla Developer Network) article: https://developer.mozilla.org/en-US/docs/Web/CSS/backdrop-filter
Mozilla implementation: https://bugzilla.mozilla.org/show_bug.cgi?id=1178765
From the MDN documentation page:
/* URL to SVG filter */
backdrop-filter: url(commonfilters.svg#filter);
/* <filter-function> values */
backdrop-filter: blur(2px);
backdrop-filter: brightness(60%);
backdrop-filter: contrast(40%);
backdrop-filter: drop-shadow(4px 4px 10px blue);
backdrop-filter: grayscale(30%);
backdrop-filter: hue-rotate(120deg);
backdrop-filter: invert(70%);
backdrop-filter: opacity(20%);
backdrop-filter: sepia(90%);
backdrop-filter: saturate(80%);
/* Multiple filters */
backdrop-filter: url(filters.svg#filter) blur(4px) saturate(150%);
Use iloc to access by position (rather than label):
In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])
In [12]: df
Out[12]:
A B
a 1 2
b 3 4
In [13]: df.iloc[0] # first row in a DataFrame
Out[13]:
A 1
B 2
Name: a, dtype: int64
In [14]: df['A'].iloc[0] # first item in a Series (Column)
Out[14]: 1
Use show/hide method as below
$("div").show();//To Show
$("div").hide();//To Hide
Android Studio v1.2 installs the adb tool in this path:
~/Library/Android/sdk/platform-tools/adb
So it goes like this:
adb version
and expect an error outputtouch ~/.bash_profile
open ~/.bash_profile
source ~/.bash_profile
adb version
and expect an outputGood luck!
Jarret Hardie is correct. Or, first merge your changes back into master and then try the push. By default, git push
pushes all branches that have names that match on the remote -- and no others. So those are your two choices -- either specify it explicitly like Jarret said or merge back to a common branch and then push.
There's been talk about this on the Git mail list and it's clear that this behavior is not about to change anytime soon -- many developers rely on this behavior in their workflows.
Edit/Clarification
Assuming your upstreammaster
branch is ready to push then you could do this:
Pull in any changes from the upstream.
$ git pull upstream master
Switch to my local master branch
$ git checkout master
Merge changes in from upstreammaster
$ git merge upstreammaster
Push my changes up
$ git push upstream
Another thing that you may want to do before pushing is to rebase
your changes against upstream/master so that your commits are all together. You can either do that as a separate step between #1 and #2 above (git rebase upstream/master
) or you can do it as part of your pull (git pull --rebase upstream master
)
Thanks a lot Codo.
I've just updated and completed what you have done to :
add, remove and update node (who knows)
Option Explicit
Private ScriptEngine As ScriptControl
Public Sub InitScriptEngine()
Set ScriptEngine = New ScriptControl
ScriptEngine.Language = "JScript"
ScriptEngine.AddCode "function getProperty(jsonObj, propertyName) { return jsonObj[propertyName]; } "
ScriptEngine.AddCode "function getType(jsonObj, propertyName) {return typeof(jsonObj[propertyName]);}"
ScriptEngine.AddCode "function getKeys(jsonObj) { var keys = new Array(); for (var i in jsonObj) { keys.push(i); } return keys; } "
ScriptEngine.AddCode "function addKey(jsonObj, propertyName, value) { jsonObj[propertyName] = value; return jsonObj;}"
ScriptEngine.AddCode "function removeKey(jsonObj, propertyName) { var json = jsonObj; delete json[propertyName]; return json }"
End Sub
Public Function removeJSONProperty(ByVal JsonObject As Object, propertyName As String)
Set removeJSONProperty = ScriptEngine.Run("removeKey", JsonObject, propertyName)
End Function
Public Function updateJSONPropertyValue(ByVal JsonObject As Object, propertyName As String, value As String) As Object
Set updateJSONPropertyValue = ScriptEngine.Run("removeKey", JsonObject, propertyName)
Set updateJSONPropertyValue = ScriptEngine.Run("addKey", JsonObject, propertyName, value)
End Function
Public Function addJSONPropertyValue(ByVal JsonObject As Object, propertyName As String, value As String) As Object
Set addJSONPropertyValue = ScriptEngine.Run("addKey", JsonObject, propertyName, value)
End Function
Public Function DecodeJsonString(ByVal JsonString As String)
InitScriptEngine
Set DecodeJsonString = ScriptEngine.Eval("(" + JsonString + ")")
End Function
Public Function GetProperty(ByVal JsonObject As Object, ByVal propertyName As String) As Variant
GetProperty = ScriptEngine.Run("getProperty", JsonObject, propertyName)
End Function
Public Function GetObjectProperty(ByVal JsonObject As Object, ByVal propertyName As String) As Object
Set GetObjectProperty = ScriptEngine.Run("getProperty", JsonObject, propertyName)
End Function
Public Function SerializeJSONObject(ByVal JsonObject As Object) As String()
Dim Length As Integer
Dim KeysArray() As String
Dim KeysObject As Object
Dim Index As Integer
Dim Key As Variant
Dim tmpString As String
Dim tmpJSON As Object
Dim tmpJSONArray() As Variant
Dim tmpJSONObject() As Variant
Dim strJsonObject As String
Dim tmpNbElement As Long, i As Long
InitScriptEngine
Set KeysObject = ScriptEngine.Run("getKeys", JsonObject)
Length = GetProperty(KeysObject, "length")
ReDim KeysArray(Length - 1)
Index = 0
For Each Key In KeysObject
tmpString = ""
If ScriptEngine.Run("getType", JsonObject, Key) = "object" Then
'MsgBox "object " & SerializeJSONObject(GetObjectProperty(JsonObject, Key))(0)
Set tmpJSON = GetObjectProperty(JsonObject, Key)
strJsonObject = VBA.Replace(ScriptEngine.Run("getKeys", tmpJSON), " ", "")
tmpNbElement = Len(strJsonObject) - Len(VBA.Replace(strJsonObject, ",", ""))
If VBA.IsNumeric(Left(ScriptEngine.Run("getKeys", tmpJSON), 1)) = True Then
ReDim tmpJSONArray(tmpNbElement)
For i = 0 To tmpNbElement
tmpJSONArray(i) = GetProperty(tmpJSON, i)
Next
tmpString = "[" & Join(tmpJSONArray, ",") & "]"
Else
tmpString = "{" & Join(SerializeJSONObject(tmpJSON), ", ") & "}"
End If
Else
tmpString = GetProperty(JsonObject, Key)
End If
KeysArray(Index) = Key & ": " & tmpString
Index = Index + 1
Next
SerializeJSONObject = KeysArray
End Function
Public Function GetKeys(ByVal JsonObject As Object) As String()
Dim Length As Integer
Dim KeysArray() As String
Dim KeysObject As Object
Dim Index As Integer
Dim Key As Variant
InitScriptEngine
Set KeysObject = ScriptEngine.Run("getKeys", JsonObject)
Length = GetProperty(KeysObject, "length")
ReDim KeysArray(Length - 1)
Index = 0
For Each Key In KeysObject
KeysArray(Index) = Key
Index = Index + 1
Next
GetKeys = KeysArray
End Function
You can use any
:
print any(df.column == 07311954)
True #true if it contains the number, false otherwise
If you rather want to see how many times '07311954' occurs in a column you can use:
df.column[df.column == 07311954].count()
In my case, the problem was with a scatterplot of a dataframe X[]:
ax.scatter(X[:,0],X[:,1],c=colors,
cmap=CMAP, edgecolor='k', s=40) #c=y[:,0],
#ValueError: setting an array element with a sequence.
#Fix with .toarray():
colors = 'br'
y = label_binarize(y, classes=['Irrelevant','Relevant'])
ax.scatter(X[:,0].toarray(),X[:,1].toarray(),c=colors,
cmap=CMAP, edgecolor='k', s=40)
I had the same problem (forms with tons of text fields and unskilled users).
I solved it in this way:
function chkSubmit() {
if (window.confirm('Do you want to store the data?')) {
return true;
} else {
// some code to focus on a specific field
return false;
}
}
using this in the HTML code:
<form
action="go.php"
method="post"
accept-charset="utf-8"
enctype="multipart/form-data"
onsubmit="return chkSubmit()"
>
In this way the ENTER
key works as planned, but a confirmation (a second ENTER
tap, usually) is required.
I leave to the readers the quest for a script sending the user in the field where he pressed ENTER
if he decide to stay on the form.
MySQL makes a difference between "localhost" and "127.0.0.1".
It might be possible that 'root'@'localhost' is not allowed because there is an entry in the user table that will only allow root login from 127.0.0.1.
This could also explain why some application on your server can connect to the database and some not because there are different ways of connecting to the database. And you currently do not allow it through "localhost".
Using HttpClient (Http's replacement) in Angular 4.3+, the entire mapping/casting process is made simpler/eliminated.
Using your CountryData class, you would define a service method like this:
getCountries() {
return this.httpClient.get<CountryData[]>('http://theUrl.com/all');
}
Then when you need it, define an array like this:
countries:CountryData[] = [];
and subscribe to it like this:
this.countryService.getCountries().subscribe(countries => this.countries = countries);
A complete setup answer is posted here also.
Here is my Java code for Selenium WebDriver. Write the following method and call it during assertion:
protected boolean isElementPresent(By by){
try{
driver.findElement(by);
return true;
}
catch(NoSuchElementException e){
return false;
}
}
Another option is to enclose the unwanted lines in an IF block that can never be true
if 1==0 (
...
)
Of course nothing within the if block will be executed, but it will be parsed. So you can't have any invalid syntax within. Also, the comment cannot contain )
unless it is escaped or quoted. For those reasons the accepted GOTO solution is more reliable. (The GOTO solution may also be faster)
Update 2017-09-19
Here is a cosmetic enhancement to pdub's GOTO solution. I define a simple environment variable "macro" that makes the GOTO comment syntax a bit better self documenting. Although it is generally recommended that :labels are unique within a batch script, it really is OK to embed multiple comments like this within the same batch script.
@echo off
setlocal
set "beginComment=goto :endComment"
%beginComment%
Multi-line comment 1
goes here
:endComment
echo This code executes
%beginComment%
Multi-line comment 2
goes here
:endComment
echo Done
Or you could use one of these variants of npocmaka's solution. The use of REM instead of BREAK makes the intent a bit clearer.
rem.||(
remarks
go here
)
rem^ ||(
The space after the caret
is critical
)
Or you can look at schemacrawler
for example:
<ImageView android:id="@+id/image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxWidth="42dp"
android:maxHeight="42dp"
android:scaleType="fitCenter"
android:layout_marginLeft="3dp"
android:src="@drawable/icon"
/>
Add property android:scaleType="fitCenter"
and android:adjustViewBounds="true"
.
del parentpath
(or just place the .bat file inside parent folder) *.txt /s
That will delete all .txt files in the parent and all sub folders. If you want to delete multiple file extensions just add a space and do the same thing. Ex. *.txt *.dll *.xml
In HTML:
<button type="button" id="AddButton" onclick="AddButtonClick()" class="btn btn-success btn-block ">Add</button>
In Jquery write this function:
function AddButtonClick(){
//change text from add to Update
$("#AddButton").text('Update');
}
To initialize a two-dimensional array in Python:
a = [[0 for x in range(columns)] for y in range(rows)]
recommend using DI approach from other answers instead of this approach
You should be able to use the class directly
new DatePipe().transform(myDate, 'yyyy-MM-dd');
For instance
var raw = new Date(2015, 1, 12);
var formatted = new DatePipe().transform(raw, 'yyyy-MM-dd');
expect(formatted).toEqual('2015-02-12');
I have a hard time remember the char to int conversions so this could be optimized
def decryptCaesar(encrypted, shift):
minRange = ord('a')
decrypted = ""
for char in encrypted:
decrypted += chr(((ord(char) - minRange + shift) % 26) + minRange)
return decrypted
Using the Windows Command Prompt you can increase the buffer size of the window as much you want to see the number of columns. This depends on the no of columns in the table.
sysctl -w net.ipv4.tcp_timestamps=1
sysctl -w net.ipv4.tcp_tw_recycle=1
-- TRY THIS --
select name= case when isnumeric(empname)= 1 then 'numeric' else 'notmumeric' end from [Employees]
But conversion is quit impossible
select empname=
case
when isnumeric(empname)= 1 then empname
else 'notmumeric'
end
from [Employees]
To anyone still struggling to get the os.environ
solution to work as I was, check that this is placed before you import tensorflow
in your script, just like mwweb's answer:
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # or any {'0', '1', '2'}
import tensorflow as tf
var test2NotInTest1 = test2.Where(t2 => test1.Count(t1 => t2.Contains(t1))==0);
Faster version as per Tim's suggestion:
var test2NotInTest1 = test2.Where(t2 => !test1.Any(t1 => t2.Contains(t1)));
You can look at the headers or libs installed. pkg-config can tell you where they are:
pkg-config --cflags opencv
pkg-config --libs opencv
Alternatively you can write a simple program and print the following defs:
CV_MAJOR_VERSION
CV_MINOR_VERSION
A similar question has been also asked here:
calling
var parsed_data = JSON.parse(data);
should result in the ability to access the data like you want.
console.log(parsed_data.success);
should now show '1'
After reading all these answers here in order to symbolicate a crash log (and finally succeeding) I think there are some points missing here that are really important in order to determine why the invocation of symbolicatecrash does not produce a symbolicated output.
There are 3 assets that have to fit together when symbolicating a crash log:
example.crash
), either exported from XCode's organizer or received from iTunes Connect..app
package (i.e. example.app
) that itself contains the app binary belonging to the crash log. If you have an .ipa
package (i.e. example.ipa
) then you can extract the .app
package by unzipping the .ipa
package (i.e. unzip example.ipa
). Afterwards the .app
package resides in the extracted Payload/
folder..dSYM
package containing the debug symbols (i.e. example.app.dSYM
)Before starting symbolication you should check if all those artifacts match, which means that the crash log belongs to the binary you have and that the debug symbols are the ones produced during the build of that binary.
Each binary is referred by a UUID that can be seen in the crash log file:
...
Binary Images:
0xe1000 - 0x1f0fff +example armv7 <aa5e633efda8346cab92b01320043dc3> /var/mobile/Applications/9FB5D11F-42C0-42CA-A336-4B99FF97708F/example.app/example
0x2febf000 - 0x2fedffff dyld armv7s <4047d926f58e36b98da92ab7a93a8aaf> /usr/lib/dyld
...
In this extract the crash log belongs to an app binary image named example.app/example with UUID aa5e633efda8346cab92b01320043dc3
.
You can check the UUID of the binary package you have with dwarfdump:
dwarfdump --uuid example.app/example
UUID: AA5E633E-FDA8-346C-AB92-B01320043DC3 (armv7) example.app/example
Afterwards you should check if the debug symbols you have also belong to that binary:
dwarfdump --uuid example.app.dSYM
UUID: AA5E633E-FDA8-346C-AB92-B01320043DC3 (armv7) example.app.dSYM/Contents/Resources/DWARF/example
In this example all assets fit together and you should be able to symbolicate your stacktrace.
Proceeding to the symbolicatecrash
script:
In Xcode 8.3 you should be able to invoke the script via
/Applications/Xcode.app/Contents/SharedFrameworks/DVTFoundation.framework/Versions/A/Resources/symbolicatecrash -v example.crash 2> symbolicate.log
If it is not there you may run a find . -name symbolicatecrash
in your Xcode.app directory to find it.
As you can see there are no more parameters given. So the script has to find your application binary and debug symbols by running a spotlight search. It searches the debug symbols with a specific index called com_apple_xcode_dsym_uuids
. You can do this search yourself:
mdfind 'com_apple_xcode_dsym_uuids = *'
resp.
mdfind "com_apple_xcode_dsym_uuids == AA5E633E-FDA8-346C-AB92-B01320043DC3"
The first spotlight invocation gives you all indexed dSYM packages and the second one gives you the .dSYM
packages with a specific UUID. If spotlight does not find your .dSYM
package then symbolicatecrash
will neither. If you do all this stuff e.g. in a subfolder of your ~/Desktop
spotlight should be able to find everything.
If symbolicatecrash
finds your .dSYM
package there should be a line like the following in symbolicate.log
:
@dsym_paths = ( <SOME_PATH>/example.app.dSYM/Contents/Resources/DWARF/example )
For finding your .app
package a spotlight search like the following is invoked by symbolicatecrash
:
mdfind "kMDItemContentType == com.apple.application-bundle && (kMDItemAlternateNames == 'example.app' || kMDItemDisplayName == 'example' || kMDItemDisplayName == 'example.app')"
If symbolicatecrash
finds your .app
package there should be the following extract in symbolicate.log
:
Number of symbols in <SOME_PATH>/example.app/example: 2209 + 19675 = 21884
Found executable <SOME_PATH>/example.app/example
-- MATCH
If all those resources are found by symbolicatecrash
it should print out the symbolicated version of your crash log.
If not you can pass in your dSYM and .app files directly.
symbolicatecrash -v --dsym <SOME_PATH>/<App_URI>.app.dSYM/<APP_NAME>.app.dsym <CRASHFILE> <SOME_OTHER_PATH>/<APP_NAME>.app/<APP_NAME> > symbolicate.log
Note: The symbolicated backtrace will be output to terminal, not symbolicate.log
.
To resolve the issue on a Debian/Ubuntu system modify the /etc/apache2/ports.conf
settings file by adding NameVirtualHost *:443
to it. My ports.conf
is the following at the moment:
# /etc/apache/ports.conf
# If you just change the port or add more ports here, you will likely also
# have to change the VirtualHost statement in
# /etc/apache2/sites-enabled/000-default
# This is also true if you have upgraded from before 2.2.9-3 (i.e. from
# Debian etch). See /usr/share/doc/apache2.2-common/NEWS.Debian.gz and
# README.Debian.gz
NameVirtualHost *:80
Listen 80
<IfModule mod_ssl.c>
# If you add NameVirtualHost *:443 here, you will also have to change
# the VirtualHost statement in /etc/apache2/sites-available/default-ssl
# to <VirtualHost *:443>
# Server Name Indication for SSL named virtual hosts is currently not
# supported by MSIE on Windows XP.
NameVirtualHost *:443
Listen 443
</IfModule>
<IfModule mod_gnutls.c>
NameVirtualHost *:443
Listen 443
</IfModule>
Furthermore ensure that 'sites-available/default-ssl' is not enabled, type a2dissite default-ssl
to disable the site. While you're at it type a2dissite
by itself to get a list and see if there is any other site settings that you have enabled that might be mapping onto port 443.
Please note that MVC 3 onwards the persistence behavior of TempData has changed, now the value in TempData is persisted until it is read, and not just for the next request.
The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request. https://msdn.microsoft.com/en-in/library/dd394711%28v=vs.100%29.aspx
using select-object
for example:
Get-ADUser -Filter * -SearchBase 'OU=Users & Computers, DC=aaaaaaa, DC=com' -Properties DisplayName | select -expand displayname | Export-CSV "ADUsers.csv"
This example uses memoization, basically storing values in a table (dictionary in this case) so you can look them up later instead of recalculating them.
Here we use a simple class with a __call__
method to calculate factorials (through a callable object) instead of a factorial function that contains a static variable (as that's not possible in Python).
class Factorial:
def __init__(self):
self.cache = {}
def __call__(self, n):
if n not in self.cache:
if n == 0:
self.cache[n] = 1
else:
self.cache[n] = n * self.__call__(n-1)
return self.cache[n]
fact = Factorial()
Now you have a fact
object which is callable, just like every other function. For example
for i in xrange(10):
print("{}! = {}".format(i, fact(i)))
# output
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
And it is also stateful.
For the question
How can i run a jar file in command prompt but with arguments
.
To pass arguments to the jar file at the time of execution
java -jar myjar.jar arg1 arg2
In the main() method of "Main-Class" [mentioned in the manifest.mft file]of your JAR file. you can retrieve them like this:
String arg1 = args[0];
String arg2 = args[1];
This sometimes happens when you have a random XML file doing nothing. Removing the file resolves the issue.
I would use DBA_SOURCE (if you have access to it) because if the object you require is not owned by the schema under which you are logged in you will not see it.
If you need to know the functions and Procs inside the packages try something like this:
select * from all_source
where type = 'PACKAGE'
and (upper(text) like '%FUNCTION%' or upper(text) like '%PROCEDURE%')
and owner != 'SYS';
The last line prevents all the sys stuff (DBMS_ et al) from being returned. This will work in user_source if you just want your own schema stuff.
If you want to install requests directly you can use the "-m" (module) option available to python.
python.exe -m pip install requests
You can do this directly in PowerShell, though you may need to use the full python path (eg. C:\Python27\python.exe
) instead of just python.exe
.
As mentioned in the comments, if you have added Python to your path you can simply do:
python -m pip install requests
The simplest solution is :
listView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
listView.setStackFromBottom(true);
To stay portable you could use Boost::Thread for sleeping:
#include <boost/thread/thread.hpp>
int main()
{
//waits 2 seconds
boost::this_thread::sleep( boost::posix_time::seconds(1) );
boost::this_thread::sleep( boost::posix_time::milliseconds(1000) );
return 0;
}
This answer is a duplicate and has been posted in this question before. Perhaps you could find some usable answers there too.
Usually this happens if something is wrong with the byte array.
File.WriteAllBytes("filename.PDF", Byte[]);
This creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.
Asynchronous implementation of this is also available.
public static System.Threading.Tasks.Task WriteAllBytesAsync
(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = null);
You are apparently using Django.
You are probably better off just using models.IntegerField()
instead of models.TextField()
. Not only will it do the check for you, but it will give you the error message translated in several langs, and it will cast the value from it's type in the database to the type in your Python code transparently.
There are already so many good answers on this thread! I am going to post this to help anybody trying to do this automatically! To automatically remove unused imports for the whole project this article was really helpful to me.
In the article the author explains it like this:
Make a stand alone tslint file that has the following in it:
{
"extends": ["tslint-etc"],
"rules": {
"no-unused-declaration": true
}
}
Then run the following command to fix the imports:
tslint --config tslint-imports.json --fix --project .
Consider fixing any other errors it throws. (I did)
Then check the project works by building it:
ng build
or
ng build name_of_project --configuration=production
End: If it builds correctly, you have successfully removed imports automatically!
NOTE: This only removes unnecessary imports. It does not provide the other features that VS Code does when using one of the commands previously mentioned.
NetBeans update their tutorial for JDK8 and this Issue:
Getting Started with JAX-WS Web Services -> Enabling Access to External Schema
You can load both json strings into Python Dictionaries and then combine. This will only work if there are unique keys in each json string.
import json
a = json.loads(jsonStringA)
b = json.loads(jsonStringB)
c = dict(a.items() + b.items())
# or c = dict(a, **b)
Something like this (not tested)
with match_groups as (
select product_id,
matching_product_id,
product_id as group_id
from matches
where product_id not in (select matching_product_id from matches)
union all
select m.product_id, m.matching_product_id, p.group_id
from matches m
join match_groups p on m.product_id = p.matching_product_id
)
select group_id, product_id
from match_groups
order by group_id;
Install this nuget package from Microsoft System.Net.Http.Json
. It contains extension methods.
Then add using System.Net.Http.Json
Now, you'll be able to see these methods:
So you can now do this:
await httpClient.GetFromJsonAsync<IList<WeatherForecast>>("weatherforecast");
Source: https://www.stevejgordon.co.uk/sending-and-receiving-json-using-httpclient-with-system-net-http-json
I noticed this wasn't working with a static-first-then-reverse-proxy setup. Here's what that looks like:
location @app {
proxy_pass http://localhost:3000$request_uri;
}
location / {
try_files $uri $uri/ @app;
error_page 405 @app;
}
If you have a valid but untrusted ssl-certificates you can import it in Extras/Properties/Advanced/Encryption --> View Certificates. After Importing ist as "Servers" you have to "Edit trust" to "Trust the authenticity of this certifikate" and that' it. I always have trouble with recording secure websites with HP VuGen and Performance Center
I solved this by copying the branch data (with the errors) to my apple laptop local git folder.
Somehow in the terminal and when running: git status, tells me more specific data where the error occurs. If you look under the errors, hopefully you see a list of folders with error. In my case GIT showed the folder which was responsible for the error. Deleting that folder and commiting the branche, I succeeded. git status was working again the other devices updating by git pull; everything working again on every machine.
Hopefully this will work for you also.
These are the very basic pivot example kindly go through that.
SQL SERVER – PIVOT and UNPIVOT Table Examples
Example from above link for the product table:
SELECT PRODUCT, FRED, KATE
FROM (
SELECT CUST, PRODUCT, QTY
FROM Product) up
PIVOT (SUM(QTY) FOR CUST IN (FRED, KATE)) AS pvt
ORDER BY PRODUCT
renders:
PRODUCT FRED KATE
--------------------
BEER 24 12
MILK 3 1
SODA NULL 6
VEG NULL 5
Similar examples can be found in the blog post Pivot tables in SQL Server. A simple sample
You should use the * operator, like foo(*values)
Read the Python doc unpackaging argument lists.
Also, do read this: http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
def foo(x,y,z):
return "%d, %d, %d" % (x,y,z)
values = [1,2,3]
# the solution.
foo(*values)
Hope you don't mind but I cobbled together all the helpful stuff, from above, and came up with a complete class ready for testing...
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class MultiBrowPop {
public static void main(String[] args) {
OUT("\nWelcome to Multi Brow Pop.\nThis aims to popup a browsers in multiple operating systems.\nGood luck!\n");
String url = "http://www.birdfolk.co.uk/cricmob";
OUT("We're going to this page: "+ url);
String myOS = System.getProperty("os.name").toLowerCase();
OUT("(Your operating system is: "+ myOS +")\n");
try {
if(Desktop.isDesktopSupported()) { // Probably Windows
OUT(" -- Going with Desktop.browse ...");
Desktop desktop = Desktop.getDesktop();
desktop.browse(new URI(url));
} else { // Definitely Non-windows
Runtime runtime = Runtime.getRuntime();
if(myOS.contains("mac")) { // Apples
OUT(" -- Going on Apple with 'open'...");
runtime.exec("open " + url);
}
else if(myOS.contains("nix") || myOS.contains("nux")) { // Linux flavours
OUT(" -- Going on Linux with 'xdg-open'...");
runtime.exec("xdg-open " + url);
}
else
OUT("I was unable/unwilling to launch a browser in your OS :( #SadFace");
}
OUT("\nThings have finished.\nI hope you're OK.");
}
catch(IOException | URISyntaxException eek) {
OUT("**Stuff wrongly: "+ eek.getMessage());
}
}
private static void OUT(String str) {
System.out.println(str);
}
}
Python has a %
operator for this.
>>> a = 5
>>> b = "hello"
>>> buf = "A = %d\n , B = %s\n" % (a, b)
>>> print buf
A = 5
, B = hello
>>> c = 10
>>> buf = "C = %d\n" % c
>>> print buf
C = 10
See this reference for all supported format specifiers.
You could as well use format
:
>>> print "This is the {}th tome of {}".format(5, "knowledge")
This is the 5th tome of knowledge
To do this you should alter the vertical-align property of the input.
<dd><label class="<?=$email_confirm_class;?>" style="text-align:right; padding-right:3px">Confirm Email</label><input class="text" type="text" style="vertical-align: middle; border:none;" name="email_confirm" id="email_confirm" size="18" value="<?=$_POST['email_confirm'];?>" tabindex="4" /> *</dd>
Here is a more complete version. It has been tested in IE 8 and it works. see the difference by removing the vertical-align: middle from the input:
<html><head></head><body><dl><dt>test</dt><dd><label class="test" style="text-align:right; padding-right:3px">Confirm Email</label><input class="text" type="text" style="vertical-align: middle; font-size: 22px" name="email_confirm" id="email_confirm" size="28" value="test" tabindex="4" /> *</dd></dl></body></html>
Just use indexOf
:
haystack.indexOf(needle) >= 0
If you want to support old Internet Explorers (< IE9), you'll have to include your current code as a workaround though.
Unless your list is sorted, you need to compare every value to the needle. Therefore, both your solution and indexOf
will have to execute n/2
comparisons on average. However, since indexOf
is a built-in method, it may use additional optimizations and will be slightly faster in practice. Note that unless your application searches in lists extremely often (say a 1000 times per second) or the lists are huge (say 100k entries), the speed difference will not matter.
There's also concat, but it doesn't get used much
select concat('a','b') from dual;
is
compares identity. A string will never be identical to a not-string.
==
is equality. But a string will never be equal to either True
or False
.
You want neither.
path = '/bla/bla/bla'
if path:
print "True"
else:
print "False"
As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:
WHILE EXISTS (SELECT 1
FROM YourTable
WHERE <yourCondition>)
DELETE TOP(10000) FROM YourTable
WHERE <yourCondition>
Yes you can pass variable no. of arguments to a function. You can use apply
to achieve this.
E.g.:
var arr = ["Hi","How","are","you"];
function applyTest(){
var arg = arguments.length;
console.log(arg);
}
applyTest.apply(null,arr);
I added the DOCTYPE
directive you see here:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xsl:stylesheet [
<!ENTITY nl "
">
]>
<xsl:stylesheet xmlns:x="http://www.w3.org/2005/02/query-test-XQTSCatalog"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0">
This allows me to use &nl;
instead of 

to produce a newline in the output. Like other solutions, this is typically placed inside a <xsl:text>
tag.
Simply translating the "old for loop way" into streams:
private Map<String, String> mapConfig(Map<String, Integer> input, String prefix) {
int subLength = prefix.length();
return input.entrySet().stream()
.collect(Collectors.toMap(
entry -> entry.getKey().substring(subLength),
entry -> AttributeType.GetByName(entry.getValue())));
}
You have to use target attribute
<a href="newsletter_01.pdf" target="_blank">
Apple's "Build Setting Reference" documentation for what's officially documented (or as rjstelling's answer shows, use env in a build script to see what Xcode actually passes you.
In case the above link changes, Google search for: "build setting reference" site:developer.apple.com
Use cURL
,
Check if you have it via phpinfo();
And for the code:
function getHtml($url, $post = null) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
if(!empty($post)) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
}
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
To see your log in SQL Developer
then press:
CTRL+SHIFT + L (or CTRL + CMD + L on macOS)
or
View -> Log
or by using mysql query
show errors;
Taken from
span() returns both start and end indexes in a single tuple. Since the match method only checks if the RE matches at the start of a string, start() will always be zero. However, the search method of RegexObject instances scans through the string, so the match may not start at zero in that case.
>>> p = re.compile('[a-z]+')
>>> print p.match('::: message')
None
>>> m = p.search('::: message') ; print m
<re.MatchObject instance at 80c9650>
>>> m.group()
'message'
>>> m.span()
(4, 11)
Combine that with:
In Python 2.2, the finditer() method is also available, returning a sequence of MatchObject instances as an iterator.
>>> p = re.compile( ... )
>>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
>>> iterator
<callable-iterator object at 0x401833ac>
>>> for match in iterator:
... print match.span()
...
(0, 2)
(22, 24)
(29, 31)
you should be able to do something on the order of
for match in re.finditer(r'[a-z]', 'a1b2c3d4'):
print match.span()
Late resurrection.
Your query seems very similar to the one at page 259 of the book Pro JPA 2: Mastering the Java Persistence API, which in JPQL reads:
SELECT e
FROM Employee e
WHERE e IN (SELECT emp
FROM Project p JOIN p.employees emp
WHERE p.name = :project)
Using EclipseLink + H2 database, I couldn't get neither the book's JPQL nor the respective criteria working. For this particular problem I have found that if you reference the id directly instead of letting the persistence provider figure it out everything works as expected:
SELECT e
FROM Employee e
WHERE e.id IN (SELECT emp.id
FROM Project p JOIN p.employees emp
WHERE p.name = :project)
Finally, in order to address your question, here is an equivalent strongly typed criteria query that works:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Employee> c = cb.createQuery(Employee.class);
Root<Employee> emp = c.from(Employee.class);
Subquery<Integer> sq = c.subquery(Integer.class);
Root<Project> project = sq.from(Project.class);
Join<Project, Employee> sqEmp = project.join(Project_.employees);
sq.select(sqEmp.get(Employee_.id)).where(
cb.equal(project.get(Project_.name),
cb.parameter(String.class, "project")));
c.select(emp).where(
cb.in(emp.get(Employee_.id)).value(sq));
TypedQuery<Employee> q = em.createQuery(c);
q.setParameter("project", projectName); // projectName is a String
List<Employee> employees = q.getResultList();
This is a verbose translation of what Symfony uses to get the host name (see the second example for a more literal translation):
function getHost() {
$possibleHostSources = array('HTTP_X_FORWARDED_HOST', 'HTTP_HOST', 'SERVER_NAME', 'SERVER_ADDR');
$sourceTransformations = array(
"HTTP_X_FORWARDED_HOST" => function($value) {
$elements = explode(',', $value);
return trim(end($elements));
}
);
$host = '';
foreach ($possibleHostSources as $source)
{
if (!empty($host)) break;
if (empty($_SERVER[$source])) continue;
$host = $_SERVER[$source];
if (array_key_exists($source, $sourceTransformations))
{
$host = $sourceTransformations[$source]($host);
}
}
// Remove port number from host
$host = preg_replace('/:\d+$/', '', $host);
return trim($host);
}
Outdated:
This is my translation to bare PHP of a method used in Symfony framework that tries to get the hostname from every way possible in order of best practice:
function get_host() {
if ($host = $_SERVER['HTTP_X_FORWARDED_HOST'])
{
$elements = explode(',', $host);
$host = trim(end($elements));
}
else
{
if (!$host = $_SERVER['HTTP_HOST'])
{
if (!$host = $_SERVER['SERVER_NAME'])
{
$host = !empty($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : '';
}
}
}
// Remove port number from host
$host = preg_replace('/:\d+$/', '', $host);
return trim($host);
}
After trying out ngGrid, ngTable, trNgGrid and Smart Table, I have come to the conclusion that Smart Table is by far the best implementation AngularJS-wise and Bootstrap-wise. It is built exactly the same way as you would build your own, naive table using standard angular. On top of that, they have added a few directives that help you do sorting, filtering etc. Their approach also makes it quite simple to extend yourself. The fact that they use the regular html tags for tables and the standard ng-repeat for the rows and standard bootstrap for formatting makes this my clear winner.
Their JS code depends on angular and your html can depend on bootstrap if you want to. The JS code is 4 kb in total and you can even easily pick stuff out of there if you want to reach an even smaller footprint.
Where the other grids will give you claustrophobia in different areas, Smart Table just feels open and to the point.
If you rely heavily on inline editing and other advanced features, you might get up and running quicker with ngTable for instance. However, you are free to add such features quite easily in Smart Table.
Don't miss Smart Table!!!
I have no relation to Smart Table, except from using it myself.
Static variables are generally considered bad because they represent global state and are therefore much more difficult to reason about. In particular, they break the assumptions of object-oriented programming. In object-oriented programming, each object has its own state, represented by instance (non-static) variables. Static variables represent state across instances which can be much more difficult to unit test. This is mainly because it is more difficult to isolate changes to static variables to a single test.
That being said, it is important to make a distinction between regular static variables (generally considered bad), and final static variables (AKA constants; not so bad).
I think you are looking for this ?
$('#your_id').html('<p>name</p><p><span style="font-size:xx-small;">ajde</span></p><p><em>da</em></p>').text();
That's because the browser doesn't transmit that part to the server, sorry.
A very minimal light weight plugin: vim-commentary.
gcc to comment a line
gcgc to uncomment. check out the plugin page for more.
v+k/j highlight the block then gcc to comment that block.
In Eclipse Project -> Clean Modify project.properties like this :
target=android-10
android.library.reference.1=F:/svn/WiEngine_library
You can clear the input field by using $('#shares').val('');
if you want to execute the statement when number of rows are modified then it can be possible by statement level triggers.. viseversa... when you want to execute your statement each modification on your number of rows then you need to go for row level triggers..
for example: statement level triggers works for when table is modified..then more number of records are effected. and row level triggers works for when each row updation or modification..
If you mean the angle that P1 is the vertex of then using the Law of Cosines should work:
arccos((P122 + P132 - P232) / (2 * P12 * P13))
where P12 is the length of the segment from P1 to P2, calculated by
sqrt((P1x - P2x)2 + (P1y - P2y)2)
Use round()
$float_val = 4.5;
echo round($float_val);
You can also set param for precision and rounding mode, for more info
Update (According to your updated question):
$float_val = 1.0000124668092E+14;
printf('%.0f', $float_val / 1E+14); //Output Rounds Of To 1000012466809201
Alternately, if you have a case where you don't particularly care about the values of the resolved promises when there is one failure but you still want them to have run, you could do something like this which will resolve with the promises as normal when they all succeed and reject with the failed promises when any of them fail:
function promiseNoReallyAll (promises) {
return new Promise(
async (resolve, reject) => {
const failedPromises = []
const successfulPromises = await Promise.all(
promises.map(
promise => promise.catch(error => {
failedPromises.push(error)
})
)
)
if (failedPromises.length) {
reject(failedPromises)
} else {
resolve(successfulPromises)
}
}
)
}
VB 6 provides a Clipboard
object that makes all of this extremely simple and convenient, but unfortunately that's not available from VBA.
If it were me, I'd go the API route. There's no reason to be scared of calling native APIs; the language provides you with the ability to do that for a reason.
However, a simpler alternative is to use the DataObject
class, which is part of the Forms library. I would only recommend going this route if you are already using functionality from the Forms library in your app. Adding a reference to this library only to use the clipboard seems a bit silly.
For example, to place some text on the clipboard, you could use the following code:
Dim clipboard As MSForms.DataObject
Set clipboard = New MSForms.DataObject
clipboard.SetText "A string value"
clipboard.PutInClipboard
Or, to copy text from the clipboard into a string variable:
Dim clipboard As MSForms.DataObject
Dim strContents As String
Set clipboard = New MSForms.DataObject
clipboard.GetFromClipboard
strContents = clipboard.GetText
The split() method is used to split a string into an array of substrings, and returns the new array.
Syntax:
string.split(separator,limit)
arr = strVale.split(',');