I use JarExplorer or JarVisualizer.
I like the viewer of Total Commander because it only loads the text you actually see and so is very fast. Of course, it is just a text/hex viewer, so it won't format your XML, but you can use a basic text search.
An easy solution for most situations: copy/paste the markdown into a viewer in the "cloud." Here are two choices:
Nothing to install! Cross platform! Cross browser! Always available!
Disadvantages: could be hassle for large files, standard cloud application security issues.
You may also be missing using namespace std;
You would need to use an Iterator like so:
Iterator<String> iterator = a.iterator();
while(iterator.hasNext())
{
String value = iterator.next();
if ("abcd".equals(value))
{
iterator.remove();
break;
}
}
That being said, you can use the remove(int index) or remove(Object obj) which are provided by the ArrayList class. Note however, that calling these methods while you are iterating over the loop, will cause a ConcurrentModificationException, so this will not work:
for(String str : a)
{
if (str.equals("acbd")
{
a.remove("abcd");
break;
}
}
But this will (since you are not iterating over the contents of the loop):
a.remove("acbd");
If you have more complex objects you would need to override the equals method.
Angular 2 or 4:
There's no more ng-repeat, it's *ngFor now in recent Angular versions!
<table style="padding: 20px; width: 60%;">
<tr>
<th align="left">id</th>
<th align="left">status</th>
<th align="left">name</th>
</tr>
<tr *ngFor="let item of myJSONArray">
<td>{{item.id}}</td>
<td>{{item.status}}</td>
<td>{{item.name}}</td>
</tr>
</table>
Used this simple JSON:
[{"id":1,"status":"active","name":"A"},
{"id":2,"status":"live","name":"B"},
{"id":3,"status":"active","name":"C"},
{"id":6,"status":"deleted","name":"D"},
{"id":4,"status":"live","name":"E"},
{"id":5,"status":"active","name":"F"}]
re.split(pattern, string[, maxsplit=0])
Split string by the occurrences of pattern. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits occur, and the remainder of the string is returned as the final element of the list. (Incompatibility note: in the original Python 1.5 release, maxsplit was ignored. This has been fixed in later releases.)
>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
If you need to position an element relative to its containing element first you need to add position: relative
to the container element. The child element you want to position relatively to the parent has to have position: absolute
. The way that absolute positioning works is that it is done relative to the first relatively (or absolutely) positioned parent element. In case there is no relatively positioned parent, the element will be positioned relative to the root element (directly to the HTML element).
So if you want to position your child element to the top left of the parent container, you should do this:
.parent {
position: relative;
}
.child {
position: absolute;
top: 0;
left: 0;
}
You will benefit greatly from reading this article. Hope this helps!
Also, you can use bool method(s)
Query :
DataTable tempData = (DataTable)grdUsageRecords.DataSource;
var query = from r in tempData.AsEnumerable()
where isValid(Field<string>("UserName"))// && otherMethod() && otherMethod2()
select r;
DataTable newDT = query.CopyToDataTable();
Method:
bool isValid(string userName)
{
if(userName == "XXXX" || userName == "YYYY")
return false;
else return true;
}
As Dillon Kearns suggested, setting focusable to false works fine. But if your goal is to cancel the keyboard when EditText is clicked, you might want to use:
mEditText.setInputType(0);
You can see the error information from:
Magento/var/report
Most of the time it is cause by broken database connection especially at local server, when one forget to start XAMPP or WAMPP server.
You are looking to see if a single value is in an array. Use in_array
.
However note that case is important, as are any leading or trailing spaces. Use var_dump
to find out the length of the strings too, and see if they fit.
Here is a code example to follow. #thumbnail is a DIV parent of the #handle DIV
buildDraggable = function() {
$( "#handle" ).draggable({
containment: '#thumbnail',
drag: function(event) {
var top = $(this).position().top;
var left = $(this).position().left;
ICZoom.panImage(top, left);
},
});
There is nothing about the languages Fortran and C which makes one faster than the other for specific purposes. There are things about specific compilers for each of these languages which make some favorable for certain tasks more than others.
For many years, Fortran compilers existed which could do black magic to your numeric routines, making many important computations insanely fast. The contemporary C compilers couldn't do it as well. As a result, a number of great libraries of code grew in Fortran. If you want to use these well tested, mature, wonderful libraries, you break out the Fortran compiler.
My informal observations show that these days people code their heavy computational stuff in any old language, and if it takes a while they find time on some cheap compute cluster. Moore's Law makes fools of us all.
You can use GPO to use the certificate within the domain.
But my problem is with Internet Explorer 8, that even with the certificate in the trusted root certification store... it still won't say it's a trusted site.
With this and the driver signing that needs to be done now... I'm starting to wonder who owns my computer!
As stated above, the simple answer is:
date = input(monyy,date9.);
with the addition of:
put date=yymmdd.;
The reason why this works, and what you did doesn't, is because of a common misunderstanding in SAS. DATE9. is an INFORMAT. In an INPUT statement, it provides the SAS interpreter with a set of translation commands it can send to the compiler to turn your text into the right numbers, which will then look like a date once the right FORMAT is applied. FORMATs are just visible representations of numbers (or characters). So by using YYMMDD., you confused the INPUT function by handing it a FORMAT instead of an INFORMAT, and probably got a helpful error that said:
Invalid argument to INPUT function at line... etc...
Which told you absolutely nothing about what to do next.
In summary, to represent your character date as a YYMMDD. In SAS you need to:
date = input(monyy,date9.);
put date=YYMMDD10.;
as above, but qualitatively:
private - least access, best encapsulation
protected - some access, moderate encapsulation
public - full access, no encapsulation
the less access you provide the fewer implementation details leak out of your objects. less of this sort of leakage means more flexibility (aka "looser coupling") in terms of changing how an object is implemented without breaking clients of the object. this is a truly fundamental thing to understand.
In my PyCharm 2019.3, select the project, then File ---> Settings, then Project: YourProjectName, in 'Project Interpreter', click the interpreter or settings, ---> Show all... ---> Select the current interpreter ---> Show paths for the selected interpreter ---> then click 'Add' to add your library, in my case, it is a wheel package
It looks like you are using a custom Kubernetes Cluster (using minikube
, kubeadm
or the like). In this case, there is no LoadBalancer integrated (unlike AWS or Google Cloud). With this default setup, you can only use NodePort
or an Ingress Controller.
With the Ingress Controller you can setup a domain name which maps to your pod; you don't need to give your Service the LoadBalancer
type if you use an Ingress Controller.
May be below approach will be helpful for someone TS with reactjs
interface Event {
name: string;
dateCreated: string;
type: string;
}
interface UserEvent<T> extends Event<T> {
UserId: string;
}
Maybe it is not quite as elegant, but the following might also work. I suspect asynchronously this would not be a good solution.
$p = Start-Process myjob.bat -redirectstandardoutput $logtempfile -redirecterroroutput $logtempfile -wait
add-content $logfile (get-content $logtempfile)
If you want to continue exactly one Docker container with a known name:
docker start `docker ps -a -q --filter "name=elas"`
Use CHAR_LENGTH() instead-of LENGTH() as suggested in: MySQL - length() vs char_length()
SELECT name, CHAR_LENGTH(name) AS mlen FROM mytable ORDER BY mlen DESC LIMIT 1
Simple. In the print, do:
print(foobar.__dict__)
as long as the constructor is
__init__
Very simple: no color, no opacity:
rgba(0, 0, 0, 0);
@RequestMapping("/api/status")
public Map doSomething()
{
return Collections.singletonMap("status", myService.doSomething());
}
PS. Works only for 1 value
None of the solutions were working correctly for me on Chrome in iOS 12 and most of them are not tailored to cope with possible multiple date inputs on a page. I did the following, which basically creates a fake label over the date input and removes it on tap. I am also removing the fake label if viewport width is beyond 992px.
JS:
function addMobileDatePlaceholder() {
if (window.matchMedia("(min-width: 992px)").matches) {
$('input[type="date"]').next("span.date-label").remove();
return false;
}
$('input[type="date"]').after('<span class="date-label" />');
$('span.date-label').each(function() {
var $placeholderText = $(this).prev('input[type="date"]').attr('placeholder');
$(this).text($placeholderText);
});
$('input[type="date"]').on("click", function() {
$(this).next("span.date-label").remove();
});
}
CSS:
@media (max-width: 991px) {
input[type="date"] {
padding-left: calc(50% - 45px);
}
span.date-label {
pointer-events: none;
position: absolute;
top: 2px;
left: 50%;
transform: translateX(-50%);
text-align: center;
height: 27px;
width: 70%;
padding-top: 5px;
}
}
To be able to use the jobParameters I think you need to define your reader as scope 'step', but I am not sure if you can do it using annotations.
Using xml-config it would go like this:
<bean id="foo-readers" scope="step"
class="...MyReader">
<property name="fileName" value="#{jobExecutionContext['fileName']}" />
</bean>
See further at the Spring Batch documentation.
Perhaps it works by using @Scope
and defining the step scope in your xml-config:
<bean class="org.springframework.batch.core.scope.StepScope" />
This will show only Cart Items Count.
global $woocommerce;
echo $woocommerce->cart->cart_contents_count;
You can use NOW()
:
INSERT INTO servers (server_name, online_status, exchange, disk_space, network_shares, c_time)
VALUES('m1', 'ONLINE', 'exchange', 'disk_space', 'network_shares', NOW())
If array is static allocated:
size_t size = sizeof(arr) / sizeof(int);
if array is dynamic allocated(heap):
int *arr = malloc(sizeof(int) * size);
where variable size is a dimension of the arr.
EF Core 2.1+ :
Property:
public string[] Strings { get; set; }
OnModelCreating:
modelBuilder.Entity<YourEntity>()
.Property(e => e.Strings)
.HasConversion(
v => string.Join(',', v),
v => v.Split(',', StringSplitOptions.RemoveEmptyEntries));
The PostgreSQL has an array data type and the Npgsql EF Core provider does support that. So it will map your C# arrays and lists to the PostgreSQL array data type automatically and no extra config is required. Also you can operate on the array and the operation will be translated to SQL.
More information on this page.
File extensions do not have any bearing or impact on the content of the file. You can hold YAML content in files with any extension: .yml
, .yaml
or indeed anything else.
The (rather sparse) YAML FAQ recommends that you use .yaml
in preference to .yml
, but for historic reasons many Windows programmers are still scared of using extensions with more than three characters and so opt to use .yml
instead.
So, what really matters is what is inside the file, rather than what its extension is.
Compilating answers here and there, here's a complete set of arr tools to get the work done:
Function getArraySize(arr As Variant)
' returns array size for a n dimention array
' usage result(k) = size of the k-th dimension
Dim ndims As Long
Dim arrsize() As Variant
ndims = getDimensions(arr)
ReDim arrsize(ndims - 1)
For i = 1 To ndims
arrsize(i - 1) = getDimSize(arr, i)
Next i
getArraySize = arrsize
End Function
Function getDimSize(arr As Variant, dimension As Integer)
' returns size for the given dimension number
getDimSize = UBound(arr, dimension) - LBound(arr, dimension) + 1
End Function
Function getDimensions(arr As Variant) As Long
' returns number of dimension in an array (ex. sheet range = 2 dimensions)
On Error GoTo Err
Dim i As Long
Dim tmp As Long
i = 0
Do While True
i = i + 1
tmp = UBound(arr, i)
Loop
Err:
getDimensions = i - 1
End Function
console.log( 'You are running jQuery version: ' + $.fn.jquery );
var strcmp = new Intl.Collator(undefined, {numeric:true, sensitivity:'base'}).compare;
Usage: strcmp(string1, string2)
Result: 1
means string1 is bigger, 0
means equal, -1
means string2 is bigger.
This has higher performance than String.prototype.localeCompare
Also, numeric:true
makes it do logical number comparison
If you are working a lot with graphs and ggplot, you might be tired to add the theme() each time. If you don't want to change the default theme as suggested earlier, you may find easier to create your own personal theme.
personal_theme = theme(plot.title =
element_text(hjust = 0.5))
Say you have multiple graphs, p1, p2 and p3, just add personal_theme to them.
p1 + personal_theme
p2 + personal_theme
p3 + personal_theme
dat <- data.frame(
time = factor(c("Lunch","Dinner"),
levels=c("Lunch","Dinner")),
total_bill = c(14.89, 17.23)
)
p1 = ggplot(data=dat, aes(x=time, y=total_bill,
fill=time)) +
geom_bar(colour="black", fill="#DD8888",
width=.8, stat="identity") +
guides(fill=FALSE) +
xlab("Time of day") + ylab("Total bill") +
ggtitle("Average bill for 2 people")
p1 + personal_theme
The data-reactid
attribute is a custom attribute used so that React can uniquely identify its components within the DOM.
This is important because React applications can be rendered at the server as well as the client. Internally React builds up a representation of references to the DOM nodes that make up your application (simplified version is below).
{
id: '.1oqi7occu80',
node: DivRef,
children: [
{
id: '.1oqi7occu80.0',
node: SpanRef,
children: [
{
id: '.1oqi7occu80.0.0',
node: InputRef,
children: []
}
]
}
]
}
There's no way to share the actual object references between the server and the client and sending a serialized version of the entire component tree is potentially expensive. When the application is rendered at the server and React is loaded at the client, the only data it has are the data-reactid
attributes.
<div data-reactid='.loqi70ccu80'>
<span data-reactid='.loqi70ccu80.0'>
<input data-reactid='.loqi70ccu80.0' />
</span>
</div>
It needs to be able to convert that back into the data structure above. The way it does that is with the unique data-reactid
attributes. This is called inflating the component tree.
You might also notice that if React renders at the client-side, it uses the data-reactid
attribute, even though it doesn't need to lose its references. In some browsers, it inserts your application into the DOM using .innerHTML
then it inflates the component tree straight away, as a performance boost.
The other interesting difference is that client-side rendered React ids will have an incremental integer format (like .0.1.4.3
), whereas server-rendered ones will be prefixed with a random string (such as .loqi70ccu80.1.4.3
). This is because the application might be rendered across multiple servers and it's important that there are no collisions. At the client-side, there is only one rendering process, which means counters can be used to ensure unique ids.
React 15 uses document.createElement
instead, so client rendered markup won't include these attributes anymore.
A workaround - at least for the minimum size: You can use grid to manage the frames contained in root and make them follow the grid size by setting sticky='nsew'. Then you can use root.grid_rowconfigure and root.grid_columnconfigure to set values for minsize like so:
from tkinter import Frame, Tk
class MyApp():
def __init__(self):
self.root = Tk()
self.my_frame_red = Frame(self.root, bg='red')
self.my_frame_red.grid(row=0, column=0, sticky='nsew')
self.my_frame_blue = Frame(self.root, bg='blue')
self.my_frame_blue.grid(row=0, column=1, sticky='nsew')
self.root.grid_rowconfigure(0, minsize=200, weight=1)
self.root.grid_columnconfigure(0, minsize=200, weight=1)
self.root.grid_columnconfigure(1, weight=1)
self.root.mainloop()
if __name__ == '__main__':
app = MyApp()
But as Brian wrote (in 2010 :D) you can still resize the window to be smaller than the frame if you don't limit its minsize.
Try this code to ensure you have a spacing of 5px between each item:
- (UIEdgeInsets)collectionView:(UICollectionView *) collectionView
layout:(UICollectionViewLayout *) collectionViewLayout
insetForSectionAtIndex:(NSInteger) section {
return UIEdgeInsetsMake(0, 0, 0, 5); // top, left, bottom, right
}
- (CGFloat)collectionView:(UICollectionView *) collectionView
layout:(UICollectionViewLayout *) collectionViewLayout
minimumInteritemSpacingForSectionAtIndex:(NSInteger) section {
return 5.0;
}
Why just don't do like this?:
if ($res) {
$converted_res = "true";
}
else {
$converted_res = "false";
}
You can use XDocument.Parse
for this.
Try This
this example is one directory back
require_once('../images/yourimg.png');
this example is two directory back
require_once('../../images/yourimg.png');
More general sorted, where the key
keyword defines the sorting method, minus before numerical type indicates descending:
>>> x = Counter({'a':5, 'b':3, 'c':7})
>>> sorted(x.items(), key=lambda k: -k[1]) # Ascending
[('c', 7), ('a', 5), ('b', 3)]
Here's a compact version of using applymap
with a straightforward lambda expression to call strip
only when the value is of a string type:
df.applymap(lambda x: x.strip() if isinstance(x, str) else x)
A more complete example:
import pandas as pd
def trim_all_columns(df):
"""
Trim whitespace from ends of each value across all series in dataframe
"""
trim_strings = lambda x: x.strip() if isinstance(x, str) else x
return df.applymap(trim_strings)
# simple example of trimming whitespace from data elements
df = pd.DataFrame([[' a ', 10], [' c ', 5]])
df = trim_all_columns(df)
print(df)
>>>
0 1
0 a 10
1 c 5
Here's a working example hosted by trinket: https://trinket.io/python3/e6ab7fb4ab
Assuming this is what the HTML looks like
<div class="form-group required">
<label class="col-md-2 control-label">E-mail</label>
<div class="col-md-4"><input class="form-control" id="id_email" name="email" placeholder="E-mail" required="required" title="" type="email" /></div>
</div>
To display an asterisk on the right of the label:
.form-group.required .control-label:after {
color: #d00;
content: "*";
position: absolute;
margin-left: 8px;
top:7px;
}
Or to the left of the label:
.form-group.required .control-label:before{
color: red;
content: "*";
position: absolute;
margin-left: -15px;
}
To make a nice big red asterisks you can add these lines:
font-family: 'Glyphicons Halflings';
font-weight: normal;
font-size: 14px;
Or if you are using Font Awesome add these lines (and change the content line):
font-family: 'FontAwesome';
font-weight: normal;
font-size: 14px;
content: "\f069";
Yes.You can try with some hidden params.
$("#form").submit( function(eventObj) {
$("<input />").attr("type", "hidden")
.attr("name", "something")
.attr("value", "something")
.appendTo("#form");
return true;
});
Add style="width:100%; height:100%;"
to the div see what that does
not to the #map_canvas
but the main div
example
<body>
<div style="height:100%; width:100%;">
<div id="map-canvas"></div>
</div>
</body>
There are some other answers on here the explain why this is necessary
If you only care about html5 browsers you can use error event (since this is only for error handling, it should be ok to only support this on next gen browsers for KISS IMHO).
From the spec:
If the src attribute's value is the empty string or if it could not be resolved, then the user agent must queue a task to fire a simple event named error at the element, and abort these steps.
~
If the load resulted in an error (for example a DNS error, or an HTTP 404 error) Executing the script block must just consist of firing a simple event named error at the element.
This means you don't have to do any error prone polling and can combine it with async and defer attribute to make sure the script is not blocking page rendering:
The defer attribute may be specified even if the async attribute is specified, to cause legacy Web browsers that only support defer (and not async) to fall back to the defer behavior instead of the synchronous blocking behavior that is the default.
With countries, languages or currency you may use emojis.
Works with pretty much every browser/OS that supports the use of emojis.
select {_x000D_
height: 50px;_x000D_
line-height: 50px;_x000D_
font-size: 12pt;_x000D_
}
_x000D_
<select name="countries">_x000D_
<option value="NL"> Netherlands</option>_x000D_
<option value="DE"> Germany</option>_x000D_
<option value="FR"> France</option>_x000D_
<option value="ES"> Spain</option>_x000D_
</select>_x000D_
_x000D_
<br /><br />_x000D_
_x000D_
<select name="currency">_x000D_
<option value="EUR"> € EUR </option>_x000D_
<option value="GBP"> £ GBP </option>_x000D_
<option value="USD"> $ USD </option>_x000D_
<option value="YEN"> ¥ YEN </option>_x000D_
</select>
_x000D_
You can also add a file handler or rotating file handler to send your logs to a local file: http://docs.python.org/2/library/logging.handlers.html
The accepted solution only works on arrays, but not objects or associative arrays. Unfortunately, since Angular depends on the JavaScript implementation of array enumeration, the order of object properties cannot be consistently controlled. Some browsers may iterate through object properties lexicographically, but this cannot be guaranteed.
e.g. Given the following assignment:
$scope.cards = {
"card2": {
values: {
opt1: 9,
opt2: 12
}
},
"card1": {
values: {
opt1: 9,
opt2: 11
}
}
};
and the directive <ul ng-repeat="(key, card) in cards | orderBy:myValueFunction">
, ng-repeat may iterate over "card1" prior to "card2", regardless of sort order.
To workaround this, we can create a custom filter to convert the object to an array, and then apply a custom sort function before returning the collection.
myApp.filter('orderByValue', function () {
// custom value function for sorting
function myValueFunction(card) {
return card.values.opt1 + card.values.opt2;
}
return function (obj) {
var array = [];
Object.keys(obj).forEach(function (key) {
// inject key into each object so we can refer to it from the template
obj[key].name = key;
array.push(obj[key]);
});
// apply a custom sorting function
array.sort(function (a, b) {
return myValueFunction(b) - myValueFunction(a);
});
return array;
};
});
We cannot iterate over (key, value) pairings in conjunction with custom filters (since the keys for arrays are numerical indexes), so the template should be updated to reference the injected key names.
<ul ng-repeat="card in cards | orderByValue">
<li>{{card.name}} {{value(card)}}</li>
</ul>
Here is a working fiddle utilizing a custom filter on an associative array: http://jsfiddle.net/av1mLpqx/1/
Reference: https://github.com/angular/angular.js/issues/1286#issuecomment-22193332
To improve on Ryan's answer:
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)size {
CGFloat oldWidth = image.size.width;
CGFloat oldHeight = image.size.height;
//You may need to take some retina adjustments into consideration here
CGFloat scaleFactor = (oldWidth > oldHeight) ? width / oldWidth : height / oldHeight;
return [UIImage imageWithCGImage:image.CGImage scale:scaleFactor orientation:UIImageOrientationUp];
}
import pandas as pd
Date_Time = pd.to_datetime(df.NameOfColumn, unit='ms')
Spotlight.js is a great library for iterating over the window object and other host objects looking for certain things.
// find all "length" properties
spotlight.byName('length');
// or find all "map" properties on jQuery
spotlight.byName('map', { 'object': jQuery, 'path': '$' });
// or all properties with `RegExp` values
spotlight.byKind('RegExp');
// or all properties containing "oo" in their name
spotlight.custom(function(value, key) { return key.indexOf('oo') > -1; });
You'll like it for this.
YES!....always style textarea using CSS and avoid the attributes, unless you need to support some very old agent that does not support style sheets. Otherwise, you have full power to use CSS. Below is my default CSS formatting for textarea that looks beautiful in any website. Customize it as you like. Comments are included below so you can see why I chose those CSS properties and values:
textarea {
display: inline-block;
margin: 0;
padding: .2em;
width: auto;
min-width: 30em;
/* The max-width "100%" value fixes a weird issue where width is too wide by default and extends beyond 100% of the parent in some agents. */
max-width: 100%;
/* Height "auto" will allow the text area to expand vertically in size with a horizontal scrollbar if pre-existing content is added to the box before rendering. Remove this if you want a pre-set height. Use "em" to match the font size set in the website. */
height: auto;
/* Use "em" to define the height based on the text size set in your website and the text rows in the box, not a static pixel value. */
min-height: 10em;
/* Do not use "border" in textareas unless you want to remove the 3D box most browsers assign and flatten the box design. */
/*border: 1px solid black;*/
cursor: text;
/* Some textareas have a light gray background by default anyway. */
background-color: #eee;
/* Overflow "auto" allows the box to start with no scrollbars but add them as content fills the box. */
overflow: auto;
/* Resize creates a tab in the lower right corner of textarea for most modern browsers and allows users to resize the box manually. Note: Resize isn't supported by most older agents and IE. */
resize: both;
}
In my "reset" element style sheet I set these values as defaults for "textarea" by default, which give all your textareas a nice look and feel with scrolling when detected, a resizing tab (non-IE browsers), and fixes for dimensions, including a height that allows the box to size itself based on existing content you put in it for the user and a width that does not break out beyond its parent containers limitations.
The simplest approach would simply generate a random number between 0 and the difference of the two numbers. Then add the smaller of the two numbers to the result.
You Must use
-(void)viewWillAppear:(BOOL)animated
and set your entries like you want...
There are significant differences. Let's set up some test cases:
var unused; // value will be undefined
Test("test1", "some value");
Test("test2");
Test("test3", unused);
Test("test4", null);
Test("test5", 0);
Test("test6", "");
With the first method you describe, only the second test will use the default value. The second method will default all but the first (as JS will convert undefined
, null
, 0
, and ""
into the boolean false
. And if you were to use Tom's method, only the fourth test will use the default!
Which method you choose really depends on your intended behavior. If values other than undefined
are allowable for argument2
, then you'll probably want some variation on the first; if a non-zero, non-null, non-empty value is desired, then the second method is ideal - indeed, it is often used to quickly eliminate such a wide range of values from consideration.
The best way to get good control over the colorbar position is to give it its own axis. Like so:
# What I imagine your plotting looks like so far
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(your_data)
# Now adding the colorbar
cbaxes = fig.add_axes([0.8, 0.1, 0.03, 0.8])
cb = plt.colorbar(ax1, cax = cbaxes)
The numbers in the square brackets of add_axes refer to [left, bottom, width, height], where the coordinates are just fractions that go from 0 to 1 of the plotting area.
You can aliasing both query and Selecting them in the select query
http://sqlfiddle.com/#!2/ca27b/1
SELECT x.a, y.b FROM (SELECT * from a) as x, (SELECT * FROM b) as y
This is nowhere definied in the JDBC API contract, but if you're lucky, the JDBC driver in question may return the complete SQL by just calling PreparedStatement#toString()
. I.e.
System.out.println(preparedStatement);
To my experience, the ones which do so are at least the PostgreSQL 8.x and MySQL 5.x JDBC drivers. For the case your JDBC driver doesn't support it, your best bet is using a statement wrapper which logs all setXxx()
methods and finally populates a SQL string on toString()
based on the logged information. For example Log4jdbc or P6Spy.
If they are in the same controller class, it would be:
foreach ( $characters as $character) {
$num += $this->getFactorial($index) * $index;
$index ++;
}
Otherwise you need to create a new instance of the class, and call the method, ie:
$controller = new MyController();
foreach ( $characters as $character) {
$num += $controller->getFactorial($index) * $index;
$index ++;
}
PUT = replace the ENTIRE RESOURCE with the new representation provided
PATCH = replace parts of the source resource with the values provided AND|OR other parts of the resource are updated that you havent provided (timestamps) AND|OR updating the resource effects other resources (relationships)
I'm on rails 5.2, and trying to rename a column on a devise User.
the rename_column
bit worked for me, but the singular :table_name
threw a "User table not found" error. Plural worked for me.
rails g RenameAgentinUser
Then change migration file to this:
rename_column :users, :agent?, :agent
Where :agent? is the old column name.
Int nullable to int conversion can be done like so:
v2=(int)v1;
You can apply Object.prototype.toString
to any object:
var toString = Object.prototype.toString;
console.log(toString.call([]));
//-> [object Array]
console.log(toString.call(/reg/g));
//-> [object RegExp]
console.log(toString.call({}));
//-> [object Object]
This works well in all browsers, with the exception of IE - when calling this on a variable obtained from another window it will just spit out [object Object]
.
I was needed to solve absolutely the same task. I have divided visually the table using different background colors for different parts. Googling the Internet I've found this page https://support.microsoft.com/kb/2815384. Unfortunately it doesn't solve the issue because ColorIndex refers to some unpredictable value, so if some cells have nuances of one color (for example different values of brightness of the color), the suggested function counts them. The solution below is my fix:
Function CountBgColor(range As range, criteria As range) As Long
Dim cell As range
Dim color As Long
color = criteria.Interior.color
For Each cell In range
If cell.Interior.color = color Then
CountBgColor = CountBgColor + 1
End If
Next cell
End Function
Try this -->
new DzieckoAndOpiekun(
p.Imie,
p.Nazwisko,
p.Opiekun.Imie,
p.Opiekun.Nazwisko).ToList()
The MySQL server can be started manually from the command line. This can be done on any version of Windows.
To start the mysqld server from the command line, you should start a console window (or “DOS window”) and enter this command:
shell> "C:\Program Files\MySQL\MySQL Server 5.0\bin\mysqld"
The path to mysqld may vary depending on the install location of MySQL on your system.
You can stop the MySQL server by executing this command:
shell> "C:\Program Files\MySQL\MySQL Server 5.0\bin\mysqladmin" -u root shutdown
**Note : **
If the MySQL root user account has a password, you need to invoke mysqladmin with the -p option and supply the password when prompted.
This command invokes the MySQL administrative utility mysqladmin to connect to the server and tell it to shut down. The command connects as the MySQL root user, which is the default administrative account in the MySQL grant system. Note that users in the MySQL grant system are wholly independent from any login users under Windows.
If mysqld doesn't start, check the error log to see whether the server wrote any messages there to indicate the cause of the problem. The error log is located in the C:\Program Files\MySQL\MySQL Server 5.0\data directory. It is the file with a suffix of .err. You can also try to start the server as mysqld --console; in this case, you may get some useful information on the screen that may help solve the problem.
The last option is to start mysqld with the --standalone and --debug options. In this case, mysqld writes a log file C:\mysqld.trace that should contain the reason why mysqld doesn't start. See MySQL Internals: Porting to Other Systems.
The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:
ffmpeg -i input.mov -qscale 0 output.mp4
Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0
):
ffmpeg -i input.mov -q:v 0 output.mp4
I had the exact same problem, with my configuration files correct. In my case the issue comes from the Eduroam wifi I used : when I connect via another wifi everything works. It seems that Eduroam blocks port 5432, at least in my university.
For some reason I was not able to use my scalar function until I referenced it using brackets, like so:
select [dbo].[fun_functional_score]('01091400003')
Use media queries. Your CSS code would be:
@media screen and (max-width: 1024px) {
.yourClass {
display: none !important;
}
}
newVariable = originalVariable.valueOf();
for objects you can use,
b = Object.assign({},a);
I'd do this one of two ways. Since you're setting your start and end dates in your t-sql code, i wouldn't ask for parameters in the stored proc
Option 1
Create Procedure [Test] AS
DECLARE @StartDate varchar(10)
DECLARE @EndDate varchar(10)
Set @StartDate = '201620' --Define start YearWeek
Set @EndDate = (SELECT CAST(DATEPART(YEAR,getdate()) AS varchar(4)) + CAST(DATEPART(WEEK,getdate())-1 AS varchar(2)))
SELECT
*
FROM
(SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)
Option 2
Create Procedure [Test] @StartDate varchar(10),@EndDate varchar(10) AS
SELECT
*
FROM
(SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)
Then run exec test '2016-01-01','2016-01-25'
You can use React-Bootstrap (https://react-bootstrap.github.io/components/modal). There is an example for modals at that link. Once you have loaded react-bootstrap, the modal component can be used as a react component:
var Modal = ReactBootstrap.Modal;
can then be used as a react component as
<Modal/>
.
For Bootstrap 4, there is react-strap (https://reactstrap.github.io). React-Bootstrap only supports Bootstrap 3.
The properties on the style
object are only the styles applied directly to the element (e.g., via a style
attribute or in code). So .style.marginTop
will only have something in it if you have something specifically assigned to that element (not assigned via a style sheet, etc.).
To get the current calculated style of the object, you use either the currentStyle
property (Microsoft) or the getComputedStyle
function (pretty much everyone else).
Example:
var p = document.getElementById("target");
var style = p.currentStyle || window.getComputedStyle(p);
display("Current marginTop: " + style.marginTop);
Fair warning: What you get back may not be in pixels. For instance, if I run the above on a p
element in IE9, I get back "1em"
.
I have catched the same exception and found a InnerException: SocketException.
in the svclog trace.
After looking in the windows event log I saw an error coming from the System.ServiceModel.Activation.TcpWorkerProcess
class.
Are you hosting your wcf service in IIS with netTcpBinding and port sharing?
It seems there is a bug in IIS port sharing feature, check the fix:
My solution is to host your WCF service in a Windows Service.
There's the plotrix package with has a built-in function for this: std.error
Thanks to this question. I wanted the exact opposite, i.e a hidden div should still occupy its space on the browser. So, I used visibility: hidden
instead of display: none
.
If you need to stay on Xcode 11.4, try this:
xcodes
for example);/Applications/Xcode-11.5.0.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/13.5
to /Applications/Xcode-11.4.1.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/13.5
;You should now be able to run your app on iOS 13.5 with Xcode 11.4.
Try converting your procedure in to an Inline Function which returns a table as follows:
CREATE FUNCTION MyProc()
RETURNS TABLE AS
RETURN (SELECT * FROM MyTable)
And then you can call it as
SELECT * FROM MyProc()
You also have the option of passing parameters to the function as follows:
CREATE FUNCTION FuncName (@para1 para1_type, @para2 para2_type , ... )
And call it
SELECT * FROM FuncName ( @para1 , @para2 )
I had the same problem and tried all of the above without any success, then I found out what it was:
I'd created a folder called "System" in one of my projects and then created a class in it. The problem seems to stem from having a namespace called "System" when the .cs file is created, even if it is in a namespace of "MyProject.System".
Looking back I can understand why this would cause problems. It really stumped me at first as the error messages don't initially seem to relate to the problem.
In Preferences->Text Editing-> Show: Line numbers you can enable the line numbers on the left hand side of the file.
Please check my working code.
function sendMail()
{
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => 465,
'smtp_user' => '[email protected]', // change it to yours
'smtp_pass' => 'xxx', // change it to yours
'mailtype' => 'html',
'charset' => 'iso-8859-1',
'wordwrap' => TRUE
);
$message = '';
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->email->from('[email protected]'); // change it to yours
$this->email->to('[email protected]');// change it to yours
$this->email->subject('Resume from JobsBuddy for your Job posting');
$this->email->message($message);
if($this->email->send())
{
echo 'Email sent.';
}
else
{
show_error($this->email->print_debugger());
}
}
in my case, some characters like " , :"'{}[] " maybe corrupt the JSON format, so use try json.loads(str) except to check your input
On Linux:
Use /usr/bin/time -v <program> <args>
and look for "Maximum resident set size".
(Not to be confused with the Bash time
built-in command! So use the full path, /usr/bin/time
)
For example:
> /usr/bin/time -v ./myapp
User time (seconds): 0.00
. . .
Maximum resident set size (kbytes): 2792
. . .
On BSD, MacOS:
Use /usr/bin/time -l <program> <args>
, looking for "maximum resident set size":
>/usr/bin/time -l ./myapp
0.01 real 0.00 user 0.00 sys
1440 maximum resident set size
. . .
An easy solution which avoids looping over the ticklabes is to just use
This command automatically rotates the xaxis labels and adjusts their position. The default values are a rotation angle 30° and horizontal alignment "right". But they can be changed in the function call
fig.autofmt_xdate(bottom=0.2, rotation=30, ha='right')
The additional bottom
argument is equivalent to setting plt.subplots_adjust(bottom=bottom)
, which allows to set the bottom axes padding to a larger value to host the rotated ticklabels.
So basically here you have all the settings you need to have a nice date axis in a single command.
A good example can be found on the matplotlib page.
With the parentheses:
setTimeout("alertMsg()", 3000); // It work, here it treat as a function
Without the quotes and the parentheses:
setTimeout(alertMsg, 3000); // It also work, here it treat as a function
And the third is only using quotes:
setTimeout("alertMsg", 3000); // It not work, here it treat as a string
function alertMsg1() {_x000D_
alert("message 1");_x000D_
}_x000D_
function alertMsg2() {_x000D_
alert("message 2");_x000D_
}_x000D_
function alertMsg3() {_x000D_
alert("message 3");_x000D_
}_x000D_
function alertMsg4() {_x000D_
alert("message 4");_x000D_
}_x000D_
_x000D_
// this work after 2 second_x000D_
setTimeout(alertMsg1, 2000);_x000D_
_x000D_
// This work immediately_x000D_
setTimeout(alertMsg2(), 4000);_x000D_
_x000D_
// this fail_x000D_
setTimeout('alertMsg3', 6000);_x000D_
_x000D_
// this work after 8second_x000D_
setTimeout('alertMsg4()', 8000);
_x000D_
In the above example first alertMsg2() function call immediately (we give the time out 4S but it don't bother) after that alertMsg1() (A time wait of 2 Second) then alertMsg4() (A time wait of 8 Second) but the alertMsg3() is not working because we place it within the quotes without parties so it is treated as a string.
Okay, but you all know that the * is a wildcard and allows cross site scripting from every domain?
You would like to send multiple Access-Control-Allow-Origin
headers for every site that's allowed to - but unfortunately its officially not supported to send multiple Access-Control-Allow-Origin
headers, or to put in multiple origins.
You can solve this by checking the origin, and sending back that one in the header, if it is allowed:
$origin = $_SERVER['HTTP_ORIGIN'];
$allowed_domains = [
'http://mysite1.com',
'https://www.mysite2.com',
'http://www.mysite2.com',
];
if (in_array($origin, $allowed_domains)) {
header('Access-Control-Allow-Origin: ' . $origin);
}
Thats much safer. You might want to edit the matching and change it to a manual function with some regex, or something like that. At least this will only send back 1 header, and you will be sure its the one that the request came from. Please do note that all HTTP headers can be spoofed, but this header is for the client's protection. Don't protect your own data with those values. If you want to know more, read up a bit on CORS and CSRF.
Why is it safer?
Allowing access from other locations then your own trusted site allows for session highjacking. I'm going to go with a little example - image Facebook allows a wildcard origin - this means that you can make your own website somewhere, and make it fire AJAX calls (or open iframes) to facebook. This means you can grab the logged in info of the facebook of a visitor of your website. Even worse - you can script POST
requests and post data on someone's facebook - just while they are browsing your website.
Be very cautious when using the ACAO
headers!
just clean and make project / rebuilt fixed my issue give a try :-)
It's not difficult as we thing. Just create a frame for UIButton with clear background color, assign action for the button and place over the navigationbar back button. And finally remove the button after use.
Here is the Swift 3 sample code done with UIImage instead of UIButton
override func viewDidLoad() {
super.viewDidLoad()
let imageView = UIImageView()
imageView.backgroundColor = UIColor.clear
imageView.frame = CGRect(x:0,y:0,width:2*(self.navigationController?.navigationBar.bounds.height)!,height:(self.navigationController?.navigationBar.bounds.height)!)
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(back(sender:)))
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(tapGestureRecognizer)
imageView.tag = 1
self.navigationController?.navigationBar.addSubview(imageView)
}
write the code need to be executed
func back(sender: UIBarButtonItem) {
// Perform your custom actions}
_ = self.navigationController?.popViewController(animated: true)
}
Remove the subView after action is performed
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
for view in (self.navigationController?.navigationBar.subviews)!{
if view.tag == 1 {
view.removeFromSuperview()
}
}
ABSTRACTION:"A view of a problem that extracts the essential information relevant to a particular purpose and ignores the remainder of the information."[IEEE, 1983]
ENCAPSULATION: "Encapsulation or equivalently information hiding refers to the practice of including within an object everything it needs, and furthermore doing this in such a way that no other object need ever be aware of this internal structure."
Do you mean you want to use a formula in VBA? Something like:
Dim iVal As Integer
iVal = Application.WorksheetFunction.COUNTIF(Range("A1:A10"),"Green")
should work.
If this question is from the interviewer then please DONT USE SORTING Technique or Don't use any built in methods like Arrays.sort or Collection.sort. The purpose of this questions is how optimal your solution is in terms of performance so the best option would be just implement with your own logic with O(n-1) implementation. The below code is strictly for beginners and not for experienced guys.
public void printLargest(){
int num[] ={ 900,90,6,7,5000,4,60000,20,3};
int largest = num[0];
int secondLargest = num[1];
for (int i=1; i<num.length; i++)
{
if(largest < num[i])
{
secondLargest = largest;
largest = num[i];
}
else if(secondLargest < num[i]){
secondLargest = num[i];
}
}
System.out.println("Largest : " +largest);
System.out.println("Second Largest : "+secondLargest);
}
The native Python way for asynchronous calls in 2021 with Python 3.9 suitable also for Jupyter / Ipython Kernel
Camabeh's answer is the way to go since Python 3.3.
async def display_date(loop): end_time = loop.time() + 5.0 while True: print(datetime.datetime.now()) if (loop.time() + 1.0) >= end_time: break await asyncio.sleep(1) loop = asyncio.get_event_loop() # Blocking call which returns when the display_date() coroutine is done loop.run_until_complete(display_date(loop)) loop.close()
This will work in Jupyter Notebook / Jupyter Lab but throw an error:
RuntimeError: This event loop is already running
Due to Ipython's usage of event loops we need something called nested asynchronous loops which is not yet implemented in Python. Luckily there is nest_asyncio to deal with the issue. All you need to do is:
!pip install nest_asyncio # use ! within Jupyter Notebook, else pip install in shell
import nest_asyncio
nest_asyncio.apply()
(Based on this thread)
Only when you call loop.close()
it throws another error as it probably refers to Ipython's main loop.
RuntimeError: Cannot close a running event loop
I'll update this answer as soon as someone answered to this github issue.
In your form are you passing in any other attributes, via mass assignment that don't belong to your user model, or any of the nested models?
If so, I believe the ActiveRecord::UnknownAttributeError is triggered in this instance.
Otherwise, I think you can just create your own controller, by generating something like this:
# app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
def new
super
end
def create
# add custom create logic here
end
def update
super
end
end
And then tell devise to use that controller instead of the default with:
# app/config/routes.rb
devise_for :users, :controllers => {:registrations => "registrations"}
For anyone with this situation: I saw this error when I accidentally used my_first_scope::my_second_scope::true
in place of simply true
, like this:
bool my_var = my_first_scope::my_second_scope::true;
instead of:
bool my_var = true;
This is because I had a macro which caused MY_MACRO(true)
to expand into my_first_scope::my_second_scope::true
, by mistake, and I was actually calling bool my_var = MY_MACRO(true);
.
Here's a quick demo of this type of scoping error:
Program (you can run it online here: https://onlinegdb.com/BkhFBoqUw):
#include <iostream>
#include <cstdio>
namespace my_first_scope
{
namespace my_second_scope
{
} // namespace my_second_scope
} // namespace my_first_scope
int main()
{
printf("Hello World\n");
bool my_var = my_first_scope::my_second_scope::true;
std::cout << my_var << std::endl;
return 0;
}
Output (build error):
main.cpp: In function ‘int main()’: main.cpp:27:52: error: expected unqualified-id before ‘true’ bool my_var = my_first_scope::my_second_scope::true; ^~~~
Notice the error: error: expected unqualified-id before ‘true’
, and where the arrow under the error is pointing. Apparently the "unqualified-id" in my case is the double colon (::
) scope operator I have just before true
.
When I add in the macro and use it (run this new code here: https://onlinegdb.com/H1eevs58D):
#define MY_MACRO(input) my_first_scope::my_second_scope::input
...
bool my_var = MY_MACRO(true);
I get this new error instead:
main.cpp: In function ‘int main()’: main.cpp:29:28: error: expected unqualified-id before ‘true’ bool my_var = MY_MACRO(true); ^ main.cpp:16:58: note: in definition of macro ‘MY_MACRO’ #define MY_MACRO(input) my_first_scope::my_second_scope::input ^~~~~
For production code requiring a large compatibility with client browsers I still suggest Ivan Nevostruev's answer above with shim to ensure Object.keys
in older browsers. However, it's possible to get the exact functionality requested using ECMA's new defineProperty
feature.
As of ECMAScript 5 - Object.defineProperty
As of ECMA5 you can use Object.defineProperty()
to define non-enumerable properties. The current compatibility still has much to be desired, but this should eventually become usable in all browsers. (Specifically note the current incompatibility with IE8!)
Object.defineProperty(Object.prototype, 'keys', {
value: function keys() {
var keys = [];
for(var i in this) if (this.hasOwnProperty(i)) {
keys.push(i);
}
return keys;
},
enumerable: false
});
var o = {
'a': 1,
'b': 2
}
for (var k in o) {
console.log(k, o[k])
}
console.log(o.keys())
# OUTPUT
# > a 1
# > b 2
# > ["a", "b"]
However, since ECMA5 already added Object.keys
you might as well use:
Object.defineProperty(Object.prototype, 'keys', {
value: function keys() {
return Object.keys(this);
},
enumerable: false
});
Original answer
Object.prototype.keys = function ()
{
var keys = [];
for(var i in this) if (this.hasOwnProperty(i))
{
keys.push(i);
}
return keys;
}
Edit: Since this answer has been around for a while I'll leave the above untouched. Anyone reading this should also read Ivan Nevostruev's answer below.
There's no way of making prototype functions non-enumerable which leads to them always turning up in for-in loops that don't use hasOwnProperty
. I still think this answer would be ideal if extending the prototype of Object wasn't so messy.
Don't escape the underscore. Might be causing some whackness.
use as at end of query
Select * into #temp (select * from table1,table2) as temp_table
Here is an example of basic solution with a user function.
ondblClickRow: function(rowid) {
var cont = $('#grid').getCell(rowid, 'MyCol');
var val = getCellValue(cont);
}
...
function getCellValue(content) {
var k1 = content.indexOf(' value=', 0);
var k2 = content.indexOf(' name=', k1);
var val = '';
if (k1 > 0) {
val = content.substr(k1 + 7, k2 - k1 - 6);
}
return val;
}
Select / Option elements are rendered by the OS, not HTML. You cannot change the style for these elements.
Or if you prefer a one-liner that also illustrates the Python equivalent of C/C++ varags, lambda expressions, and if expressions:
qsort = lambda x=None, *xs: [] if x is None else qsort(*[a for a in xs if a<x]) + [x] + qsort(*[a for a in xs if a>=x])
find . -type d -print0 | xargs -0 -n 1 my_command
Weak references are collected eagerly. If GC finds that an object is weakly reachable (reachable only through weak references), it'll clear the weak references to that object immediately. As such, they're good for keeping a reference to an object for which your program also keeps (strongly referenced) "associated information" somewere, like cached reflection information about a class, or a wrapper for an object, etc. Anything that makes no sense to keep after the object it is associated with is GC-ed. When the weak reference gets cleared, it gets enqueued in a reference queue that your code polls somewhere, and it discards the associated objects as well. That is, you keep extra information about an object, but that information is not needed once the object it refers to goes away. Actually, in certain situations you can even subclass WeakReference and keep the associated extra information about the object in the fields of the WeakReference subclass. Another typical use of WeakReference is in conjunction with Maps for keeping canonical instances.
SoftReferences on the other hand are good for caching external, recreatable resources as the GC typically delays clearing them. It is guaranteed though that all SoftReferences will get cleared before OutOfMemoryError is thrown, so they theoretically can't cause an OOME[*].
Typical use case example is keeping a parsed form of a contents from a file. You'd implement a system where you'd load a file, parse it, and keep a SoftReference to the root object of the parsed representation. Next time you need the file, you'll try to retrieve it through the SoftReference. If you can retrieve it, you spared yourself another load/parse, and if the GC cleared it in the meantime, you reload it. That way, you utilize free memory for performance optimization, but don't risk an OOME.
Now for the [*]. Keeping a SoftReference can't cause an OOME in itself. If on the other hand you mistakenly use SoftReference for a task a WeakReference is meant to be used (namely, you keep information associated with an Object somehow strongly referenced, and discard it when the Reference object gets cleared), you can run into OOME as your code that polls the ReferenceQueue and discards the associated objects might happen to not run in a timely fashion.
So, the decision depends on usage - if you're caching information that is expensive to construct, but nonetheless reconstructible from other data, use soft references - if you're keeping a reference to a canonical instance of some data, or you want to have a reference to an object without "owning" it (thus preventing it from being GC'd), use a weak reference.
Open your Google Chrome devTools and then Console tab: and type this:
"Peace".match(/(\w)(\w)(\w)/)
Run it and you will see:
["Pea", "P", "e", "a", index: 0, input: "Peace", groups: undefined]
The JavaScript
RegExp engine capture three groups, the items with indexes 1,2,3. Now use non-capturing mark to see the result.
"Peace".match(/(?:\w)(\w)(\w)/)
The result is:
["Pea", "e", "a", index: 0, input: "Peace", groups: undefined]
This is obvious what is non capturing group.
There are 2 jQuery functions that you'll want to use here.
1) click
. This will take an anonymous function as it's sole parameter, and will execute it when the element is clicked.
2) html
. This will take an html string as it's sole parameter, and will replace the contents of your element with the html provided.
So, in your case, you'll want to do the following:
$('#content-container a').click(function(e){
$(this).parent().html('<a href="#">I\'m a new link</a>');
e.preventDefault();
});
If you only want to add content to your div, rather than replacing everything in it, you should use append
:
$('#content-container a').click(function(e){
$(this).parent().append('<a href="#">I\'m a new link</a>');
e.preventDefault();
});
If you want the new added links to also add new content when clicked, you should use event delegation:
$('#content-container').on('click', 'a', function(e){
$(this).parent().append('<a href="#">I\'m a new link</a>');
e.preventDefault();
});
I have just discovered a way to append text and its working fine at least.
var text = 'Put any text here';
$('#text').append(text);
You can change text according to your need.
Hope this helps.
GetLastError returns a numerical error code. To obtain a descriptive error message (e.g., to display to a user), you can call FormatMessage:
// This functions fills a caller-defined character buffer (pBuffer)
// of max length (cchBufferLength) with the human-readable error message
// for a Win32 error code (dwErrorCode).
//
// Returns TRUE if successful, or FALSE otherwise.
// If successful, pBuffer is guaranteed to be NUL-terminated.
// On failure, the contents of pBuffer are undefined.
BOOL GetErrorMessage(DWORD dwErrorCode, LPTSTR pBuffer, DWORD cchBufferLength)
{
if (cchBufferLength == 0)
{
return FALSE;
}
DWORD cchMsg = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, /* (not used with FORMAT_MESSAGE_FROM_SYSTEM) */
dwErrorCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
pBuffer,
cchBufferLength,
NULL);
return (cchMsg > 0);
}
In C++, you can simplify the interface considerably by using the std::string class:
#include <Windows.h>
#include <system_error>
#include <memory>
#include <string>
typedef std::basic_string<TCHAR> String;
String GetErrorMessage(DWORD dwErrorCode)
{
LPTSTR psz{ nullptr };
const DWORD cchMsg = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS
| FORMAT_MESSAGE_ALLOCATE_BUFFER,
NULL, // (not used with FORMAT_MESSAGE_FROM_SYSTEM)
dwErrorCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
reinterpret_cast<LPTSTR>(&psz),
0,
NULL);
if (cchMsg > 0)
{
// Assign buffer to smart pointer with custom deleter so that memory gets released
// in case String's c'tor throws an exception.
auto deleter = [](void* p) { ::LocalFree(p); };
std::unique_ptr<TCHAR, decltype(deleter)> ptrBuffer(psz, deleter);
return String(ptrBuffer.get(), cchMsg);
}
else
{
auto error_code{ ::GetLastError() };
throw std::system_error( error_code, std::system_category(),
"Failed to retrieve error message string.");
}
}
NOTE: These functions also work for HRESULT values. Just change the first parameter from DWORD dwErrorCode to HRESULT hResult. The rest of the code can remain unchanged.
FORMAT_MESSAGE_IGNORE_INSERTS
flag. See The importance of the FORMAT_MESSAGE_IGNORE_INSERTS flag for more information.If I understand them correctly (and I'm far from an expert on each) they fundamentally each have a different philosophy. I first used mercurial for 9 months. Now I've used git for 6.
hg is version control software. It's main goal is to track versions of a piece of software.
git is a time based file system. It's goal is to add another dimension to a file system. Most have files and folders, git adds time. That it happens to work awesome as a VCS is a byproduct of its design.
In hg, there's a history of the entire project it's always trying to maintain. By default I believe hg wants all changes to all objects by all users when pushing and pulling.
In git there's just a pool of objects and these tracking files (branches/heads) that determine which set of those objects represent the tree of files in a particular state. When pushing or pulling git only sends the objects needed for the the particular branches you are pushing or pulling, which is a small subset of all objects.
As far as git is concerned there is no "1 project". You could have 50 projects all in the same repo and git wouldn't care. Each one could be managed separately in the same repo and live fine.
Hg's concept of branches is branches off the main project or branches off branches etc. Git has no such concept. A branch in git is just a state of the tree, everything is a branch in git. Which branch is official, current, or newest has no meaning in git.
I don't know if that made any sense. If I could draw pictures hg might look like this where each commit is a o
o---o---o
/
o---o---o---o---o---o---o---o
\ /
o---o---o
A tree with a single root and branches coming off of it. While git can do that and often people use it that way that's not enforced. A git picture, if there is such a thing, could easily look like this
o---o---o---o---o
o---o---o---o
\
o---o
o---o---o---o
In fact in some ways it doesn't even make sense to show branches in git.
One thing that is very confusing for the discussion, git and mercurial both have something called a "branch" but they are not remotely the same things. A branch in mercurial comes about when there are conflicts between different repos. A branch in git is apparently similar to a clone in hg. But a clone, while it might give similar behavior is most definitely not the same. Consider me trying these in git vs hg using the chromium repo which is rather large.
$ time git checkout -b some-new-branch
Switched to new branch 'some-new-branch'
real 0m1.759s
user 0m1.596s
sys 0m0.144s
And now in hg using clone
$ time hg clone project/ some-clone/
updating to branch default
29387 files updated, 0 files merged, 0 files removed, 0 files unresolved.
real 0m58.196s
user 0m19.901s
sys 0m8.957
Both of those are hot runs. Ie, I ran them twice and this is the second run. hg clone is the actually the same as git-new-workdir. Both of those make an entirely new working dir almost as though you had typed cp -r project project-clone
. That's not the same as making a new branch in git. It's far more heavy weight. If there is true equivalent of git's branching in hg I don't know what it is.
I understand at some level hg and git might be able to do similar things. If so then there is a still a huge difference in the workflow they lead you to. In git, the typical workflow is to create a branch for every feature.
git checkout master
git checkout -b add-2nd-joypad-support
git checkout master
git checkout -b fix-game-save-bug
git checkout master
git checkout -b add-a-star-support
That just created 3 branches, each based off a branch called master. (I'm sure there's some way in git to make those 1 line each instead of 2)
Now to work on one I just do
git checkout fix-game-save-bug
and start working. Commit things, etc. Switching between branches even in a project as big as chrome is nearly instantaneous. I actually don't know how to do that in hg. It's not part of any tutorials I've read.
One other big difference. Git's stage.
Git has this idea of a stage. You can think of it as a hidden folder. When you commit you only commit what's on the stage, not the changes in your working tree. That might sound strange. If you want to commit all the changes in your working tree you'd do git commit -a
which adds all the modified files to the stage and then commits them.
What's the point of the stage then? You can easily separate your commits. Imagine you edited joypad.cpp and gamesave.cpp and you want to commit them separately
git add joypad.cpp // copies to stage
git commit -m "added 2nd joypad support"
git add gamesave.cpp // copies to stage
git commit -m "fixed game save bug"
Git even has commands to decide which particular lines in the same file you want to copy to the stage so you can split up those commits separately as well. Why would you want to do that? Because as separate commits others can pull only the ones they want or if there was an issue they can revert just the commit that had the issue.
Using alternative dplyr package:
library("dplyr") # or library("tidyverse")
df <- df %>% mutate(id = row_number())
/* Drop all non-system stored procs */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 ORDER BY [name])
WHILE @name is not null
BEGIN
SELECT @SQL = 'DROP PROCEDURE [dbo].[' + RTRIM(@name) +']'
EXEC (@SQL)
PRINT 'Dropped Procedure: ' + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO
/* Drop all views */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 ORDER BY [name])
WHILE @name IS NOT NULL
BEGIN
SELECT @SQL = 'DROP VIEW [dbo].[' + RTRIM(@name) +']'
EXEC (@SQL)
PRINT 'Dropped View: ' + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO
/* Drop all functions */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 ORDER BY [name])
WHILE @name IS NOT NULL
BEGIN
SELECT @SQL = 'DROP FUNCTION [dbo].[' + RTRIM(@name) +']'
EXEC (@SQL)
PRINT 'Dropped Function: ' + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 AND [name] > @name ORDER BY [name])
END
GO
/* Drop all Foreign Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
WHILE @name is not null
BEGIN
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
WHILE @constraint IS NOT NULL
BEGIN
SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint) +']'
EXEC (@SQL)
PRINT 'Dropped FK Constraint: ' + @constraint + ' on ' + @name
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
END
GO
/* Drop all Primary Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
WHILE @name IS NOT NULL
BEGIN
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
WHILE @constraint is not null
BEGIN
SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint)+']'
EXEC (@SQL)
PRINT 'Dropped PK Constraint: ' + @constraint + ' on ' + @name
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
END
GO
/* Drop all tables */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 ORDER BY [name])
WHILE @name IS NOT NULL
BEGIN
SELECT @SQL = 'DROP TABLE [dbo].[' + RTRIM(@name) +']'
EXEC (@SQL)
PRINT 'Dropped Table: ' + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO
You can always use this, taken from Microsofts website.
static void Main()
{
// Copy from the current directory, include subdirectories.
DirectoryCopy(".", @".\temp", true);
}
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
Just use Analyze | Inspect Code
with appropriate inspection enabled (Unused declaration under Declaration redundancy group).
Using IntelliJ 11 CE you can now "Analyze | Run Inspection by Name ... | Unused declaration"
Had the same problem when running the nodemon command so i reduced the name of files open in sublime text and the error dissappeared.
This is possible if you have an existing Newline character in the row or another row.
Select the square-box that represents the existing Newline character, copy it (control-C), and then paste it (control-V) where you want it to be.
This is slightly cheesy, but I actually did get it to work in SSMS 2008 and I was not able to get any of the other suggestions (control-enter, alt-13, or any alt-##) to work.
[SOLVED]
I only observed this error today, for me the Error code was different though.
SCRIPT7002: XMLHttpRequest: Network Error 0x2efd, Could not complete the operation due to error 00002efd.
It was occurring randomly and not all the time. but what it noticed is, if it comes for subsequent ajax calls. so i put some delay of 5 seconds between the ajax calls and it resolved.
if you don't want to use json.parse(json.stringify(object)) you could create recursively key-value copies:
function copy(item){
let result = null;
if(!item) return result;
if(Array.isArray(item)){
result = [];
item.forEach(element=>{
result.push(copy(element));
});
}
else if(item instanceof Object && !(item instanceof Function)){
result = {};
for(let key in item){
if(key){
result[key] = copy(item[key]);
}
}
}
return result || item;
}
But the best way is to create a class that can return a clone of it self
class MyClass{
data = null;
constructor(values){ this.data = values }
toString(){ console.log("MyClass: "+this.data.toString(;) }
remove(id){ this.data = data.filter(d=>d.id!==id) }
clone(){ return new MyClass(this.data) }
}
$ disown node server.js &
It will remove command from active task list and send the command to background
In this two queries, you are using JOIN to query all employees that have at least one department associated.
But, the difference is: in the first query you are returning only the Employes for the Hibernate. In the second query, you are returning the Employes and all Departments associated.
So, if you use the second query, you will not need to do a new query to hit the database again to see the Departments of each Employee.
You can use the second query when you are sure that you will need the Department of each Employee. If you not need the Department, use the first query.
I recomend read this link if you need to apply some WHERE condition (what you probably will need): How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery?
Update
If you don't use fetch
and the Departments continue to be returned, is because your mapping between Employee and Department (a @OneToMany
) are setted with FetchType.EAGER
. In this case, any HQL (with fetch
or not) query with FROM Employee
will bring all Departments. Remember that all mapping *ToOne (@ManyToOne
and @OneToOne
) are EAGER by default.
Here's the magic you want:
autocomplete="new-password"
Chrome intentionally ignores autocomplete="off"
and autocomplete="false"
. However, they put new-password
in as a special clause to stop new password forms from being auto-filled.
I put the above line in my password input, and now I can edit other fields in my form and the password is not auto-filled.
if you have long processing server side code, I don't think it does fall into 404 as you said ("it goes to a webpage is not found error page")
Browser should report request timeout error.
You may do 2 things:
Based on CGI/Server side engine increase timeout there
PHP : http://www.php.net/manual/en/info.configuration.php#ini.max-execution-time - default is 30 seconds
In php.ini:
max_execution_time 60
Increase apache timeout - default is 300 (in version 2.4 it is 60).
In your httpd.conf (in server config or vhost config)
TimeOut 600
Note that first setting allows your PHP script to run longer, it will not interferre with network timeout.
Second setting modify maximum amount of time the server will wait for certain events before failing a request
Sorry, I'm not sure if you are using PHP as server side processing, but if you provide more info I will be more accurate.
First, you should download the suitable version for your system from here: https://pecl.php.net/package/mcrypt/1.0.3/windows
Then, you should copy php_mcrypt.dll
to ../xampp/php/ext/
and enable the extension by adding extension=mcrypt
to your xampp/php/php.ini
file.
If you want to get back only the first row of a sorted result with the least subqueries, try this:
select *
from ( select a.*
, row_number() over ( order by sysdate_col desc ) as row_num
from table_name a )
where row_num = 1;
I just stumbled onto this issue accessing some Python libraries: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools". The latest link to that is actually here: https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2019
When you begin the installer, it will have several "options" enabled which will balloon the install size to 5gb. If you have Windows 10, you'll need to leave selected the "Windows 10 SDK" option as mentioned here.
I hope it helps save others time!
I've a PHP library which helps to insert array into MySQL Database. By using this you can create update and delete. Your array key value should be same as the table column value. Just using a single line code for the create operation
DB::create($db, 'YOUR_TABLE_NAME', $dataArray);
where $db is your Database connection.
Similarly, You can use this for update and delete. Select operation will be available soon. Github link to download : https://github.com/pairavanvvl/crud
You asked how to escape an Apostrophe character (')
in SQL Server. All the answers above do an excellent job of explaining that.
However, depending on the situation, the Right single quotation mark character (’)
might be appropriate.
(No escape characters needed)
-- Direct insert
INSERT INTO Table1 (Column1) VALUES ('John’s')
• Apostrophe (U+0027)
• Right single quotation mark (U+2019)
The negative margin trick on the box container works just great. Here is another example working great with order, wrapping and what not.
.container {_x000D_
border: 1px solid green;_x000D_
width: 200px;_x000D_
display: inline-block;_x000D_
}_x000D_
_x000D_
#box {_x000D_
display: flex;_x000D_
flex-wrap: wrap-reverse;_x000D_
margin: -10px;_x000D_
border: 1px solid red;_x000D_
}_x000D_
.item {_x000D_
flex: 1 1 auto;_x000D_
order: 1;_x000D_
background: gray;_x000D_
width: 50px;_x000D_
height: 50px;_x000D_
margin: 10px;_x000D_
border: 1px solid blue;_x000D_
}_x000D_
.first {_x000D_
order: 0;_x000D_
}
_x000D_
<div class=container>_x000D_
<div id='box'>_x000D_
<div class='item'>1</div>_x000D_
<div class='item'>2</div>_x000D_
<div class='item first'>3*</div>_x000D_
<div class='item'>4</div>_x000D_
<div class='item'>5</div>_x000D_
</div>_x000D_
</div>
_x000D_
Script to perform Docker save and load function (tried and tested):
Docker Save:
#!/bin/bash
#files will be saved in the dir 'Docker_images'
mkdir Docker_images
cd Docker_images
directory=`pwd`
c=0
#save the image names in 'list.txt'
doc= docker images | awk '{print $1}' > list.txt
printf "START \n"
input="$directory/list.txt"
#Check and create the image tar for the docker images
while IFS= read -r line
do
one=`echo $line | awk '{print $1}'`
two=`echo $line | awk '{print $1}' | cut -c 1-3`
if [ "$one" != "<none>" ]; then
c=$((c+1))
printf "\n $one \n $two \n"
docker save -o $two$c'.tar' $one
printf "Docker image number $c successfully converted: $two$c \n \n"
fi
done < "$input"
Docker Load:
#!/bin/bash
cd Docker_images/
directory=`pwd`
ls | grep tar > files.txt
c=0
printf "START \n"
input="$directory/files.txt"
while IFS= read -r line
do
c=$((c+1))
printf "$c) $line \n"
docker load -i $line
printf "$c) Successfully created the Docker image $line \n \n"
done < "$input"
I have 2 Nexus 4 devices. One was connecting to ADB without any problems, the second one never showed up when I used the adb devices
command. An additional symptom was, that the second phone did not show up as a portable device in Windows Explorer when the phone was set to Media mode.
At some point I found that a temporary solution for the second Nexus was to switch it to PTP mode. Then it was found by the adb devices
command. The weired thing was that the first phone worked in both modes all the time!
Finally I found this solution that now allows me to connect both phones in both modes:
set USB mode of the phone to MTP (Media)
Using PC device manager uninstall the device ->Android Device ->Android ADB Interface
Make sure to check the box "Delete the driver software"!
then set the USB mode of the phone to PTP (Camera)
Using PC device manager uninstall the device ->Portable Devies ->Nexus 4
Then unplug the USB and plug it back in (ensuring that its set to MTP (Media) and I found that the device was correctly registered in Device manager as a ->Portable Devies ->Nexus 4
Solution found at: http://forum.xda-developers.com/showthread.php?p=34910298#post34910298
If you have a similar problem to connect your Nexus to ADB then I recommend to first switch it to PTP mode. If your problem vanishes with that step, I recommend to go through the additional steps listed above as MTP will probably be the mode you will want to set your phone to most of the time.
Use the formatting operator %
:
buf = "A = %d\n , B= %s\n" % (a, b)
print >>f, buf
Put a z-indez
of -1
on your absolute (or relative) positioned element.
This will pull it out of the stacking context. (I think.) Read more wonderful things about "stacking contexts" here: https://philipwalton.com/articles/what-no-one-told-you-about-z-index/
$("#id").autocomplete(
{
search: function () {},
source: function (request, response)
{
$.ajax(
{
url: ,
dataType: "json",
data:
{
term: request.term,
},
success: function (data)
{
response(data);
}
});
},
minLength: 2,
select: function (event, ui)
{
var test = ui.item ? ui.item.id : 0;
if (test > 0)
{
alert(test);
}
}
});
Note the guidelines for performing work on a UI thread, collected on my blog:
There are two techniques you should use:
1) Use ConfigureAwait(false)
when you can.
E.g., await MyAsync().ConfigureAwait(false);
instead of await MyAsync();
.
ConfigureAwait(false)
tells the await
that you do not need to resume on the current context (in this case, "on the current context" means "on the UI thread"). However, for the rest of that async
method (after the ConfigureAwait
), you cannot do anything that assumes you're in the current context (e.g., update UI elements).
For more information, see my MSDN article Best Practices in Asynchronous Programming.
2) Use Task.Run
to call CPU-bound methods.
You should use Task.Run
, but not within any code you want to be reusable (i.e., library code). So you use Task.Run
to call the method, not as part of the implementation of the method.
So purely CPU-bound work would look like this:
// Documentation: This method is CPU-bound.
void DoWork();
Which you would call using Task.Run
:
await Task.Run(() => DoWork());
Methods that are a mixture of CPU-bound and I/O-bound should have an Async
signature with documentation pointing out their CPU-bound nature:
// Documentation: This method is CPU-bound.
Task DoWorkAsync();
Which you would also call using Task.Run
(since it is partially CPU-bound):
await Task.Run(() => DoWorkAsync());
System.currentTimeMillis()
everything else works off that.. eg new Date() calls System.currentTimeMillis().
You might want to take a look at this example:
public static void main(String[] args) {
String myTime = "10:30:54";
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date = null;
try {
date = sdf.parse(myTime);
} catch (ParseException e) {
e.printStackTrace();
}
String formattedTime = sdf.format(date);
System.out.println(formattedTime);
}
I like to be super lazy by using tables to align images with the vertical pipe (|
) syntax. This is supported by some Markdown flavours (and is also supported by Textile if that floats your boat):
| I am text to the left | ![Flowers](/flowers.jpeg) |
or
| ![Flowers](/flowers.jpeg) | I am text to the right |
It is not the most flexible solution, but it is good for most of my simple needs, is easy to read in markdown format, and you don't need to remember any CSS or raw HTML.
Change your line
ws.Range(Rand, 1).EntireRow.Delete
to
ws.Cells(Rand, 1).EntireRow.Delete
If you just want the node closest to the text you're searching for, you could use this:
$('*:contains("my text"):last');
This will even work if your HTML looks like this:
<p> blah blah <strong>my <em>text</em></strong></p>
Using the above selector will find the <strong>
tag, since that's the last tag which contains that entire string.
Codo was exactly right on Oct. 5 that ¤t[i] is the intended text (with the currency symbol inadvertently introduced when the source was put into HTML (see original): http://downloads.securityfocus.com/vulnerabilities/exploits/59846-1.c
Codo's change makes this exploit code compile without error. I did that and was able to use the exploit on Ubuntu 12.04 to escalate to root privilege.
You are dealing with a HttpPostedFile; this is the file that is "uploaded" to the web server. You really need to save that file somewhere and then use it, because...
...in your instance, it just so happens to be that you are hosting your website on the same machine the file resides, so the path is accessible. As soon as you deploy your site to a different machine, your code isn't going to work.
Break this down into two steps:
1) Save the file somewhere - it's very common to see this:
string saveFolder = @"C:\temp\uploads"; //Pick a folder on your machine to store the uploaded files
string filePath = Path.Combine(saveFolder, FileUpload1.FileName);
FileUpload1.SaveAs(filePath);
Now you have your file locally and the real work can be done.
2) Get the data from the file. Your code should work as is but you can simply write your connection string this way:
string excelConnString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties="Excel 12.0";", filePath);
You can then think about deleting the file you've just uploaded and imported.
To provide a more concrete example, we can refactor your code into two methods:
private void SaveFileToDatabase(string filePath)
{
String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\Hemant\\documents\\visual studio 2010\\Projects\\CRMdata\\CRMdata\\App_Data\\Database1.mdf';Integrated Security=True;User Instance=True";
String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
//Create Connection to Excel work book
using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
{
//Create OleDbCommand to fetch data from Excel
using (OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection))
{
excelConnection.Open();
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
using(SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
{
//Give your Destination table name
sqlBulk.DestinationTableName = "Excel_table";
sqlBulk.WriteToServer(dReader);
}
}
}
}
}
private string GetLocalFilePath(string saveDirectory, FileUpload fileUploadControl)
{
string filePath = Path.Combine(saveDirectory, fileUploadControl.FileName);
fileUploadControl.SaveAs(filePath);
return filePath;
}
You could simply then call SaveFileToDatabase(GetLocalFilePath(@"C:\temp\uploads", FileUpload1));
Consider reviewing the other Extended Properties for your Excel connection string. They come in useful!
Other improvements you might want to make include putting your Sql Database connection string into config, and adding proper exception handling. Please consider this example for demonstration only!
only this will work:
path=%set path%;C:\Program Files\Java\jdk1.7.0_04\bin
You can get a pretty coarse idea of the OS you're using by checking sys.platform
.
Once you have that information you can use it to determine if calling something like os.uname()
is appropriate to gather more specific information. You could also use something like Python System Information on unix-like OSes, or pywin32 for Windows.
There's also psutil if you want to do more in-depth inspection without wanting to care about the OS.
If you don't have the Runnable references, on the first callback, get the obj of the message, and use removeCallbacksAndMessages() to remove all related callbacks.
I think its a bug, please apply the workaround and then try again: http://support.microsoft.com/kb/281517.
Also, go into Advanced tab, and confirm if Target columns length is Varchar(max).
You can pass the struct pointer to function as function argument. It called pass by reference.
If you modify something inside that pointer, the others will be updated to. Try like this:
typedef struct client_t client_t, *pno;
struct client_t
{
pid_t pid;
char password[TAM_MAX]; // -> 50 chars
pno next;
};
pno AddClient(client_t *client)
{
/* this will change the original client value */
client.password = "secret";
}
int main()
{
client_t client;
//code ..
AddClient(&client);
}
Maybe this can help you also. It's from the website:
http://nathanael.hevenet.com/android-dev-changing-the-title-bar-background/
First things first you need to have a custom theme declared for your application (or activity, depending on your needs). Something like…
<!-- Somewhere in AndroidManifest.xml -->
<application ... android:theme="@style/ThemeSelector">
Then, declare your custom theme for two cases, API versions with and without the Holo Themes. For the old themes we’ll customize the windowTitleBackgroundStyle attribute, and for the newer ones the ActionBarStyle.
<!-- res/values/styles.xml -->
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="ThemeSelector" parent="android:Theme.Light">
<item name="android:windowTitleBackgroundStyle">@style/WindowTitleBackground</item>
</style>
<style name="WindowTitleBackground">
<item name="android:background">@color/title_background</item>
</style>
</resources>
<!-- res/values-v11/styles.xml -->
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="ThemeSelector" parent="android:Theme.Holo.Light">
<item name="android:actionBarStyle">@style/ActionBar</item>
</style>
<style name="ActionBar" parent="android:style/Widget.Holo.ActionBar">
<item name="android:background">@color/title_background</item>
</style>
</resources>
That’s it!
Your resource methods won't get hit, so their headers will never get set. The reason is that there is what's called a preflight request before the actual request, which is an OPTIONS
request. So the error comes from the fact that the preflight request doesn't produce the necessary headers.
For RESTeasy, you should use CorsFilter
. You can see here for some example how to configure it. This filter will handle the preflight request. So you can remove all those headers you have in your resource methods.
See Also:
You can use DataSet.Tables(0).Columns.Contains(name)
to check whether the DataTable
contains a column with a particular name.
window.location.hash is a string
, so do this:
var page_number: number = 3;
window.location.hash = String(page_number);
<?php
$val1 = rand(1,4);
$val2=rand(1,4);
if ($pars[$last0] == "reviews" && $pars[$last] > 0) {
echo widget("Bootstrap Theme - Member Profile - Read Review",'',$w[website_id],$w);
} else { ?>
<div class="w100">
<div style="background:transparent!important;" class="w100 well" id="postreview">
<?php
$_GET[user_id] = $user[user_id];
$_GET[member_id] = $_COOKIE[userid];
$_GET[subaction] = "savereview";
$_GET[ip] = $_SERVER[REMOTE_ADDR];
$_GET[httpr] = $_ENV[requesturl];
echo form("member_review","",$w[website_id],$w);?>
</div></div>
ive replaced the 'else' with '&&' so both are placed ... argh
I had the same problem. What i found was i called my recieving object the same name as the class name. example:
const AspectType = new AspectType();
this screwed things up that way... hope this helps
For your example you can try
DateTime StartDate = new DateTime(2009, 3, 10);
DateTime EndDate = new DateTime(2009, 3, 26);
int DayInterval = 3;
List<DateTime> dateList = new List<DateTime>();
while (StartDate.AddDays(DayInterval) <= EndDate)
{
StartDate = StartDate.AddDays(DayInterval);
dateList.Add(StartDate);
}
(I'm using React Native; targetSdkVersion 22). I'm trying to change the look of a calendar date picker dialog. The accepted answer didn't work for me, but this did. Hope this snippet helps some of you.
<style name="CalendarDatePickerDialog" parent="Theme.AppCompat.Light.Dialog">
<item name="colorAccent">#6bf442</item>
<item name="android:textColorPrimary">#6bf442</item>
</style>
You could change your code in this way:
public delegate void CallbackHandler(string str);
public class ServerRequest
{
public void DoRequest(string request, CallbackHandler callback)
{
// do stuff....
callback("asdf");
}
}
$i=0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($i>0){
$import="INSERT into importing(text,number)values('".$data[0]."','".$data[1]."')";
mysql_query($import) or die(mysql_error());
}
$i=1;
}
This happened to me when carrying out manual tests of the sign up process of my application (signing up/in with multiple users).
A very simple and pragmatic solution may be to do what I did, and use a different browser (or incognito if using chrome).
This was a much better solution in my case than disabling security features!!
if(new File("/sdcard/your_filename.txt").exists())){
// Your code goes here...
}
Via Environment.OSVersion
which "Gets an System.OperatingSystem object that contains the current platform identifier and version number."
I've been frustrated on many occasions with this problem, especially when intergating a project library as part of another project. In the most recent occurrence of this plagued problem, my Android lib project was using a WebView. It turns out that Gradle builds the R.class file in a sub directory called "web" whose path does not have anything to do with my source code path. When I imported this, my problem was gone. What have I learned? In the future, simply do a file search for R.class and note the path where it is located. Then import the package into your code using that path. It really sucks that you have to manually perform this. Gradle should automatically import packages it generates.
I have too low reputation to add comment to @bernie response, with response to @user1506145. I have run in to same issue.
The answer to it is a interval parameter which fixes things up
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import datetime as dt
np.random.seed(1)
N = 100
y = np.random.rand(N)
now = dt.datetime.now()
then = now + dt.timedelta(days=100)
days = mdates.drange(now,then,dt.timedelta(days=1))
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=5))
plt.plot(days,y)
plt.gcf().autofmt_xdate()
plt.show()
The Dr. Memory (http://drmemory.org) tool comes with a system call tracing tool called drstrace that lists all system calls made by a target application along with their arguments: http://drmemory.org/strace_for_windows.html
For programmatically enforcing system call policies, you could use the same underlying engines as drstrace: the DynamoRIO tool platform (http://dynamorio.org) and the DrSyscall system call monitoring library (http://drmemory.org/docs/page_drsyscall.html). These use dynamic binary translation technology, which does incur some overhead (20%-30% in steady state, but much higher when running new code such as launching a big desktop app), which may or may not be suitable for your purposes.
Did you write
String guid = System.Guid.NewGuid().ToString;
or
String guid = System.Guid.NewGuid().ToString();
notice the paranthesis
To reduce verbosity, you can use a static import:
import static java.util.concurrent.TimeUnit.NANOSECONDS;
-and henceforth just type
NANOSECONDS.toSeconds(elapsedTime);
Current css version still doesn't support selector find by content. But there is a way, by using css selector find by attribute, but you have to put some identifier on all of the <td>
that have $
inside. Example:
using nth-child in tables tr td
html
<tr>
<td> </td>
<td data-rel='$'>$</td>
<td> </td>
</tr>
css
table tr td[data-rel='$'] {
background-color: #333;
color: white;
}
Please try these example.
table tr td[data-content='$'] {_x000D_
background-color: #333;_x000D_
color: white;_x000D_
}
_x000D_
<table border="1">_x000D_
<tr>_x000D_
<td>A</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>B</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>C</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>D</td>_x000D_
</tr>_x000D_
</table>
_x000D_
The published responses are correct but incomplete.
Git to install the packages we first need to make sure git is installed.
$ sudo apt install git-core
Bower uses Node.js and npm to manage the programs so lets install these.
$ sudo apt install nodejs
Node will now be installed with the executable located in /etc/usr/nodejs
.
You should be able to execute Node.js by using the command below, but as ours are location in nodejs we will get an error No such file or directory.
$ /usr/bin/env node
We can manually fix this by creating a symlink.
$ sudo ln -s /usr/bin/nodejs /usr/bin/node
Now check Node.js is installed correctly by using.
$ /usr/bin/env node
>
Some users suggest installing legacy nodejs, this package just creates a symbolic link to binary nodejs.
$ sudo apt install nodejs-legacy
Now, you can install npm and bower
Install npm
$ sudo apt install npm
Install Bower
$ sudo npm install -g bower
Check bower is installed and what version you're running.
$ bower -v
1.8.0
Reference:
After searching around a bit, the best solution in my opinion makes use of hudson.model.EnvironmentContributingAction.
import hudson.model.EnvironmentContributingAction
import hudson.model.AbstractBuild
import hudson.EnvVars
class BuildVariableInjector {
def build
def out
def BuildVariableInjector(build, out) {
this.build = build
this.out = out
}
def addBuildEnvironmentVariable(key, value) {
def action = new VariableInjectionAction(key, value)
build.addAction(action)
//Must call this for action to be added
build.getEnvironment()
}
class VariableInjectionAction implements EnvironmentContributingAction {
private String key
private String value
public VariableInjectionAction(String key, String value) {
this.key = key
this.value = value
}
public void buildEnvVars(AbstractBuild build, EnvVars envVars) {
if (envVars != null && key != null && value != null) {
envVars.put(key, value);
}
}
public String getDisplayName() {
return "VariableInjectionAction";
}
public String getIconFileName() {
return null;
}
public String getUrlName() {
return null;
}
}
}
I use this class in a system groovy script (using the groovy plugin) within a job.
import hudson.model.*
import java.io.File;
import jenkins.model.Jenkins;
def jenkinsRootDir = build.getEnvVars()["JENKINS_HOME"];
def parent = getClass().getClassLoader()
def loader = new GroovyClassLoader(parent)
def buildVariableInjector = loader.parseClass(new File(jenkinsRootDir + "/userContent/GroovyScripts/BuildVariableInjector.groovy")).newInstance(build, getBinding().out)
def projectBranchDependencies = []
//Some logic to set projectBranchDependencies variable
buildVariableInjector.addBuildEnvironmentVariable("projectBranchDependencies", projectBranchDependencies.join(","));
You can then access the projectBranchDependencies variable at any other point in your build, in my case, from an ANT script.
Note: I borrowed / modified the ideas for parts of this implementation from a blog post, but at the time of this posting I was unable to locate the original source in order to give due credit.
A couple of things for ya:
The loading would be "better" like this:
with file('morsecodes.txt', 'rt') as f:
for line in f:
line = line.strip()
if len(line) > 0:
# do your stuff to parse the file
That way you don't need to close, and you don't need to manually load each line, etc., etc.
for letter in userInput:
if ValidateLetter(letter): # you need to define this
code = GetMorseCode(letter) # from my other answer
# do whatever you want
you can use this code .may be solve the problem
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://192.168.43.1:6789/mobile_base/test.apk"));
startActivity(intent);
Use sudo apt-get install --only-upgrade nodejs
to upgrade node (and only upgrade node) using the package manager.
The package name is nodejs
, see https://stackoverflow.com/a/18130296/4578017 for details.
You can also use nvm
to install and update node.
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.1/install.sh | bash
Then restart the terminal, use nvm ls-remote
to get latest version list of node, and use nvm install lts/*
to install latest LTS version.
nvm
is more recommended way to install or update node, even if you are not going to switch versions.
It's not bullet-proof but for UNIX environments simple test like
if run("which python3").find("venv") == -1:
# something when not executed from venv
works great for me. It's simpler then testing existing of some attribute and, anyway, you should name your venv directory venv
.
You can do this using the Class.cast()
method, which dynamically casts the supplied parameter to the type of the class instance you have. To get the class instance of a particular field, you use the getType()
method on the field in question. I've given an example below, but note that it omits all error handling and shouldn't be used unmodified.
public class Test {
public String var1;
public Integer var2;
}
public class Main {
public static void main(String[] args) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("var1", "test");
map.put("var2", 1);
Test t = new Test();
for (Map.Entry<String, Object> entry : map.entrySet()) {
Field f = Test.class.getField(entry.getKey());
f.set(t, f.getType().cast(entry.getValue()));
}
System.out.println(t.var1);
System.out.println(t.var2);
}
}
You can use location
to send state to other component, like this
In your Source Component
this.props.history.push(pathComponent, sendState);
pathComponent
is target component that will receive the state
In your Target Component you can receive the state like this if your use class component
constructor(props) {
this.state = this.props.location.state
}
constructor(props: {}) {
const receiveState = this.props.location.state as StateType // you must parse into your state interface or type
this.state = receiveState
}
If you want to reset the received state. Use history
to replace the location, like this
this.props.history({pathName: currentPath, state: resetState})
currentPath
is the Target Component path
resetState
is new value state whatever you want
For anyone looking to do this dynamically then setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom)
on the buttons object will assist.
Sample
Button search = (Button) findViewById(R.id.yoursearchbutton);
search.setCompoundDrawables('your_drawable',null,null,null);
Check if the Browser is IE -
$ua = htmlentities($_SERVER['HTTP_USER_AGENT'], ENT_QUOTES, 'UTF-8');
if (preg_match('~MSIE|Internet Explorer~i', $ua) || (strpos($ua, 'Trident/7.0') !== false && strpos($ua, 'rv:11.0') !== false)) {
// do stuff for IE Here
}
TLPD ("too long path directory") is the program that saved me. Very easy to use:
Yes, accessing parent page's URL is not allowed if the iframe and the main page are not in the same (sub)domain. However, if you just need the URL of the main page (i.e. the browser URL), you can try this:
var url = (window.location != window.parent.location)
? document.referrer
: document.location.href;
Note:
window.parent.location
is allowed; it avoids the security error in the OP, which is caused by accessing the href
property: window.parent.location.href
causes "Blocked a frame with origin..."
document.referrer
refers to "the URI of the page that linked to this page." This may not return the containing document if some other source is what determined the iframe
location, for example:
document.referrer
will be Domain 3, not the containing Domain 1document.location
refers to "a Location object, which contains information about the URL of the document"; presumably the current document, that is, the iframe currently open. When window.location === window.parent.location
, then the iframe's href
is the same as the containing parent's href
.
Here is how I've always done it:
public static string Serialize(object obj) {
using(MemoryStream memoryStream = new MemoryStream())
using(StreamReader reader = new StreamReader(memoryStream)) {
DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
serializer.WriteObject(memoryStream, obj);
memoryStream.Position = 0;
return reader.ReadToEnd();
}
}
public static object Deserialize(string xml, Type toType) {
using(Stream stream = new MemoryStream()) {
byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
stream.Write(data, 0, data.Length);
stream.Position = 0;
DataContractSerializer deserializer = new DataContractSerializer(toType);
return deserializer.ReadObject(stream);
}
}
The HTML attribute required="required"
is a statement telling the browser that this field is required in order for the form to be valid. (required="required"
is the XHTML form, just using required
is equivalent)
The Angular attribute ng-required="yourCondition"
means 'isRequired(yourCondition)' and sets the HTML attribute dynamically for you depending on your condition.
Also note that the HTML version is confusing, it is not possible to write something conditional like required="true"
or required="false"
, only the presence of the attribute matters (present means true) ! This is where Angular helps you out with ng-required
.
You can use the microtime
function for this. From the documentation:
microtime
— Return current Unix timestamp with microseconds
If
get_as_float
is set toTRUE
, thenmicrotime()
returns a float, which represents the current time in seconds since the Unix epoch accurate to the nearest microsecond.
Example usage:
$start = microtime(true);
while (...) {
}
$time_elapsed_secs = microtime(true) - $start;
have you checked the "Sibling" method in jQuery?
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
the n.nodeType == 1 check if the element is a html node and n!== exclude the current element.
I think you can use the same function, all that code seems to be vanilla javascript.
Cocos2d-x within your classic Android (Java) app tuto http://jpsarda.tumblr.com/post/26000816688/integrate-cocos2d-x-c-into-an-android-application
I have added a Maven/Java project with 1 Domain class with the following features:
Where are the Jacoco results? After testing and running 'mvn clean', you can find the results in 'target/site/jacoco/index.html'. Open this file in the browser.
Enjoy!
I tried to keep the project as simple as possible. The project puts many suggestions from these posts together in an example project. Thank you, contributors!
Use the eq selector to selct the nth row (0-based) and add your row after it using after, so:
$('#my_table > tbody:last tr:eq(2)').after(html);
where html is a tr
Create a new style
<!-- Theme.AppCompat.Light.Dialog -->
<style name="DialogTheme" parent="Theme.AppCompat.Light.Dialog">
<item name="colorAccent">@color/blue_500</item>
</style>
Java code:
The parent theme is the key here. Choose your colorAccent
DatePickerDialog = new DatePickerDialog(context,R.style.DialogTheme,this,now.get(Calendar.YEAR),now.get(Calendar.MONTH),now.get(Calendar.DAY_OF_MONTH);
Result:
in mvc 5
@Html.EditorFor(x => x.Address,
new {htmlAttributes = new {@class = "form-control",
@placeholder = "Complete Address", @cols = 10, @rows = 10 } })
This error happens when you send 2 responses. For example :
if(condition A)
{
res.render('Profile', {client:client_});
}
if (condition B){
res.render('Profile', {client:client_});
}
}
Imagine if for some reason condition A and B are true so in the second render
you'll get that error
For me same error occurred because I renamed the namespace of the Program class.
The "Startup object" field in "Application" tab of the project still referenced the old namespace. Selecting new startup object solved the problem and also removed the obsolete entry from that list.
You may also want to update "Default namespace" field in the same "Application" tab.
The code below will convert any XMLObject or string to a native JavaScript object. Then you can walk on the object to extract any value you want.
/**
* Tries to convert a given XML data to a native JavaScript object by traversing the DOM tree.
* If a string is given, it first tries to create an XMLDomElement from the given string.
*
* @param {XMLDomElement|String} source The XML string or the XMLDomElement prefreably which containts the necessary data for the object.
* @param {Boolean} [includeRoot] Whether the "required" main container node should be a part of the resultant object or not.
* @return {Object} The native JavaScript object which is contructed from the given XML data or false if any error occured.
*/
Object.fromXML = function( source, includeRoot ) {
if( typeof source == 'string' )
{
try
{
if ( window.DOMParser )
source = ( new DOMParser() ).parseFromString( source, "application/xml" );
else if( window.ActiveXObject )
{
var xmlObject = new ActiveXObject( "Microsoft.XMLDOM" );
xmlObject.async = false;
xmlObject.loadXML( source );
source = xmlObject;
xmlObject = undefined;
}
else
throw new Error( "Cannot find an XML parser!" );
}
catch( error )
{
return false;
}
}
var result = {};
if( source.nodeType == 9 )
source = source.firstChild;
if( !includeRoot )
source = source.firstChild;
while( source ) {
if( source.childNodes.length ) {
if( source.tagName in result ) {
if( result[source.tagName].constructor != Array )
result[source.tagName] = [result[source.tagName]];
result[source.tagName].push( Object.fromXML( source ) );
}
else
result[source.tagName] = Object.fromXML( source );
} else if( source.tagName )
result[source.tagName] = source.nodeValue;
else if( !source.nextSibling ) {
if( source.nodeValue.clean() != "" ) {
result = source.nodeValue.clean();
}
}
source = source.nextSibling;
}
return result;
};
String.prototype.clean = function() {
var self = this;
return this.replace(/(\r\n|\n|\r)/gm, "").replace(/^\s+|\s+$/g, "");
}
Here's how to use a Jet OLEDB or Ace OLEDB Access DB:
using System.Data;
using System.Data.OleDb;
string myConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=C:\myPath\myFile.mdb;" +
"Persist Security Info=True;" +
"Jet OLEDB:Database Password=myPassword;";
try
{
// Open OleDb Connection
OleDbConnection myConnection = new OleDbConnection();
myConnection.ConnectionString = myConnectionString;
myConnection.Open();
// Execute Queries
OleDbCommand cmd = myConnection.CreateCommand();
cmd.CommandText = "SELECT * FROM `myTable`";
OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); // close conn after complete
// Load the result into a DataTable
DataTable myDataTable = new DataTable();
myDataTable.Load(reader);
}
catch (Exception ex)
{
Console.WriteLine("OLEDB Connection FAILED: " + ex.Message);
}
While trying out the final suggestion above, I discovered an even simpler solution. All I had to do was cache the process handle. As soon as I did that, $process.ExitCode worked correctly. If I didn't cache the process handle, $process.ExitCode was null.
example:
$proc = Start-Process $msbuild -PassThru
$handle = $proc.Handle # cache proc.Handle
$proc.WaitForExit();
if ($proc.ExitCode -ne 0) {
Write-Warning "$_ exited with status code $($proc.ExitCode)"
}
You also can give a name to your script:
<script>
... (your code here)
//# sourceURL=somename.js
</script>
ofcourse replace "somename" by some name ;) and then you will see it in the chrome debugger at "Sources > top > (no domain) > somename.js" as a normal script and you will be able to debug it like other scripts
Your question is underspecified. Strictly, that example is a syntax error. However, mbstowcs
is probably what you're looking for.
It is a C-library function and operates on buffers, but here's an easy-to-use idiom, courtesy of Mooing Duck:
std::wstring ws(s.size(), L' '); // Overestimate number of code points.
ws.resize(::mbstowcs_s(&ws[0], ws.size(), s.c_str(), s.size())); // Shrink to fit.
Output on Windows:
you can just use this command,it is very easy!
1. no password of MySQL:
mysql ?
2. have password of MySQL:
mysql -uroot -ppassword mysql ?
I needed one line version for short array:
($array = [1, 2, 3, 4])[mt_rand(0, count($array) - 1)]
or if array is fixed:
[1, 2, 3, 4][mt_rand(0, 3]
If you need to sort the list in-place then you can use the Sort
method, passing a Comparison<T>
delegate:
objListOrder.Sort((x, y) => x.OrderDate.CompareTo(y.OrderDate));
If you prefer to create a new, sorted sequence rather than sort in-place then you can use LINQ's OrderBy
method, as mentioned in the other answers.
Change the field back to numeric and use ZEROFILL
to keep the zeros
or
use LPAD()
SELECT LPAD('1234567', 8, '0');
Your code seems to be fine, make sure that key you specify really exists in the array or such key has a value in your array eg:
$array = array(4 => 'Hello There');
print_r(array_keys($array));
// or better
print_r($array);
Output:
Array
(
[0] => 4
)
Now:
$key = 4;
$value = $array[$key];
print $value;
Output:
Hello There