It labels whatever input is the parameter for the for
attribute.
<input id='myInput' type='radio'>_x000D_
<label for='myInput'>My 1st Radio Label</label>_x000D_
<br>_x000D_
<input id='input2' type='radio'>_x000D_
<label for='input2'>My 2nd Radio Label</label>_x000D_
<br>_x000D_
<input id='input3' type='radio'>_x000D_
<label for='input3'>My 3rd Radio Label</label>
_x000D_
IBAction
and IBOutlet
are macros defined to denote variables and methods that can be referred to in Interface Builder.
IBAction
resolves to void
and IBOutlet
resolves to nothing, but they signify to Xcode and Interface builder that these variables and methods can be used in Interface builder to link UI elements to your code.
If you're not going to be using Interface Builder at all, then you don't need them in your code, but if you are going to use it, then you need to specify IBAction
for methods that will be used in IB and IBOutlet
for objects that will be used in IB.
A shorter version of converting List to Array of specific type (for example Long):
Long[] myArray = myList.toArray(Long[]::new);
I have started writing one tutorial for everyone on this topic, see making gadgets for Windows 7.
You can go without the loop:
find /path/to/dir -type f -exec /your/first/command \{\} \; -exec /your/second/command \{\} \;
HTH
You can try to use the options of --no-cache-dir
together with -I
to overwrite the cache of the previous version and install the new version. For example:
pip3 install --no-cache-dir -I tensorflow==1.1
Then use the following command to check the version of tensorflow:
python3 -c ‘import tensorflow as tf; print(tf.__version__)’
It should show the right version got installed.
In Jenkins 2.60.3 there is a way to delete build artifacts (not the archived artifacts) in order to save hard drive space on the build machine. In the General section, check "Discard old builds" with strategy "Log Rotation" and then go into its Advanced options. Two more options will appear related to keeping build artifacts for the job based on number of days or builds.
The settings that work for me are to enter 1 for "Max # of builds to keep with artifacts" and then to have a post-build action to archive the artifacts. This way, all artifacts from all builds will be archived, all information from builds will be saved, but only the last build will keep its own artifacts.
Use the following code
<span id="sptext" runat="server"></span>
Java Script
document.getElementById('<%=sptext'%>).innerHTML='change text';
C#
sptext.innerHTML
If you are using Logger.getLogger(ClassName.class)
then place your log4j.properties
file in your class path:
yourproject/javaresoures/src/log4j.properties (Put inside src folder)
For a simple count like the OP is showing, the Order by isn't strictly needed. If they are using the result of the subquery, it may be. I am working on a similiar issue and got the same error in the following query:
-- I want the rows from the cost table with an updateddate equal to the max updateddate:
SELECT * FROM #Costs Cost
INNER JOIN
(
SELECT Entityname, costtype, MAX(updatedtime) MaxUpdatedTime
FROM #HoldCosts cost
GROUP BY Entityname, costtype
ORDER BY Entityname, costtype -- *** This causes an error***
) CostsMax
ON Costs.Entityname = CostsMax.entityname
AND Costs.Costtype = CostsMax.Costtype
AND Costs.UpdatedTime = CostsMax.MaxUpdatedtime
ORDER BY Costs.Entityname, Costs.costtype
-- *** To accomplish this, there are a few options:
-- Add an extraneous TOP clause, This seems like a bit of a hack:
SELECT * FROM #Costs Cost
INNER JOIN
(
SELECT TOP 99.999999 PERCENT Entityname, costtype, MAX(updatedtime) MaxUpdatedTime
FROM #HoldCosts cost
GROUP BY Entityname, costtype
ORDER BY Entityname, costtype
) CostsMax
ON Costs.Entityname = CostsMax.entityname
AND Costs.Costtype = CostsMax.Costtype
AND Costs.UpdatedTime = CostsMax.MaxUpdatedtime
ORDER BY Costs.Entityname, Costs.costtype
-- **** Create a temp table to order the maxCost
SELECT Entityname, costtype, MAX(updatedtime) MaxUpdatedTime
INTO #MaxCost
FROM #HoldCosts cost
GROUP BY Entityname, costtype
ORDER BY Entityname, costtype
SELECT * FROM #Costs Cost
INNER JOIN #MaxCost CostsMax
ON Costs.Entityname = CostsMax.entityname
AND Costs.Costtype = CostsMax.Costtype
AND Costs.UpdatedTime = CostsMax.MaxUpdatedtime
ORDER BY Costs.Entityname, costs.costtype
Other possible workarounds could be CTE's or table variables. But each situation requires you to determine what works best for you. I tend to look first towards a temp table. To me, it is clear and straightforward. YMMV.
This is the behavior of ln
if the second arg is a directory. It places a link to the first arg inside it. If you want /etc/nginx
to be the symlink, you should remove that directory first and run that same command.
You can also try:
{
"dateProp": { $gt: new Date('06/15/2016').getTime() }
}
For Mac OS, you can use the following -
/usr/local/opt/gradle/libexec/
or more generically - path/to/gradle/libexec/
- this is recommended. (the first path is what's achieved after installing gradle via Homebrew)/path/to/android/studio/plugins/gradle
- I don't recommend this because this version of Gradle might be out of date, and Android Studio itself might say it's incompatible.All the posted answers rightfully discuss this from a strictly maven perspective. My issues was in doing this install for maven using Netbeans as my primary IDE. I found the below article helpful.
Credit to the following netbeans forum article: http://forums.netbeans.org/topic22907.html
I've used like this
function chatSearchCtrl($scope, $http,$sce) {
// some more my code
// take this
data['message'] = $sce.trustAsHtml(data['message']);
$scope.searchresults = data;
and in html I did
<p class="clsPyType clsChatBoxPadding" ng-bind-html="searchresults.message"></p>
thats it I get my <br/>
tag rendered
def formatE_decimal(x, prec=2):
""" Examples:
>>> formatE_decimal('0.1613965',10)
'1.6139650000E-01'
>>> formatE_decimal('0.1613965',5)
'1.61397E-01'
>>> formatE_decimal('0.9995',2)
'1.00E+00'
"""
xx=decimal.Decimal(x) if type(x)==type("") else x
tup = xx.as_tuple()
xx=xx.quantize( decimal.Decimal("1E{0}".format(len(tup[1])+tup[2]-prec-1)), decimal.ROUND_HALF_UP )
tup = xx.as_tuple()
exp = xx.adjusted()
sign = '-' if tup.sign else ''
dec = ''.join(str(i) for i in tup[1][1:prec+1])
if prec>0:
return '{sign}{int}.{dec}E{exp:+03d}'.format(sign=sign, int=tup[1][0], dec=dec, exp=exp)
elif prec==0:
return '{sign}{int}E{exp:+03d}'.format(sign=sign, int=tup[1][0], exp=exp)
else:
return None
Athul Prakash (age 16 at the time) gave a logical idea for how to implement an OR test by negating the conditions in IF statements and then using the ELSE clause as the location to put the code that requires execution. I thought to myself that there are however two else clauses usually needed since he is suggesting using two IF statements, and so the executed code needs to be written twice. However, if a GOTO is used to skip past the required code, instead of writing ELSE clauses the code for execution only needs to be written once.
Here is a testable example of how I would implement Athul Prakash's negative logic to create an OR.
In my example, someone is allowed to drive a tank if they have a tank licence OR they are doing their military service. Enter true or false at the two prompts and you will be able to see whether the logic allows you to drive a tank.
@ECHO OFF
@SET /p tanklicence=tanklicence:
@SET /p militaryservice=militaryservice:
IF /I NOT %tanklicence%==true IF /I NOT %militaryservice%==true GOTO done
ECHO I am driving a tank with tanklicence set to %tanklicence% and militaryservice set to %militaryservice%
:done
PAUSE
-> is for pointers to a class instance
. is for class instances
:: is for classnames - for example when using a static member
$deleted = $_POST['checkbox'];
$sql = "DELETE FROM $tbl_name WHERE id IN (".implode(",", $deleted ) . ")";
select * from SHOW VARIABLES WHERE Variable_name = 'hostname';
Spaces will not be a problem for cast
, however characters like TAB
, CR
or LF
will appear as spaces, will not be trimmed by LTRIM
or RTRIM
, and will be a problem.
For example try the following:
declare @v1 varchar(21) = '66',
@v2 varchar(21) = ' 66 ',
@v3 varchar(21) = '66' + char(13) + char(10),
@v4 varchar(21) = char(9) + '66'
select cast(@v1 as int) -- ok
select cast(@v2 as int) -- ok
select cast(@v3 as int) -- error
select cast(@v4 as int) -- error
Check your input for these characters and if you find them, use REPLACE
to clean up your data.
Per your comment, you can use REPLACE
as part of your cast
:
select cast(replace(replace(@v3, char(13), ''), char(10), '') as int)
If this is something that will be happening often, it would be better to clean up the data and modify the way the table is populated to remove the CR
and LF
before it is entered.
You need to allow transaction to your DAO method. Add,
@Transactional(readOnly = true, propagation=Propagation.NOT_SUPPORTED)
over your dao methods.
And @Transactional
should be from the package:
org.springframework.transaction.annotation.Transactional
This doesn't work in IE8 but might be an option to consider. It is primarily useful if you do not want to specify a width.
.element
{
position: absolute;
left: 50%;
transform: translateX(-50%);
}
Interactively, you can display it with
help(my_func)
Or from code you can retrieve it with
my_func.__doc__
center
tag aligns the buttons within it as expected:
<ion-footer>
<ion-toolbar>
<center>
<button royal>
Contacts
<ion-icon name="contact"></ion-icon>
</button>
<button secondary>
Receive
<ion-icon name="arrow-round-back"></ion-icon>
</button>
<button danger>
Wallet
<ion-icon name="home"></ion-icon>
</button>
<button secondary>
Send
<ion-icon name="send"></ion-icon>
</button>
<button danger>
Transactions
<ion-icon name="archive"></ion-icon>
</button>
<button danger>
About
<ion-icon name="information-circle"></ion-icon>
</button>
</center>
</ion-toolbar>
</ion-footer>
w3wp.exe is a process associated with the application pool in IIS. If you have more than one application pool, you will have more than one instance of w3wp.exe running. This process usually allocates large amounts of resources. It is important for the stable and secure running of your computer and should not be terminated.
You can get more information on w3wp.exe here
http://www.processlibrary.com/en/directory/files/w3wp/25761/
In my case (I'm using typescript) I was trying to simulate response with fake data where the data is assigned later on. My first attempt was with:
let response = {status: 200, data: []};
and later, on the assignment of the fake data it starts complaining that it is not assignable to type 'never[]'. Then I defined the response like follows and it accepted it..
let dataArr: MyClass[] = [];
let response = {status: 200, data: dataArr};
and assigning of the fake data:
response.data = fakeData;
Something very similar can be seen on http://goo.gl when you shorten the URL.
There is a readonly input element that gets programmatically focused, with tooltip press CTRL-C to copy.
When you hit that shortcut, the input content effectively gets into the clipboard. Really nice :)
You could use HttpWebRequest to get the file and stream it back to the client. This allows you to get the file with a url. An example of this that I found ( but can't remember where to give credit ) is
//Create a stream for the file
Stream stream = null;
//This controls how many bytes to read at a time and send to the client
int bytesToRead = 10000;
// Buffer to read bytes in chunk size specified above
byte[] buffer = new Byte[bytesToRead];
// The number of bytes read
try
{
//Create a WebRequest to get the file
HttpWebRequest fileReq = (HttpWebRequest) HttpWebRequest.Create(url);
//Create a response for this request
HttpWebResponse fileResp = (HttpWebResponse) fileReq.GetResponse();
if (fileReq.ContentLength > 0)
fileResp.ContentLength = fileReq.ContentLength;
//Get the Stream returned from the response
stream = fileResp.GetResponseStream();
// prepare the response to the client. resp is the client Response
var resp = HttpContext.Current.Response;
//Indicate the type of data being sent
resp.ContentType = "application/octet-stream";
//Name the file
resp.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());
int length;
do
{
// Verify that the client is connected.
if (resp.IsClientConnected)
{
// Read data into the buffer.
length = stream.Read(buffer, 0, bytesToRead);
// and write it out to the response's output stream
resp.OutputStream.Write(buffer, 0, length);
// Flush the data
resp.Flush();
//Clear the buffer
buffer = new Byte[bytesToRead];
}
else
{
// cancel the download if client has disconnected
length = -1;
}
} while (length > 0); //Repeat until no data is read
}
finally
{
if (stream != null)
{
//Close the input stream
stream.Close();
}
}
To achieve similar functionality you could use anonymous inner classes.
If you were to define a interface Foo
:
interface Foo {
Object myFunc(Object arg);
}
Create a method bar
which will receive a 'function pointer' as an argument:
public void bar(Foo foo) {
// .....
Object object = foo.myFunc(argValue);
// .....
}
Finally call the method as follows:
bar(new Foo() {
public Object myFunc(Object arg) {
// Function code.
}
}
Try dir /b
, for bare format.
dir /?
will show you documentation of what you can do with the dir
command. Here is the output from my Windows 7 machine:
C:\>dir /?
Displays a list of files and subdirectories in a directory.
DIR [drive:][path][filename] [/A[[:]attributes]] [/B] [/C] [/D] [/L] [/N]
[/O[[:]sortorder]] [/P] [/Q] [/R] [/S] [/T[[:]timefield]] [/W] [/X] [/4]
[drive:][path][filename]
Specifies drive, directory, and/or files to list.
/A Displays files with specified attributes.
attributes D Directories R Read-only files
H Hidden files A Files ready for archiving
S System files I Not content indexed files
L Reparse Points - Prefix meaning not
/B Uses bare format (no heading information or summary).
/C Display the thousand separator in file sizes. This is the
default. Use /-C to disable display of separator.
/D Same as wide but files are list sorted by column.
/L Uses lowercase.
/N New long list format where filenames are on the far right.
/O List by files in sorted order.
sortorder N By name (alphabetic) S By size (smallest first)
E By extension (alphabetic) D By date/time (oldest first)
G Group directories first - Prefix to reverse order
/P Pauses after each screenful of information.
/Q Display the owner of the file.
/R Display alternate data streams of the file.
/S Displays files in specified directory and all subdirectories.
/T Controls which time field displayed or used for sorting
timefield C Creation
A Last Access
W Last Written
/W Uses wide list format.
/X This displays the short names generated for non-8dot3 file
names. The format is that of /N with the short name inserted
before the long name. If no short name is present, blanks are
displayed in its place.
/4 Displays four-digit years
Switches may be preset in the DIRCMD environment variable. Override
preset switches by prefixing any switch with - (hyphen)--for example, /-W.
var path = window.location.pathname;
var page = path.split("/").pop();
console.log( page );
The url you are referring is a query type and I see that the request object supports a method called arguments to get the query arguments. You may also want try self.request.get('def')
directly to get your value from the object..
To answer your question, the current method would be to create the object then call the method:
$functions = new Functions();
$var = $functions->filter($_GET['params']);
Another way would be to make the method static
since the class has no private data to rely on:
public static function filter($data){
This can then be called like so:
$var = Functions::filter($_GET['params']);
Lastly, you do not need a class and can just have a file of functions which you include. So you remove the class Functions
and the public
in the method. This can then be called like you tried:
$var = filter($_GET['params']);
I had this challenge when I was working on a Rails 6 application using Bootstrap 4.
My challenge was that I didn't want this styling to override the default link styling in the application.
So I created a CSS file called custom.css
or custom.scss
.
And then defined a new CSS rule with the following properties:
.remove_link_colour {
a, a:hover, a:focus, a:active {
color: inherit;
text-decoration: none;
}
}
Then I called this rule wherever I needed to override the default link styling.
<div class="product-card__buttons">
<button class="btn btn-success remove_link_colour" type="button"><%= link_to 'Edit', edit_product_path(product) %></button>
<button class="btn btn-danger remove_link_colour" type="button"><%= link_to 'Destroy', product, method: :delete, data: { confirm: 'Are you sure?' } %></button>
</div>
This solves the issue of overriding the default link styling and removes the default colour, hover, focus, and active styling in the buttons only in places where I call the CSS rule.
That's all.
I hope this helps
As Wrikken suggested, it's a valid request. It's also quite common when the client is requesting media or resuming a download.
A client will often test to see if the server handles ranged requests other than just looking for an Accept-Ranges
response. Chrome always sends a Range: bytes=0-
with its first GET request for a video, so it's something you can't dismiss.
Whenever a client includes Range:
in its request, even if it's malformed, it's expecting a partial content (206) response. When you seek forward during HTML5 video playback, the browser only requests the starting point. For example:
Range: bytes=3744-
So, in order for the client to play video properly, your server must be able to handle these incomplete range requests.
You can handle the type of 'range' you specified in your question in two ways:
First, You could reply with the requested starting point given in the response, then the total length of the file minus one (the requested byte range is zero-indexed). For example:
Request:
GET /BigBuckBunny_320x180.mp4
Range: bytes=100-
Response:
206 Partial Content
Content-Type: video/mp4
Content-Length: 64656927
Accept-Ranges: bytes
Content-Range: bytes 100-64656926/64656927
Second, you could reply with the starting point given in the request and an open-ended file length (size). This is for webcasts or other media where the total length is unknown. For example:
Request:
GET /BigBuckBunny_320x180.mp4
Range: bytes=100-
Response:
206 Partial Content
Content-Type: video/mp4
Content-Length: 64656927
Accept-Ranges: bytes
Content-Range: bytes 100-64656926/*
Tips:
You must always respond with the content length included with the range. If the range is complete, with start to end, then the content length is simply the difference:
Request: Range: bytes=500-1000
Response: Content-Range: bytes 500-1000/123456
Remember that the range is zero-indexed, so Range: bytes=0-999
is actually requesting 1000 bytes, not 999, so respond with something like:
Content-Length: 1000
Content-Range: bytes 0-999/123456
Or:
Content-Length: 1000
Content-Range: bytes 0-999/*
But, avoid the latter method if possible because some media players try to figure out the duration from the file size. If your request is for media content, which is my hunch, then you should include its duration in the response. This is done with the following format:
X-Content-Duration: 63.23
This must be a floating point. Unlike Content-Length
, this value doesn't have to be accurate. It's used to help the player seek around the video. If you are streaming a webcast and only have a general idea of how long it will be, it's better to include your estimated duration rather than ignore it altogether. So, for a two-hour webcast, you could include something like:
X-Content-Duration: 7200.00
With some media types, such as webm, you must also include the content-type, such as:
Content-Type: video/webm
All of these are necessary for the media to play properly, especially in HTML5. If you don't give a duration, the player may try to figure out the duration (to allow for seeking) from its file size, but this won't be accurate. This is fine, and necessary for webcasts or live streaming, but not ideal for playback of video files. You can extract the duration using software like FFMPEG and save it in a database or even the filename.
X-Content-Duration
is being phased out in favor of Content-Duration
, so I'd include that too. A basic, response to a "0-" request would include at least the following:
HTTP/1.1 206 Partial Content
Date: Sun, 08 May 2013 06:37:54 GMT
Server: Apache/2.0.52 (Red Hat)
Accept-Ranges: bytes
Content-Length: 3980
Content-Range: bytes 0-3979/3980
Content-Type: video/webm
X-Content-Duration: 2054.53
Content-Duration: 2054.53
One more point: Chrome always starts its first video request with the following:
Range: bytes=0-
Some servers will send a regular 200 response as a reply, which it accepts (but with limited playback options), but try to send a 206 instead to show than your server handles ranges. RFC 2616 says it's acceptable to ignore range headers.
There is no explicit analogue - i think you are expected to use string concatenations(likely optimized as said before) or third-party class(i doubt that they are a lot more efficient - lists in python are dynamic-typed so no fast-working char[] for buffer as i assume). Stringbuilder-like classes are not premature optimization because of innate feature of strings in many languages(immutability) - that allows many optimizations(for example, referencing same buffer for slices/substrings). Stringbuilder/stringbuffer/stringstream-like classes work a lot faster than concatenating strings(producing many small temporary objects that still need allocations and garbage collection) and even string formatting printf-like tools, not needing of interpreting formatting pattern overhead that is pretty consuming for a lot of format calls.
When you try to merge one commit with a commit that can be reached by following the first commit’s history, Git simplifies things by moving the pointer forward because there is no divergent work to merge together – this is called a “fast-forward.”
For more : http://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging
In another way,
If Master has not diverged, instead of creating a new commit, git will just point master to the latest commit of the feature branch. This is a “fast forward.”
There won't be any "merge commit" in fast-forwarding merge.
text-align: center will only work for horizontal centering. For it to be in the complete center, vertical and horizontal you can do the following :
div
{
position: relative;
}
div img
{
position: absolute;
top: 50%;
left: 50%;
margin-left: [-50% of your image's width];
margin-top: [-50% of your image's height];
}
CNCopySupportedInterfaces is no longer deprecated in iOS 10. (API Reference)
You need to import SystemConfiguration/CaptiveNetwork.h and add SystemConfiguration.framework to your target's Linked Libraries (under build phases).
Here is a code snippet in swift (RikiRiocma's Answer):
import Foundation
import SystemConfiguration.CaptiveNetwork
public class SSID {
class func fetchSSIDInfo() -> String {
var currentSSID = ""
if let interfaces = CNCopySupportedInterfaces() {
for i in 0..<CFArrayGetCount(interfaces) {
let interfaceName: UnsafePointer<Void> = CFArrayGetValueAtIndex(interfaces, i)
let rec = unsafeBitCast(interfaceName, AnyObject.self)
let unsafeInterfaceData = CNCopyCurrentNetworkInfo("\(rec)")
if unsafeInterfaceData != nil {
let interfaceData = unsafeInterfaceData! as Dictionary!
currentSSID = interfaceData["SSID"] as! String
}
}
}
return currentSSID
}
}
(Important: CNCopySupportedInterfaces returns nil on simulator.)
For Objective-c, see Esad's answer here and below
+ (NSString *)GetCurrentWifiHotSpotName {
NSString *wifiName = nil;
NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
for (NSString *ifnam in ifs) {
NSDictionary *info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
if (info[@"SSID"]) {
wifiName = info[@"SSID"];
}
}
return wifiName;
}
As of iOS 9 Captive Network is deprecated*. (source)
*No longer deprecated in iOS 10, see above.
It's recommended you use NEHotspotHelper (source)
You will need to email apple at [email protected] and request entitlements. (source)
Sample Code (Not my code. See Pablo A's answer):
for(NEHotspotNetwork *hotspotNetwork in [NEHotspotHelper supportedNetworkInterfaces]) {
NSString *ssid = hotspotNetwork.SSID;
NSString *bssid = hotspotNetwork.BSSID;
BOOL secure = hotspotNetwork.secure;
BOOL autoJoined = hotspotNetwork.autoJoined;
double signalStrength = hotspotNetwork.signalStrength;
}
Side note: Yup, they deprecated CNCopySupportedInterfaces in iOS 9 and reversed their position in iOS 10. I spoke with an Apple networking engineer and the reversal came after so many people filed Radars and spoke out about the issue on the Apple Developer forums.
This isn't really going to help with your more complex issue but I'm posting this anyway because it is a simple solution for people that aren't doing a global search like you are.
I've simplified the regex in the answer to be clearer (this is not a solution to your exact problem).
var re = /^(.+?):"(.+)"$/
var regExResult = re.exec('description:"aoeu"');
var purifiedResult = purify_regex(regExResult);
// We only want the group matches in the array
function purify_regex(reResult){
// Removes the Regex specific values and clones the array to prevent mutation
let purifiedArray = [...reResult];
// Removes the full match value at position 0
purifiedArray.shift();
// Returns a pure array without mutating the original regex result
return purifiedArray;
}
// purifiedResult= ["description", "aoeu"]
That looks more verbose than it is because of the comments, this is what it looks like without comments
var re = /^(.+?):"(.+)"$/
var regExResult = re.exec('description:"aoeu"');
var purifiedResult = purify_regex(regExResult);
function purify_regex(reResult){
let purifiedArray = [...reResult];
purifiedArray.shift();
return purifiedArray;
}
Note that any groups that do not match will be listed in the array as undefined
values.
This solution uses the ES6 spread operator to purify the array of regex specific values. You will need to run your code through Babel if you want IE11 support.
Assuming you want to replace the newlines with something so that something like this:
the quick brown fox\r\n
jumped over the lazy dog\r\n
doesn't end up like this:
the quick brown foxjumped over the lazy dog
I'd do something like this:
string[] SplitIntoChunks(string text, int size)
{
string[] chunk = new string[(text.Length / size) + 1];
int chunkIdx = 0;
for (int offset = 0; offset < text.Length; offset += size)
{
chunk[chunkIdx++] = text.Substring(offset, size);
}
return chunk;
}
string[] GetComments()
{
var cmtTb = GridView1.Rows[rowIndex].FindControl("txtComments") as TextBox;
if (cmtTb == null)
{
return new string[] {};
}
// I assume you don't want to run the text of the two lines together?
var text = cmtTb.Text.Replace(Environment.Newline, " ");
return SplitIntoChunks(text, 50);
}
I apologize if the syntax isn't perfect; I'm not on a machine with C# available right now.
blog_development doesn't exist
You can see this in sql by the 0 rows affected
message
create it in mysql with
mysql> create database blog_development
However as you are using rails you should get used to using
$ rake db:create
to do the same task. It will use your database.yml file settings, which should include something like:
development:
adapter: mysql2
database: blog_development
pool: 5
Also become familiar with:
$ rake db:migrate # Run the database migration
$ rake db:seed # Run thew seeds file create statements
$ rake db:drop # Drop the database
The basic difference between
Blockquote
asymptotically upper bound and asymptotically tight Asym.upperbound means a given algorythm that can executes with maximum amount of time depending upon the number of inputs ,for eg in sorting algo if all the array (n)elements are in descending order then for ascending them it will take a running time of O(n) which shows upper bound complexity ,but if they are already sorted then it will take ohm(1).so we generally used "O"notation for upper bound complexity.
Asym. tightbound bound shows the for eg(c1g(n)<=f(n)<=c2g(n)) shows the tight bound limit such that the function have the value in between two bound (upper bound and lower bound),giving the average case.
I would use an extension method.
public static IEnumerable<T> TakeRandom<T>(this IEnumerable<T> elements, int countToTake)
{
var random = new Random();
var internalList = elements.ToList();
var selected = new List<T>();
for (var i = 0; i < countToTake; ++i)
{
var next = random.Next(0, internalList.Count - selected.Count);
selected.Add(internalList[next]);
internalList[next] = internalList[internalList.Count - selected.Count];
}
return selected;
}
If you use @RestController
you cannot return a view (By using Viewresolver
in Spring/springboot) and yes @ResponseBody
is not needed in this case.
If you use @Controller
you can return a view in Spring web MVC.
Check this code:
Javascript:
app.config( ["$routeProvider"], function($routeProvider){
$routeProvider.when("/part1", {"templateUrl" : "part1"});
$routeProvider.when("/part2", {"templateUrl" : "part2"});
$routeProvider.otherwise({"redirectTo":"/part1"});
}]
);
function HomeFragmentController($scope) {
$scope.$on("$routeChangeSuccess", function (scope, next, current) {
$scope.transitionState = "active"
});
}
CSS:
.fragmentWrapper {
overflow: hidden;
}
.fragment {
position: relative;
-moz-transition-property: left;
-o-transition-property: left;
-webkit-transition-property: left;
transition-property: left;
-moz-transition-duration: 0.1s;
-o-transition-duration: 0.1s;
-webkit-transition-duration: 0.1s;
transition-duration: 0.1s
}
.fragment:not(.active) {
left: 540px;
}
.fragment.active {
left: 0px;
}
Main page HTML:
<div class="fragmentWrapper" data-ng-view data-ng-controller="HomeFragmentController">
</div>
Partials HTML example:
<div id="part1" class="fragment {{transitionState}}">
</div>
A String is a type of Object. So any method that accepts Object as parameter will surely accept String also. Please provide more of your code if you still do not find a solution.
You cannot change the DataType after the Datatable is filled with data. However, you can clone the Data table, change the column type and load data from previous data table to the cloned table as shown below.
DataTable dtCloned = dt.Clone();
dtCloned.Columns[0].DataType = typeof(Int32);
foreach (DataRow row in dt.Rows)
{
dtCloned.ImportRow(row);
}
I try to write working code example, I test it and everything works.
Hare is code:
HTML:
<input type="file" class="attachment_input" name="file" onchange="checkFileSize(this, @Model.MaxSize.ToString(),@Html.Raw(Json.Encode(Model.FileExtensionsList)))" />
Javascript:
//function for check attachment size and extention match
function checkFileSize(element, maxSize, extentionsArray) {
var val = $(element).val(); //get file value
var ext = val.substring(val.lastIndexOf('.') + 1).toLowerCase(); // get file extention
if ($.inArray(ext, extentionsArray) == -1) {
alert('false extension!');
}
var fileSize = ($(element)[0].files[0].size / 1024 / 1024); //size in MB
if (fileSize > maxSize) {
alert("Large file");// if Maxsize from Model > real file size alert this
}
}
Yes, this is confusing...
According to this blog post, it looks like this is an omission from WPF.
To make it work you need to use a style:
<Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
<Border.Style>
<Style>
<Setter Property="Border.Background" Value="Blue"/>
<Style.Triggers>
<Trigger Property="Border.IsMouseOver" Value="True">
<Setter Property="Border.Background" Value="Green" />
</Trigger>
</Style.Triggers>
</Style>
</Border.Style>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
</Border>
I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.
I was experiencing the UnsatisfiedLinkError on Windows 7 64-bit after installing adt-bundle-windows-x86_64-20130717.zip:
Exception in thread "main" java.lang.UnsatisfiedLinkError: no swt-win32-3550 or swt-win32 in swt.library.path, java.library.path or the jar file
The root cause was that McAfee has a feature that blocks loading DLL's from the temporary directory. This is a problem because android.bat copies a bunch of JAR and DLL files to a temporary directory and runs the program from there, to make it easy to upgrade the app in-place.
This feature can be disabled, however. You can either disable "Access Protection" altogether or only disable the feature that blocks loading DLLs from temporary folders.
Plug-in solutions I found were too heavy-weight, so, I made my own jQuery plug-in called Drolex FileStyle.
This plug-in allows you to style file input fields however you want. Actually, you style div elements to look like a tricked out file input, and the actual file input is automatically overlaid with 0% opacity. No additional HTML is required. Just include the css and js files in the page you want Drolex FileStyle and that's it! Edit the css file to your liking. Don't forget the jQuery library if your page doesn't already have it. If the client does not run JavaScript, then the file input will not be modified by js or css.
Tested to work in Chrome 24, Firefox 18, Internet Explorer 9. Expected to work in previous versions of those and others.
How about using inputStreamReader.ready() to find out?
import java.io.InputStreamReader;
/// ...
InputStreamReader reader = new InputStreamReader(inputStream);
if (reader.ready()) {
// do something
}
// ...
>>> import datetime
>>> datetime.date.fromordinal(datetime.date.today().toordinal()-1).strftime("%F")
'2015-05-26'
<div class="overflow-auto p-3 mb-3 mb-md-0 mr-md-3 bg-light" style="max-width: 260px; max-height: 100px;">
<strong>Column 0 </strong><br>
<strong>Column 1</strong><br>
<strong>Column 2</strong><br>
<strong>Column 3</strong><br>
<strong>Column 4</strong><br>
<strong>Column 5</strong><br>
<strong>Column 6</strong><br>
<strong>Column 7</strong><br>
<strong>Column 8</strong><br>
<strong>Column 9</strong><br>
<strong>Column 10</strong><br>
<strong>Column 11</strong><br>
<strong>Column 12</strong><br>
<strong>Column 13</strong><br>
</div>
</div>
If you happen to use CRA with default yarn
package manager use the following. Worked for me.
yarn remove node-sass
yarn add [email protected]
C:\Program Files\Java\jre1.8.0_221\bin worked for me
EDIT: look at this answer. Using np.cumsum
is much faster than np.convolve
A quick and dirty way to smooth data I use, based on a moving average box (by convolution):
x = np.linspace(0,2*np.pi,100)
y = np.sin(x) + np.random.random(100) * 0.8
def smooth(y, box_pts):
box = np.ones(box_pts)/box_pts
y_smooth = np.convolve(y, box, mode='same')
return y_smooth
plot(x, y,'o')
plot(x, smooth(y,3), 'r-', lw=2)
plot(x, smooth(y,19), 'g-', lw=2)
You can also use below code which helps me:
select convert(numeric(10,2), column_name) as Total from TABLE_NAME
where Total
is alias of the field you want.
Using Java 8 Comparator.comparing:
list.sort(Comparator.comparing(Campaign::getName));
If you do not have privilege for "Show Status" then, The best option is to, create two triggers and a new table which keeps the row count of your billion records table.
Example:
TableA >> Billion Records
TableB >> 1 Column and 1 Row
Whenever there is insert query on TableA(InsertTrigger), Increment the row value by 1 TableB
Whenever there is delete query on TableA(DeleteTrigger), Decrement the row value by 1 in TableB
Here are some supplemental examples to see the raw text that Postman passes in the request. You can see this by opening the Postman console:
Header
content-type: multipart/form-data; boundary=--------------------------590299136414163472038474
Body
key1=value1key2=value2
Header
Content-Type: application/x-www-form-urlencoded
Body
key1=value1&key2=value2
Header
Content-Type: text/plain
Body
This is some text.
Header
Content-Type: application/json
Body
{"key1":"value1","key2":"value2"}
You can achieve the solution, by doing this:
JavaScript:
var myValue = document.getElementById("@(ViewBag.CC)").value;
or if you want to use jQuery
, then:
jQuery
var myValue = $('#' + '@(ViewBag.CC)').val();
I know this is old (and I am new to java), but I ran into the same problem. And the answers were not as clear to me as a newbie... so I thought I would add what I learned.
I used a third-party library to aid in the endeavor: org.codehaus.jackson
All of the downloads for this can be found here.
For base JSON functionality, you need to add the following jars to your project's libraries: jackson-mapper-asl and jackson-core-asl
Choose the version your project needs. (Typically you can go with the latest stable build).
Once they are imported in to your project's libraries, add the following import
lines to your code:
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
With the java object defined and assigned values that you wish to convert to JSON and return as part of a RESTful web service
User u = new User();
u.firstName = "Sample";
u.lastName = "User";
u.email = "[email protected]";
ObjectMapper mapper = new ObjectMapper();
try {
// convert user object to json string and return it
return mapper.writeValueAsString(u);
}
catch (JsonGenerationException | JsonMappingException e) {
// catch various errors
e.printStackTrace();
}
The result should looks like this:
{"firstName":"Sample","lastName":"User","email":"[email protected]"}
You can use the contains method
var result = parent.contains(child);
or you can try to use compareDocumentPosition()
var result = nodeA.compareDocumentPosition(nodeB);
The last one is more powerful: it return a bitmask as result.
The fastest way is to do a*a
or a**2
or np.square(a)
whereas np.power(a, 2)
showed to be considerably slower.
np.power()
allows you to use different exponents for each element if instead of 2
you pass another array of exponents. From the comments of @GarethRees I just learned that this function will give you different results than a**2
or a*a
, which become important in cases where you have small tolerances.
I've timed some examples using NumPy 1.9.0 MKL 64 bit, and the results are shown below:
In [29]: a = np.random.random((1000, 1000))
In [30]: timeit a*a
100 loops, best of 3: 2.78 ms per loop
In [31]: timeit a**2
100 loops, best of 3: 2.77 ms per loop
In [32]: timeit np.power(a, 2)
10 loops, best of 3: 71.3 ms per loop
My solution:
#ifdef WIN32
#include <Windows.h>
#include <tchar.h>
#else
#include <unistd.h>
#endif
void GetMachineName(char machineName[150])
{
char Name[150];
int i=0;
#ifdef WIN32
TCHAR infoBuf[150];
DWORD bufCharCount = 150;
memset(Name, 0, 150);
if( GetComputerName( infoBuf, &bufCharCount ) )
{
for(i=0; i<150; i++)
{
Name[i] = infoBuf[i];
}
}
else
{
strcpy(Name, "Unknown_Host_Name");
}
#else
memset(Name, 0, 150);
gethostname(Name, 150);
#endif
strncpy(machineName,Name, 150);
}
This will print the exact line of code in the specific method, which when invoked, raised the exception:
try {
// try code
..
m.invoke(testObject);
..
} catch (InvocationTargetException e) {
// Answer:
e.getCause().printStackTrace();
} catch (Exception e) {
// generic exception handling
e.printStackTrace();
}
You can use some inline CSS like this
<input type="submit" name="submit" style="background: url(images/stack.png); width:100px; height:25px;" />
Should do the magic, also you may wanna do a border:none; to get rid of the standard borders.
You need to set it in the value itself, not in the prepared statement SQL string.
So, this should do for a prefix-match:
notes = notes
.replace("!", "!!")
.replace("%", "!%")
.replace("_", "!_")
.replace("[", "![");
PreparedStatement pstmt = con.prepareStatement(
"SELECT * FROM analysis WHERE notes LIKE ? ESCAPE '!'");
pstmt.setString(1, notes + "%");
or a suffix-match:
pstmt.setString(1, "%" + notes);
or a global match:
pstmt.setString(1, "%" + notes + "%");
select T1.name, count (*)
from (select name from Results
union
select name from Archive_Results) as T1
group by T1.name order by T1.name
I had the same problem, the solution for me is the following.
I had only install the junit.jar file from the web, but this library related with the hacrest-core.jar When I downloaded the hacrest-core.jar file and added it in my project everything works fine.
Issue resolved.!!! Below are the solutions.
For Java 6: Add below jars into {JAVA_HOME}/jre/lib/ext. 1. bcprov-ext-jdk15on-154.jar 2. bcprov-jdk15on-154.jar
Add property into {JAVA_HOME}/jre/lib/security/java.security security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider
Java 7:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
Java 8:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html
Issue is that it is failed to decrypt 256 bits of encryption.
I had this same issue and wondered why it didn't happen with a bitbucket repo that was cloned with https. Looking into it a bit I found that the config for the BB repo had a URL that included my username. So I manually edited the config for my GH repo like so and voila, no more username prompt. I'm on Windows.
Edit your_repo_dir/.git/config
(remember: .git
folder is hidden)
Change:
https://github.com/WEMP/project-slideshow.git
to:
https://*username*@github.com/WEMP/project-slideshow.git
Save the file. Do a git pull
to test it.
The proper way to do this is probably by using git bash commands to edit the setting, but editing the file directly didn't seem to be a problem.
file name
must contain only abc...xyz
012...789
_
.
in Resources folder.
for ex:
my-image.png is False
!
MyImage.png is False
!
my image.png is False
!
...
...
my-xml.xml is False
!
MyXml.xml is False
!
my xml.xml is False
!
...
...
Here is my solution..
In Global.aspx:
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
//direct user to error page
Server.Transfer("~/ErrorPages/Oops.aspx");
}
In Oops.aspx:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadError(Server.GetLastError());
}
protected void LoadError(Exception objError)
{
if (objError != null)
{
StringBuilder lasterror = new StringBuilder();
if (objError.Message != null)
{
lasterror.AppendLine("Message:");
lasterror.AppendLine(objError.Message);
lasterror.AppendLine();
}
if (objError.InnerException != null)
{
lasterror.AppendLine("InnerException:");
lasterror.AppendLine(objError.InnerException.ToString());
lasterror.AppendLine();
}
if (objError.Source != null)
{
lasterror.AppendLine("Source:");
lasterror.AppendLine(objError.Source);
lasterror.AppendLine();
}
if (objError.StackTrace != null)
{
lasterror.AppendLine("StackTrace:");
lasterror.AppendLine(objError.StackTrace);
lasterror.AppendLine();
}
ViewState.Add("LastError", lasterror.ToString());
}
}
protected void btnReportError_Click(object sender, EventArgs e)
{
SendEmail();
}
public void SendEmail()
{
try
{
MailMessage msg = new MailMessage("webteam", "webteam");
StringBuilder body = new StringBuilder();
body.AppendLine("An unexcepted error has occurred.");
body.AppendLine();
body.AppendLine(ViewState["LastError"].ToString());
msg.Subject = "Error";
msg.Body = body.ToString();
msg.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient("exchangeserver");
smtp.Send(msg);
}
catch (Exception ex)
{
lblException.Text = ex.Message;
}
}
JavaScript does not have associative arrays. It has objects.
The following lines of code all do exactly the same thing - set the 'name' field on an object to 'orion'.
var f = new Object(); f.name = 'orion';
var f = new Object(); f['name'] = 'orion';
var f = new Array(); f.name = 'orion';
var f = new Array(); f['name'] = 'orion';
var f = new XMLHttpRequest(); f['name'] = 'orion';
It looks like you have an associative array because an Array
is also an Object
- however you're not actually adding things into the array at all; you're setting fields on the object.
Now that that is cleared up, here is a working solution to your example:
var text = '{ name = oscar }'
var dict = new Object();
// Remove {} and spaces
var cleaned = text.replace(/[{} ]/g, '');
// Split into key and value
var kvp = cleaned.split('=');
// Put in the object
dict[ kvp[0] ] = kvp[1];
alert( dict.name ); // Prints oscar.
If you have created directory and sub-directory, follow the steps below and please keep in mind all directory must have __init__.py
to get it recognized as a directory.
In your script, include import sys
and sys.path
, you will be able to see all the paths available to Python. You must be able to see your current working directory.
Now import sub-directory and respective module that you want to use using: import subdir.subdir.modulename as abc
and now you can use the methods in that module.
As an example, you can see in this screenshot I have one parent directory and two sub-directories and under second sub-directories I have the module CommonFunction
. On the right my console shows that after execution of sys.path
, I can see my working directory.
This new package looks nice http://cran.r-project.org/web/packages/openxlsx/openxlsx.pdf It doesn't require rJava and is using 'Rcpp' for speed.
I was looking for the same behavior using jdbi's BindBeanList and found the syntax is exactly the same as Peter Lang's answer above. In case anybody is running into this question, here's my code:
@SqlUpdate("INSERT INTO table_one (col_one, col_two) VALUES <beans> ON DUPLICATE KEY UPDATE col_one=VALUES(col_one), col_two=VALUES(col_two)")
void insertBeans(@BindBeanList(value = "beans", propertyNames = {"colOne", "colTwo"}) List<Beans> beans);
One key detail to note is that the propertyName you specify within @BindBeanList
annotation is not same as the column name you pass into the VALUES()
call on update.
there are several way, one i would prefer is using a table in html. you can add two coloum three rows table and place the radio buttons and lable.
<table border="0">
<tr>
<td><input type="radio" name="sex" value="1"></td>
<td>radio1</td>
</tr>
<tr>
<td><input type="radio" name="sex" value="2"></td>
<td>radio2</td>
</tr>
</table>
If you are using RemoteDriver things are different. From http://element34.ca/blog/iedriverserver-webdriver-and-python :
You will need to start the server using a line like
java -jar selenium-server-standalone-2.26.0.jar -Dwebdriver.ie.driver=C:\Temp\IEDriverServer.exe
I found that if the IEDriverServer.exe was in C:\Windows\System32\
or its subfolders, it couldn't be found automatically (even though System32 was in the %PATH%
) or explicitly using the -D flag.
function startTime() {
var today = new Date(),
h = checkTime(((today.getHours() + 11) % 12 + 1)),
m = checkTime(today.getMinutes()),
s = checkTime(today.getSeconds());
document.getElementById('demo').innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function () {
startTime()
}, 500);
}
startTime();
})();
05:12:00
This is not necessarily a VBA task - This specific task is easiest sollowed with Auto filter.
1.Insert Auto filter (In Excel 2010 click on home-> (Editing) Sort & Filter -> Filter)
2. Filter on the 'Websites' column
3. Mark the 'none' and delete them
4. Clear filter
In case of image stacks, I find it easier to use scikit-image
to read, and matplotlib
to show or save. I have handled 16-bit TIFF image stacks with the following code.
from skimage import io
import matplotlib.pyplot as plt
# read the image stack
img = io.imread('a_image.tif')
# show the image
plt.imshow(mol,cmap='gray')
plt.axis('off')
# save the image
plt.savefig('output.tif', transparent=True, dpi=300, bbox_inches="tight", pad_inches=0.0)
_.unique
no longer works for the current version of Lodash as version 4.0.0 has this breaking change. The functionality of _.unique
was splitted into _.uniq
, _.sortedUniq
, _.sortedUniqBy
, and _.uniqBy
.
You could use _.uniqBy
like this:
_.uniqBy(data, function (e) {
return e.id;
});
...or like this:
_.uniqBy(data, 'id');
Documentation: https://lodash.com/docs#uniqBy
For older versions of Lodash (< 4.0.0 ):
Assuming that the data should be uniqued by each object's id
property and your data is stored in data
variable, you can use the _.unique()
function like this:
_.unique(data, function (e) {
return e.id;
});
Or simply like this:
_.uniq(data, 'id');
Major difference:
String is immutable. It means that you can't modify a string at all; the result of modification is a new string. This is not effective if you plan to append to a string.
StringBuilder is mutable. It can be modified in any way and it doesn't require creation of a new instance. When the work is done, ToString() can be called to get the string.
Strings can participate in interning. It means that strings with same contents may have same addresses. StringBuilder can't be interned.
String is the only class that can have a reference literal.
git Stash list
List will show all stashed items eg:stash@{0}:,stash@{1}:,..,stash@{n}:
Then select the number n which denotes stash@{n}:
git stash apply n
for example:
git stash apply 1
will apply that particular stashed changes to the current branch
REPEAT
...
UNTIL cond
Is equivalent to
while True:
...
if cond:
break
Use this:
$parameter = $_SERVER['QUERY_STRING'];
echo $parameter;
Or just use:
$parameter = $_GET['link'];
echo $parameter ;
The answer given above can't solve my problem.So I change async into false to get the alert message.
jQuery.ajax({
type:"post",
dataType:"json",
async: false,
url: myAjax.ajaxurl,
data: {action: 'submit_data', info: info},
success: function(data) {
alert("Data was succesfully captured");
},
});
If you're building a class library, then perhaps the users of your library would like to use your library asynchronously. I think that's the biggest reason right there.
You also don't know how your library is going to be used. Perhaps the users will be processing lots and lots of requests, and doing so asynchronously will help it perform faster and more efficient.
If you can do so simply, try not to put the burden on the users of your library trying to make the flow asynchronous when you can take care of it for them.
The only reason I wouldn't use the async version is if I were trying to support an older version of .NET that does not already have built in async support.
Use pyfancy.
Example:
print(pyfancy.RED + "Hello Red!" + pyfancy.END)
How about this:
$ grep -rl "needle text" my_folder | tr '\n' '\0' | xargs -r -0 file | grep -e ':[^:]*text[^:]*$' | grep -v -e 'executable'
If you want the filenames without the file types, just add a final sed
filter.
$ grep -rl "needle text" my_folder | tr '\n' '\0' | xargs -r -0 file | grep -e ':[^:]*text[^:]*$' | grep -v -e 'executable' | sed 's|:[^:]*$||'
You can filter-out unneeded file types by adding more -e 'type'
options to the last grep
command.
EDIT:
If your xargs
version supports the -d
option, the commands above become simpler:
$ grep -rl "needle text" my_folder | xargs -d '\n' -r file | grep -e ':[^:]*text[^:]*$' | grep -v -e 'executable' | sed 's|:[^:]*$||'
You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.
I used CountIf below, but there is lots of different ways to check existence of a value in a range.
Public Sub test()
Dim rng As Range
Dim aNumber As Long
aNumber = 666
Set rng = Sheet5.Range("B16:B615")
If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then
rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)
Else
MsgBox aNumber & " does not exist in range " & rng.Address
End If
End Sub
ALTERNATIVE WAY
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Long
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
If Not IsError(Application.Match(aNumber, rng, 0)) Then
rowNum = Application.Match(aNumber, rng, 0)
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
OR
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Variant
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
rowNum = Application.Match(aNumber, rng, 0)
If Not IsError(rowNum) Then
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
packagingOptions {
exclude 'META-INF/DEPENDENCIES.txt'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
}
The JLS 5, Section 15.18.1.1 JLS 8 § 15.18.1 "String Concatenation Operator +", leading to JLS 8, § 5.1.11 "String Conversion", requires this operation to succeed without failure:
...Now only reference values need to be considered. If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l). Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead.
Let's look at the bytecode! The compiler takes your code:
String s = null;
s = s + "hello";
System.out.println(s); // prints "nullhello"
and compiles it into bytecode as if you had instead written this:
String s = null;
s = new StringBuilder(String.valueOf(s)).append("hello").toString();
System.out.println(s); // prints "nullhello"
(You can do so yourself by using javap -c
)
The append methods of StringBuilder
all handle null just fine. In this case because null
is the first argument, String.valueOf()
is invoked instead since StringBuilder does not have a constructor that takes any arbitrary reference type.
If you were to have done s = "hello" + s
instead, the equivalent code would be:
s = new StringBuilder("hello").append(s).toString();
where in this case the append method takes the null and then delegates it to String.valueOf()
.
Note: String concatenation is actually one of the rare places where the compiler gets to decide which optimization(s) to perform. As such, the "exact equivalent" code may differ from compiler to compiler. This optimization is allowed by JLS, Section 15.18.1.2:
To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.
The compiler I used to determine the "equivalent code" above was Eclipse's compiler, ecj.
If your library is going to be shared among several executables, it often makes sense to make it dynamic to reduce the size of the executables. Otherwise, definitely make it static.
There are several disadvantages of using a dll. There is additional overhead for loading and unloading it. There is also an additional dependency. If you change the dll to make it incompatible with your executalbes, they will stop working. On the other hand, if you change a static library, your compiled executables using the old version will not be affected.
A "sort merge" join is performed by sorting the two data sets to be joined according to the join keys and then merging them together. The merge is very cheap, but the sort can be prohibitively expensive especially if the sort spills to disk. The cost of the sort can be lowered if one of the data sets can be accessed in sorted order via an index, although accessing a high proportion of blocks of a table via an index scan can also be very expensive in comparison to a full table scan.
A hash join is performed by hashing one data set into memory based on join columns and reading the other one and probing the hash table for matches. The hash join is very low cost when the hash table can be held entirely in memory, with the total cost amounting to very little more than the cost of reading the data sets. The cost rises if the hash table has to be spilled to disk in a one-pass sort, and rises considerably for a multipass sort.
(In pre-10g, outer joins from a large to a small table were problematic performance-wise, as the optimiser could not resolve the need to access the smaller table first for a hash join, but the larger table first for an outer join. Consequently hash joins were not available in this situation).
The cost of a hash join can be reduced by partitioning both tables on the join key(s). This allows the optimiser to infer that rows from a partition in one table will only find a match in a particular partition of the other table, and for tables having n partitions the hash join is executed as n independent hash joins. This has the following effects:
You should note that hash joins can only be used for equi-joins, but merge joins are more flexible.
In general, if you are joining large amounts of data in an equi-join then a hash join is going to be a better bet.
This topic is very well covered in the documentation.
http://download.oracle.com/docs/cd/B28359_01/server.111/b28274/optimops.htm#i51523
12.1 docs: https://docs.oracle.com/database/121/TGSQL/tgsql_join.htm
Using a promise race solution will leave the request hanging and still consume bandwidth in the background and lower the max allowed concurrent request being made while it's still in process.
Instead use the AbortController to actually abort the request, Here is an example
const controller = new AbortController()
// 5 second timeout:
const timeoutId = setTimeout(() => controller.abort(), 5000)
fetch(url, { signal: controller.signal }).then(response => {
// completed request before timeout fired
// If you only wanted to timeout the request, not the response, add:
// clearTimeout(timeoutId)
})
AbortController can be used for other things as well, not only fetch but for readable/writable streams as well. More newer functions (specially promise based ones) will use this more and more. NodeJS have also implemented AbortController into its streams/filesystem as well. I know web bluetooth are looking into it also. Now it can also be used with addEventListener option and have it stop listening when the signal ends
Task is like a operation that you wanna perform , Thread helps to manage those operation through multiple process nodes. task is a lightweight option as Threading can lead to a complex code management
I will suggest to read from MSDN(Best in world) always
Task
In my application,above javascript function didnt work,because i had many procrosses inside one page.so following code worked for me hope it helps you guys.
function redirection()
{
<?php $send=$_SERVER['HTTP_REFERER'];?>
var redirect_to="<?php echo $send;?>";
window.location = redirect_to;
}
There is such possibility even if they are not Parent - Child relationship - and that's Flux. There is pretty good (for me personally) implementation for that called Alt.JS (with Alt-Container).
For example you can have Sidebar that is dependent on what is set in component Details. Component Sidebar is connected with SidebarActions and SidebarStore, while Details is DetailsActions and DetailsStore.
You could use then AltContainer like that
<AltContainer stores={{
SidebarStore: SidebarStore
}}>
<Sidebar/>
</AltContainer>
{this.props.content}
Which would keep stores (well I could use "store" instead of "stores" prop). Now, {this.props.content} CAN BE Details depending on the route. Lets say that /Details redirect us to that view. Details would have for example a checkbox that would change Sidebar element from X to Y if it would be checked.
Technically there is no relationship between them and it would be hard to do without flux. BUT WITH THAT it is rather easy.
Now let's get to DetailsActions. We will create there
class SiteActions {
constructor() {
this.generateActions(
'setSiteComponentStore'
);
}
setSiteComponent(value) {
this.dispatch({value: value});
}
}
and DetailsStore
class SiteStore {
constructor() {
this.siteComponents = {
Prop: true
};
this.bindListeners({
setSiteComponent: SidebarActions.COMPONENT_STATUS_CHANGED
})
}
setSiteComponent(data) {
this.siteComponents.Prop = data.value;
}
}
And now, this is the place where magic begin.
As You can see there is bindListener to SidebarActions.ComponentStatusChanged which will be used IF setSiteComponent will be used.
now in SidebarActions
componentStatusChanged(value){
this.dispatch({value: value});
}
We have such thing. It will dispatch that object on call. And it will be called if setSiteComponent in store will be used (that you can use in component for example during onChange on Button ot whatever)
Now in SidebarStore we will have
constructor() {
this.structures = [];
this.bindListeners({
componentStatusChanged: SidebarActions.COMPONENT_STATUS_CHANGED
})
}
componentStatusChanged(data) {
this.waitFor(DetailsStore);
_.findWhere(this.structures[0].elem, {title: 'Example'}).enabled = data.value;
}
Now here you can see, that it will wait for DetailsStore. What does it mean? more or less it means that this method need to wait for DetailsStoreto update before it can update itself.
tl;dr One Store is listening on methods in a store, and will trigger an action from component action, which will update its own store.
I hope it can help you somehow.
I am trying to get int x equal to 5 (as seen in the setNum() method) but when it prints it gives me 0.
To run the code in setNum
you have to call it. If you don't call it, the default value is 0
.
Here is another simpler way to check that.
$memory_limit = return_bytes(ini_get('memory_limit'));
if ($memory_limit < (64 * 1024 * 1024)) {
// Memory insufficient
}
/**
* Converts shorthand memory notation value to bytes
* From http://php.net/manual/en/function.ini-get.php
*
* @param $val Memory size shorthand notation string
*/
function return_bytes($val) {
$val = trim($val);
$last = strtolower($val[strlen($val)-1]);
$val = substr($val, 0, -1);
switch($last) {
// The 'G' modifier is available since PHP 5.1.0
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
return $val;
}
You can't set the field having data-type "text". Only because of that thing you are getting this error. Try to change the data-type with int
The Android Developer pages still state how you can download and use the ADT plugin for Eclipse:
https://dl-ssl.google.com/android/eclipse/
Links for the Eclipse ADT Bundle (found using Archive.org's WayBackMachine) I don't know how future-proof these links are. They all worked on February 27th, 2017.
Update (2015-06-29): Google will end development and official support for ADT in Eclipse at the end of this year and recommends switching to Android Studio.
Mozilla Developer Network has a nice description and example of onbeforeunload.
If you want to warn the user before leaving the page if your page is dirty (i.e. if user has entered some data):
window.addEventListener('beforeunload', function(e) {
var myPageIsDirty = ...; //you implement this logic...
if(myPageIsDirty) {
//following two lines will cause the browser to ask the user if they
//want to leave. The text of this dialog is controlled by the browser.
e.preventDefault(); //per the standard
e.returnValue = ''; //required for Chrome
}
//else: user is allowed to leave without a warning dialog
});
if its something you wish to switch, fading one out and fading another in the same place, you can place a {position:absolute} attribute on the divs, so both the animations play on top of one another, and you don't have to wait for one animation to be over before starting up the next.
The jquery colortip plugin also supports <br>
tags in the title attribute, you might want to look into that one.
Default behaviour of PowerShell is just to dump everything that falls out of a pipeline without being picked up by another pipeline element or being assigned to a variable (or redirected) into Out-Host
. What Out-Host
does is obviously host-dependent.
Just letting things fall out of the pipeline is not a substitute for Write-Host
which exists for the sole reason of outputting text in the host application.
If you want output, then use the Write-*
cmdlets. If you want return values from a function, then just dump the objects there without any cmdlet.
The important thing to note here is that the mime type is not the same as the file extension. Sometimes, however, they have the same value.
https://www.iana.org/assignments/media-types/media-types.xhtml includes a list of registered Mime types, though there is nothing stopping you from making up your own, as long as you are at both the sending and the receiving end. Here is where Microsoft comes in to the picture.
Where there is a lot of confusion is the fact that operating systems have their own way of identifying file types by using the tail end of the file name, referred to as the extension. In modern operating systems, the whole name is one long string, but in more primitive operating systems, it is treated as a separate attribute.
The OS which caused the confusion is MSDOS, which had limited the extension to 3 characters. This limitation is inherited to this day in devices, such as SD cards, which still store data in the same way.
One side effect of this limitation is that some file extensions, such as .gif
match their Mime Type, image/gif
, while others are compromised. This includes image/jpeg
whose extension is shortened to .jpg
. Even in modern Windows, where the limitation is lifted, Microsoft never let the past go, and so the file extension is still the shortened version.
Given that that:
The short answer is:
image/jpg
, so the answer is
that it is not the same as image/jpeg
While we’re at it …
Legacy versions of Internet Explorer took the liberty of uploading jpeg
files with the Mime Type of image/pjpeg
, which, of course, just means more work for everybody else. They also uploaded png
files as image/x-png
.
Note that if you care about speed and do not need to worry about singularities, solve()
should be preferred to ginv()
because it is much faster, as you can check:
require(MASS)
mat <- matrix(rnorm(1e6),nrow=1e3,ncol=1e3)
t0 <- proc.time()
inv0 <- ginv(mat)
proc.time() - t0
t1 <- proc.time()
inv1 <- solve(mat)
proc.time() - t1
Just to clarify, in your 3rd example _myProperty isn't actually a property. It's a field with get and set methods (and as has already been mentioned the get and set methods should specify return types).
In C# the 3rd method should be avoided in most situations. You'd only really use it if the type you wanted to return was an array, or if the get method did a lot of work rather than just returning a value. The latter isn't really necessary but for the purpose of clarity a property's get method that does a lot of work is misleading.
DECIMAL
directive('decimal', function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, element, attr, ctrl) {
function inputValue(val) {
if (val) {
var digits = val.replace(/[^0-9.]/g, '');
if (digits.split('.').length > 2) {
digits = digits.substring(0, digits.length - 1);
}
if (digits !== val) {
ctrl.$setViewValue(digits);
ctrl.$render();
}
return parseFloat(digits);
}
return "";
}
ctrl.$parsers.push(inputValue);
}
};
});
DIGITS
directive('entero', function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, element, attr, ctrl) {
function inputValue(val) {
if (val) {
var value = val + ''; //convert to string
var digits = value.replace(/[^0-9]/g, '');
if (digits !== value) {
ctrl.$setViewValue(digits);
ctrl.$render();
}
return parseInt(digits);
}
return "";
}
ctrl.$parsers.push(inputValue);
}
};
});
Ideally we should do it from either controller or directive as per applicable.
Use $anchorScroll
, $location
as dependency injection.
Then call this two method as
$location.hash('scrollToDivID');
$anchorScroll();
Here scrollToDivID
is the id where you want to scroll.
Assumed you want to navigate to a error message div as
<div id='scrollToDivID'>Your Error Message</div>
For more information please see this documentation
If you're using MySQL Workbench, right-click a table and select alter table
.
In that window you can see your table Engine and also change it.
You would have to convert the int into a string.
# This program calculates a workers gross pay
hours = float(raw_input("Enter hours worked: \n"))
rate = float(raw_input("Enter your hourly rate of pay: \n"))
gross = hours * rate
print "Your gross pay for working " +str(hours)+ " at a rate of " + str(rate) + " hourly is $" + str(gross)
Unless you need to identify the columns automatically, I found this to be the simplest solution:
df$name <- as.factor(df$name)
This makes column name
in dataframe df
a factor.
Google Chrome gives the full height of the page if you call $(window).height()
Instead, use window.innerHeight
to retrieve the height of your window.
Necessary check should be:
if($(window).scrollTop() + window.innerHeight > $(document).height() - 50) {
console.log("reached bottom!");
}
Press Ctrl+Alt+Shift+S in android studio or go to File > Project Structure... Select app on left side and select falvors tab on right side on default config change version code , name and etc...
You could also do that:
In package.json
:
"scripts": {
"cool": "./cool.js"
}
In cool.js
:
console.log({ myVar: process.env.npm_config_myVar });
In CLI:
npm --myVar=something run-script cool
Should output:
{ myVar: 'something' }
Update: Using npm 3.10.3, it appears that it lowercases the process.env.npm_config_
variables? I'm also using better-npm-run
, so I'm not sure if this is vanilla default behavior or not, but this answer is working. Instead of process.env.npm_config_myVar
, try process.env.npm_config_myvar
I just tried this with IE (11) and Chrome (54.0.2794.1 canary SyzyASan):
window.open(url, "_blank", "x=y")
... and it opened in a new window.
Which means that Clint pachl had it right when he said that providing any one parameter will cause the new window to open.
-- and apparently it doesn't have to be a legitimate parameter!
(YMMV - as I said, I only tested it in two places...and the next upgrade might invalidate the results, any way)
ETA: I just noticed, though - in IE, the window has no decorations.
I am currently creating plugins for a retail software brand, which are actually .net class libraries. As a requirement, each plugin needs to be configured using a config file. After a bit of research and testing, I compiled the following class. It does the job flawlessly. Note that I haven't implemented local exception handling in my case because, I catch exceptions at a higher level.
Some tweaking maybe needed to get the decimal point right, in case of decimals and doubles, but it works fine for my CultureInfo...
static class Settings
{
static UriBuilder uri = new UriBuilder(Assembly.GetExecutingAssembly().CodeBase);
static Configuration myDllConfig = ConfigurationManager.OpenExeConfiguration(uri.Path);
static AppSettingsSection AppSettings = (AppSettingsSection)myDllConfig.GetSection("appSettings");
static NumberFormatInfo nfi = new NumberFormatInfo()
{
NumberGroupSeparator = "",
CurrencyDecimalSeparator = "."
};
public static T Setting<T>(string name)
{
return (T)Convert.ChangeType(AppSettings.Settings[name].Value, typeof(T), nfi);
}
}
App.Config file sample
<add key="Enabled" value="true" />
<add key="ExportPath" value="c:\" />
<add key="Seconds" value="25" />
<add key="Ratio" value="0.14" />
Usage:
somebooleanvar = Settings.Setting<bool>("Enabled");
somestringlvar = Settings.Setting<string>("ExportPath");
someintvar = Settings.Setting<int>("Seconds");
somedoublevar = Settings.Setting<double>("Ratio");
Credits to Shadow Wizard & MattC
We can concat same column or also other column of the table.
If you don't want to implement your own wrapper, you can use a queue system, e.g. async.queue, queue.
Check that you have both ngModel and name
attributes in your select. Also Select is a form component and not the entire form so more logical declaration of local reference will be:-
<div class="form-group">
<label for="actionType">Action Type</label>
<select
ngControl="actionType"
===> #actionType="ngModel"
ngModel // You can go with 1 or 2 way binding as well
name="actionType"
id="actionType"
class="form-control"
required>
<option value=""></option>
<option *ngFor="let actionType of actionTypes" value="{{ actionType.label }}">
{{ actionType.label }}
</option>
</select>
</div>
One more Important thing is make sure you import either FormsModule
in the case of template driven approach or ReactiveFormsModule
in the case of Reactive approach. Or you can import both which is also totally fine.
To be more clear, I will begin at the beginning.
I will rely on the sample code found in https://github.com/ExcelDataReader/ExcelDataReader, but with some modifications to avoid inconveniences.
The following code detects the file format, either xls or xlsx.
FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader;
//1. Reading Excel file
if (Path.GetExtension(filePath).ToUpper() == ".XLS")
{
//1.1 Reading from a binary Excel file ('97-2003 format; *.xls)
excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else
{
//1.2 Reading from a OpenXml Excel file (2007 format; *.xlsx)
excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}
//2. DataSet - The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader.AsDataSet();
//3. DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = false;
Now we can access the file contents in a more convenient way. I use DataTable for this. The following is an example to access a specific cell, and print its value in the console:
DataTable dt = result.Tables[0];
Console.WriteLine(dt.Rows[rowPosition][columnPosition]);
If you do not want to do a DataTable, you can do the same as follows:
Console.WriteLine(result.Tables[0].Rows[rowPosition][columnPosition]);
It is important not try to read beyond the limits of the table, for this you can see the number of rows and columns as follows:
Console.WriteLine(result.Tables[0].Rows.Count);
Console.WriteLine(result.Tables[0].Columns.Count);
Finally, when you're done, you should close the reader and free resources:
//5. Free resources (IExcelDataReader is IDisposable)
excelReader.Close();
I hope you find it useful.
(I understand that the question is old, but I make this contribution to enhance the knowledge base, because there is little material about particular implementations of this library).
UPDATED with latest official NuGet documentation as of v3.3.0
NuGet offers three approaches to using package restore.
Automatic Package Restore is the NuGet team's recommended approach to Package Restore within Visual Studio, and it was introduced in NuGet 2.7. Beginning with NuGet 2.7, the NuGet Visual Studio extension integrates into Visual Studio's build events and restores missing packages when a build begins. This feature is enabled by default, but developers can opt out if desired.
Here's how it works:
- On project or solution build, Visual Studio raises an event that a build is beginning within the solution.
- NuGet responds to this event and checks for packages.config files included in the solution.
- For each packages.config file found, its packages are enumerated and Checked for exists in the solution's packages folder.
- Any missing packages are downloaded from the user's configured (and enabled) package sources, respecting the order of the package sources.
- As packages are downloaded, they are unzipped into the solution's packages folder.
If you have Nuget 2.7+ installed; it's important to pick one method for > managing Automatic Package Restore in Visual Studio.
Two methods are available:
- (Nuget 2.7+): Visual Studio -> Tools -> Package Manager -> Package Manager Settings -> Enable Automatic Package Restore
- (Nuget 2.6 and below) Right clicking on a solution and clicking "Enable Package Restore for this solution".
Command-Line Package Restore is required when building a solution from the command-line; it was introduced in early versions of NuGet, but was improved in NuGet 2.7.
nuget.exe restore contoso.sln
The MSBuild-integrated package restore approach is the original Package Restore implementation and though it continues to work in many scenarios, it does not cover the full set of scenarios addressed by the other two approaches.
In order to remove a row from a JTable, you need to remove the target row from the underlying TableModel. If, for instance, your TableModel is an instance of DefaultTableModel, you can remove a row by doing the following:
((DefaultTableModel)myJTable.getModel()).removeRow(rowToRemove);
This worked for me:
sonar.exclusions=src/**/wwwroot/**/*.js,src/**/wwwroot/**/*.css
It excludes any .js and .css files under any of the sub directories of a folder "wwwroot" appearing as one of the sub directories of the "src" folder (project root).
personally I favor validating without a callback:
public bool ValidateSchema(string xmlPath, string xsdPath)
{
XmlDocument xml = new XmlDocument();
xml.Load(xmlPath);
xml.Schemas.Add(null, xsdPath);
try
{
xml.Validate(null);
}
catch (XmlSchemaValidationException)
{
return false;
}
return true;
}
(see Timiz0r's post in Synchronous XML Schema Validation? .NET 3.5)
git pull
wants you to either remove or save your current work so that the merge it triggers doesn't cause conflicts with your uncommitted work. Note that you should only need to remove/save untracked files if the changes you're pulling create files in the same locations as your local uncommitted files.
git checkout -f
git clean -fd
git stash
git stash -u
git pull
:git stash pop
If you want to only update on rows that are not currently uppercase (instead of all rows), you'd need to identify the difference using COLLATE
like this:
UPDATE MyTable
SET MyColumn = UPPER(MyColumn)
WHERE MyColumn != UPPER(MyColumn) COLLATE Latin1_General_CS_AS
Cases sensitivity is based on your collation settings, and is typically case insensitive by default.
Collation can be set at the Server, Database, Column, or Query Level:
-- Server
SELECT SERVERPROPERTY('COLLATION')
-- Database
SELECT name, collation_name FROM sys.databases
-- Column
SELECT COLUMN_NAME, COLLATION_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE CHARACTER_SET_NAME IS NOT NULL
Collation Names specify how a string should be encoded and read, for example:
Latin1_General_CI_AS
? Case InsensitiveLatin1_General_CS_AS
? Case SensitiveAdd the "extern" keyword to the function definitions in point.h
extension Date {
func toString(template: String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = DateFormatter.dateFormat(fromTemplate: template, options: 0, locale: NSLocale.current)
return formatter.string(from: self)
}
}
let now = Date()
let nowStr0 = now.toString(template: "EEEEdMMM") // Tuesday, May 9
let nowStr1 = now.toString(template: "yyyy-MM-dd") // 2017-05-09
let nowStr2 = now.toString(template: "HH:mm:ss") // 17:47:09
Play with template to match your needs. Examples and doc here to help you build the template you need.
You may want to cache your DateFormatter
if you plan to use it in TableView
for instance.
To give an idea, looping over 1000 dates took me 0.5 sec using the above toString(template: String)
function, compared to 0.05 sec using myFormatter.string(from: Date)
.
public static string JSONSerialize<T>(T obj)
{
string retVal = String.Empty;
using (MemoryStream ms = new MemoryStream())
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
serializer.WriteObject(ms, obj);
var byteArray = ms.ToArray();
retVal = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
}
return retVal;
}
Better to use a HashSet
than an ArrayList
when you are checking for existence of a value.
Java docs for HashSet
says: "This class offers constant time performance for the basic operations (add, remove, contains and size)"
ArrayList.contains()
might have to iterate the whole list to find the instance you are looking for.
Avoid using any interval based methods and use MutationObserver targeting a parent div
of dynamically loaded div
for better efficiency.
Here's the simple snippet:
HTML:
<div class="parent-static-div">
<div class="dynamic-loaded-div">
this div is loaded after DOM ready event
</div>
</div>
JS:
var observer = new MutationObserver(function (mutationList, obsrvr) {
var div_to_check = document.querySelector(".dynamic-loaded-div"); //get div by class
// var div_to_check = document.getElementById('div-id'); //get div by id
console.log("checking for div...");
if (div_to_check) {
console.log("div is loaded now"); // DO YOUR STUFF!
obsrvr.disconnect(); // stop observing
return;
}
});
var parentElement = document.querySelector("parent-static-div"); // use parent div which is already present in DOM to maximise efficiency
// var parentElement = document // if not sure about parent div then just use whole 'document'
// start observing for dynamic div
observer.observe(parentElement, {
// for properties details: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserverInit
childList: true,
subtree: true,
});
It means "a python object", i.e. not one of the builtin scalar types supported by numpy.
np.array([object()]).dtype
=> dtype('O')
Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.
The first element in a collection is generally located at index 0
. The last element is at index n-1
, where n
is the Size
of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1
, you're going to get an error.
When you declare an array like this:
var array = new int[6]
The first and last elements in the array are
var firstElement = array[0];
var lastElement = array[5];
So when you write:
var element = array[5];
you are retrieving the sixth element in the array, not the fifth one.
Typically, you would loop over an array like this:
for (int index = 0; index < array.Length; index++)
{
Console.WriteLine(array[index]);
}
This works, because the loop starts at zero, and ends at Length-1
because index
is no longer less than Length
.
This, however, will throw an exception:
for (int index = 0; index <= array.Length; index++)
{
Console.WriteLine(array[index]);
}
Notice the <=
there? index
will now be out of range in the last loop iteration, because the loop thinks that Length
is a valid index, but it is not.
Lists work the same way, except that you generally use Count
instead of Length
. They still start at zero, and end at Count - 1
.
for (int index = 0; i < list.Count; index++)
{
Console.WriteLine(list[index]);
}
However, you can also iterate through a list using foreach
, avoiding the whole problem of indexing entirely:
foreach (var element in list)
{
Console.WriteLine(element.ToString());
}
You cannot index an element that hasn't been added to a collection yet.
var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]); // Throws exception.
How do I make Axios send cookies in requests automatically?
set axios.defaults.withCredentials = true;
or for some specific request you can use axios.get(url,{withCredentials:true})
this will give CORS error if your 'Access-Control-Allow-Origin' is set to wildcard(*). Therefore make sure to specify the url of origin of your request
for ex: if your front-end which makes the request runs on localhost:3000 , then set the response header as
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
also set
res.setHeader('Access-Control-Allow-Credentials',true);
Since PyYAML's yaml.load()
function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:
import yaml
with open('tree.yaml', 'r') as f:
doc = yaml.load(f)
To access branch1 text
you would use:
txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"
because, in your YAML document, the value of the branch1
key is under the treeroot
key.
All of the answers already given are really good and valid (especially Yunus idea of using the mask
property).
However I needed something a little more complex because my layer could often change sizes which mean I needed to call that masking logic every time and this was a little bit annoying.
I used swift extensions
and computed properties to build a real cornerRadii
property which takes care of auto updating the mask when layer is layed out.
This was achieved using Peter Steinberg great Aspects library for swizzling.
Full code is here:
extension CALayer {
// This will hold the keys for the runtime property associations
private struct AssociationKey {
static var CornerRect:Int8 = 1 // for the UIRectCorner argument
static var CornerRadius:Int8 = 2 // for the radius argument
}
// new computed property on CALayer
// You send the corners you want to round (ex. [.TopLeft, .BottomLeft])
// and the radius at which you want the corners to be round
var cornerRadii:(corners: UIRectCorner, radius:CGFloat) {
get {
let number = objc_getAssociatedObject(self, &AssociationKey.CornerRect) as? NSNumber ?? 0
let radius = objc_getAssociatedObject(self, &AssociationKey.CornerRadius) as? NSNumber ?? 0
return (corners: UIRectCorner(rawValue: number.unsignedLongValue), radius: CGFloat(radius.floatValue))
}
set (v) {
let radius = v.radius
let closure:((Void)->Void) = {
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: v.corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.CGPath
self.mask = mask
}
let block: @convention(block) Void -> Void = closure
let objectBlock = unsafeBitCast(block, AnyObject.self)
objc_setAssociatedObject(self, &AssociationKey.CornerRect, NSNumber(unsignedLong: v.corners.rawValue), .OBJC_ASSOCIATION_RETAIN)
objc_setAssociatedObject(self, &AssociationKey.CornerRadius, NSNumber(float: Float(v.radius)), .OBJC_ASSOCIATION_RETAIN)
do { try aspect_hookSelector("layoutSublayers", withOptions: .PositionAfter, usingBlock: objectBlock) }
catch _ { }
}
}
}
I wrote a simple blog post explaining this.
What you should do is to serialize your form data and send it to the controller action. ASP.NET MVC will bind the form data to the EditPostViewModel
object( your action method parameter), using MVC model binding feature.
You can validate your form at client side and if everything is fine, send the data to server. The valid()
method will come in handy.
$(function () {
$("#yourSubmitButtonID").click(function (e) {
e.preventDefault();
var _this = $(this);
var _form = _this.closest("form");
var isvalid = _form .valid(); // Tells whether the form is valid
if (isvalid)
{
$.post(_form.attr("action"), _form.serialize(), function (data) {
//check the result and do whatever you want
})
}
});
});
In my case, the issue was a misconstrued list of command-line arguments. I was doing this in my deployment file:
...
args:
- "--foo 10"
- "--bar 100"
Instead of the correct approach:
...
args:
- "--foo"
- "10"
- "--bar"
- "100"
git rebase origin
means "rebase from the tracking branch of origin
", while git rebase origin/master
means "rebase from the branch master
of origin
"
You must have a tracking branch in ~/Desktop/test
, which means that git rebase origin
knows which branch of origin
to rebase with. If no tracking branch exists (in the case of ~/Desktop/fallstudie
), git doesn't know which branch of origin
it must take, and fails.
To fix this, you can make the branch track origin/master
with:
git branch --set-upstream-to=origin/master
Or, if master
isn't the currently checked-out branch:
git branch --set-upstream-to=origin/master master
Thanks for the links, but it does seem as if the actual text highlighting just isn't exposed.
As far as the actual issue at hand, I ended up opting for a different approach by eliminating the need for a text input altogether and using innerHTML with some JavaScript. Not only does it get around the text highlighting, it actually looks much cleaner.
This granular of a tweak to an HTML form control is just another good argument for eliminating form controls altogether. Haha!
The problem here is the performance, if you have a lot of rows it will be a problem.
If it is your case, please try with this:
import pandas as pd
source = pd.DataFrame({'Country' : ['USA', 'USA', 'Russia','USA'],
'City' : ['New-York', 'New-York', 'Sankt-Petersburg', 'New-York'],
'Short_name' : ['NY','New','Spb','NY']})
source.groupby(['Country','City']).agg(lambda x:x.value_counts().index[0])
source.groupby(['Country','City']).Short_name.value_counts().groupby['Country','City']).first()
I think the importance of the concept "Turing Complete" is in the the ability to identify a computing machine (not necessarily a mechanical/electrical "computer") that can have its processes be deconstructed into "simple" instructions, composed of simpler and simpler instructions, that a Universal machine could interpret and then execute.
I highly recommend The Annotated Turing
@Mark i think what you are explaining is a mix between the description of the Universal Turing Machine and Turing Complete.
Something that is Turing Complete, in a practical sense, would be a machine/process/computation able to be written and represented as a program, to be executed by a Universal Machine (a desktop computer). Though it doesn't take consideration for time or storage, as mentioned by others.
TMTOWTDI, chose the method that best fits how you work. I use the environment method so I don't have to think about it.
In the environment:
export PERL_UNICODE=SDL
on the command line:
perl -CSDL -le 'print "\x{1815}"';
or with binmode:
binmode(STDOUT, ":utf8"); #treat as if it is UTF-8
binmode(STDIN, ":encoding(utf8)"); #actually check if it is UTF-8
or with PerlIO:
open my $fh, ">:utf8", $filename
or die "could not open $filename: $!\n";
open my $fh, "<:encoding(utf-8)", $filename
or die "could not open $filename: $!\n";
or with the open pragma:
use open ":encoding(utf8)";
use open IN => ":encoding(utf8)", OUT => ":utf8";
As for 2018 there is still not a simple answer to the question of how to convert a PDF document to an image in C#; many libraries use Ghostscript licensed under AGPL and in most cases an expensive commercial license is required for production use.
A good alternative might be using the popular 'pdftoppm' utility which has a GPL license; it can be used from C# as command line tool executed with System.Diagnostics.Process. Popular tools are well known in the Linux world, but a windows build is also available.
If you don't want to integrate pdftoppm by yourself, you can use my PdfRenderer popular wrapper (supports both classic .NET Framework and .NET Core) - it is not free, but pricing is very affordable.
You can use the auto_now
and auto_now_add
options for updated_at
and created_at
respectively.
class MyModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
If you use Excel, then the command would be Find and MID. Here is what it would look like in Powershell.
$text = "asdfNAME=PC123456<>Diweursejsfdjiwr"
asdfNAME=PC123456<>Diweursejsfdjiwr - Randon line of text, we want PC123456
$text.IndexOf("E=")
7 - this is the "FIND" command for Powershell
$text.substring(10,5)
C1234 - this is the "MID" command for Powershell
$text.substring($text.IndexOf("E=")+2,8)
PC123456 - tada it has found and cut our text
-RavonTUS
Working for me:
var st = new StackTrace(e, true);
// Get the bottom stack frame
var frame = st.GetFrame(st.FrameCount - 1);
// Get the line number from the stack frame
var line = frame.GetFileLineNumber();
var method = frame.GetMethod().ReflectedType.FullName;
var path = frame.GetFileName();
This is how I solved it without using custom helpers or extensions with .NET core 3.1.
public enum YourEnum
{
[Display(Name = "Suryoye means Arameans")]
SURYOYE = 0,
[Display(Name = "Oromoye means Syriacs")]
OROMOYE = 1,
}
@using Enumerations
foreach (var name in Html.GetEnumSelectList(typeof(YourEnum)))
{
<h1>@name.Text</h1>
}
If you are using curl versions curl-7.19.7-46.el6.x86_64 or older. Please provide an option as -k1 (small K1).
I've developed an almost flawless try & catch implementation in bash, that allows you to write code like:
try
echo 'Hello'
false
echo 'This will not be displayed'
catch
echo "Error in $__EXCEPTION_SOURCE__ at line: $__EXCEPTION_LINE__!"
You can even nest the try-catch blocks inside themselves!
try {
echo 'Hello'
try {
echo 'Nested Hello'
false
echo 'This will not execute'
} catch {
echo "Nested Caught (@ $__EXCEPTION_LINE__)"
}
false
echo 'This will not execute too'
} catch {
echo "Error in $__EXCEPTION_SOURCE__ at line: $__EXCEPTION_LINE__!"
}
The code is a part of my bash boilerplate/framework. It further extends the idea of try & catch with things like error handling with backtrace and exceptions (plus some other nice features).
Here's the code that's responsible just for try & catch:
set -o pipefail
shopt -s expand_aliases
declare -ig __oo__insideTryCatch=0
# if try-catch is nested, then set +e before so the parent handler doesn't catch us
alias try="[[ \$__oo__insideTryCatch -gt 0 ]] && set +e;
__oo__insideTryCatch+=1; ( set -e;
trap \"Exception.Capture \${LINENO}; \" ERR;"
alias catch=" ); Exception.Extract \$? || "
Exception.Capture() {
local script="${BASH_SOURCE[1]#./}"
if [[ ! -f /tmp/stored_exception_source ]]; then
echo "$script" > /tmp/stored_exception_source
fi
if [[ ! -f /tmp/stored_exception_line ]]; then
echo "$1" > /tmp/stored_exception_line
fi
return 0
}
Exception.Extract() {
if [[ $__oo__insideTryCatch -gt 1 ]]
then
set -e
fi
__oo__insideTryCatch+=-1
__EXCEPTION_CATCH__=( $(Exception.GetLastException) )
local retVal=$1
if [[ $retVal -gt 0 ]]
then
# BACKWARDS COMPATIBILE WAY:
# export __EXCEPTION_SOURCE__="${__EXCEPTION_CATCH__[(${#__EXCEPTION_CATCH__[@]}-1)]}"
# export __EXCEPTION_LINE__="${__EXCEPTION_CATCH__[(${#__EXCEPTION_CATCH__[@]}-2)]}"
export __EXCEPTION_SOURCE__="${__EXCEPTION_CATCH__[-1]}"
export __EXCEPTION_LINE__="${__EXCEPTION_CATCH__[-2]}"
export __EXCEPTION__="${__EXCEPTION_CATCH__[@]:0:(${#__EXCEPTION_CATCH__[@]} - 2)}"
return 1 # so that we may continue with a "catch"
fi
}
Exception.GetLastException() {
if [[ -f /tmp/stored_exception ]] && [[ -f /tmp/stored_exception_line ]] && [[ -f /tmp/stored_exception_source ]]
then
cat /tmp/stored_exception
cat /tmp/stored_exception_line
cat /tmp/stored_exception_source
else
echo -e " \n${BASH_LINENO[1]}\n${BASH_SOURCE[2]#./}"
fi
rm -f /tmp/stored_exception /tmp/stored_exception_line /tmp/stored_exception_source
return 0
}
Feel free to use, fork and contribute - it's on GitHub.
This XPath is specific to the code snippet you've provided. To select <child>
with id as #grand
you can write //child[@id='#grand']
.
To get age //child[@id='#grand']/@age
Hope this helps
You might get the error with the latest android gradle plugin (3.0):
Cannot set the value of read-only property 'outputFile'
According to the migration guide, we should use the following approach now:
applicationVariants.all { variant ->
variant.outputs.all {
outputFileName = "${applicationName}_${variant.buildType.name}_${defaultConfig.versionName}.apk"
}
}
Note 2 main changes here:
all
is used now instead of each
to iterate over the variant outputs.outputFileName
property is used instead of mutating a file reference.Another reason may be if you add any html tag before this redirect. Look carefully, you may left DOCTYPE or any html comment before this line.
You could translate spaces to newlines and then grep, e.g.:
cat * | tr ' ' '\n' | grep th
var s = '/Controller/Action?id=11112&value=4444';
s = s.substring(0, s.indexOf('?'));
document.write(s);
I should also mention that native string functions are much faster than regular expressions, which should only really be used when necessary (this isn't one of those cases).
Updated code to account for no '?':
var s = '/Controller/Action';
var n = s.indexOf('?');
s = s.substring(0, n != -1 ? n : s.length);
document.write(s);
Here's a different way of looking at it, and it's a simple one-liner:
int spaces = s.replaceAll("[^ ]", "").length();
This works by effectively removing all non-spaces then taking the length of what’s left (the spaces).
You might want to add a null check:
int spaces = s == null ? 0 : s.replaceAll("[^ ]", "").length();
You can use a stream too:
int spaces = s.chars().filter(c -> c == (int)' ').count();
You can use either jQuery Autocomplete or ASP.NET AJAX Toolkit Autocomplete
# first this
> npm config rm proxy
> npm config rm https-proxy
# then this
> npm config set registry https://registry.npmjs.org/
solved my problem.
Again: Be sure to check whether you have internet connected properly.
Might look excessive but will convert any given format no mater the locale:
function normalizeDecimal($val, int $precision = 4): string
{
$input = str_replace(' ', '', $val);
$number = str_replace(',', '.', $input);
if (strpos($number, '.')) {
$groups = explode('.', str_replace(',', '.', $number));
$lastGroup = array_pop($groups);
$number = implode('', $groups) . '.' . $lastGroup;
}
return bcadd($number, 0, $precision);
}
Output:
.12 -> 0.1200
123 -> 123.0000
123.91 -> 12345678.9100
123 456 78.91 -> 12345678.9100
123,456,78.91 -> 12345678.9100
123.456.78,91 -> 12345678.9100
123 456 78,91 -> 12345678.9100
Write all your code below this 2 lines:-
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
It worked for me without re-installing again.
yes, simply use colspan.
state={
name:"",
email:""
}
handalSubmit = () => {
after api call
let resetFrom = {}
fetch('url')
.then(function(response) {
if(response.success){
resetFrom{
name:"",
email:""
}
}
})
this.setState({...resetFrom})
}
double a,b;
Console.WriteLine("istenen sayiyi sonuna .00 koyarak yaz");
try
{
a = Convert.ToDouble(Console.ReadLine());
b = a * Math.PI;
Console.WriteLine("Sonuç " + b);
}
catch (Exception)
{
Console.WriteLine("dönüstürme hatasi");
throw;
}
The UNION ALL
operator may be what you are looking for.
With this operator, you can concatenate the resultsets from multiple queries together, preserving all of the rows from each. Note that a UNION
operator (without the ALL
keyword) will eliminate any "duplicate" rows which exist in the resultset. The UNION ALL
operator preserves all of the rows from each query (and will likely perform better since it doesn't have the overhead of performing the duplicate check and removal operation).
The number of columns and data type of each column must match in each of the queries. If one of the queries has more columns than the other, we sometimes include dummy expressions in the other query to make the columns and datatypes "match". Often, it's helpful to include an expression (an extra column) in the SELECT list of each query that returns a literal, to reveal which of the queries was the "source" of the row.
SELECT 'q1' AS source, a, b, c, d FROM t1 WHERE ...
UNION ALL
SELECT 'q2', t2.fee, t2.fi, t2.fo, 'fum' FROM t2 JOIN t3 ON ...
UNION ALL
SELECT 'q3', '1', '2', buckle, my_shoe FROM t4
You can wrap a query like this in a set of parenthesis, and use it as an inline view (or "derived table", in MySQL lingo), so that you can perform aggregate operations on all of the rows.
SELECT t.a
, SUM(t.b)
, AVG(t.c)
FROM (
SELECT 'q1' AS source, a, b, c, d FROM t1
UNION ALL
SELECT 'q2', t2.fee, t2.fi, t2.fo, 'fum' FROM t2
) t
GROUP BY t.a
ORDER BY t.a
val jobName = "WordCount";
//overwrite the output directory in spark set("spark.hadoop.validateOutputSpecs", "false")
val conf = new
SparkConf().setAppName(jobName).set("spark.hadoop.validateOutputSpecs", "false");
val sc = new SparkContext(conf)
In short you have to do like this
repositories {
maven { url "http://maven.springframework.org/release" }
maven { url "https://maven.fabric.io/public" }
}
Detail:
You need to specify each maven URL in its own curly braces. Here is what I got working with skeleton dependencies for the web services project I’m going to build up:
apply plugin: 'java'
sourceCompatibility = 1.7
version = '1.0'
repositories {
maven { url "http://maven.springframework.org/release" }
maven { url "http://maven.restlet.org" }
mavenCentral()
}
dependencies {
compile group:'org.restlet.jee', name:'org.restlet', version:'2.1.1'
compile group:'org.restlet.jee', name:'org.restlet.ext.servlet',version.1.1'
compile group:'org.springframework', name:'spring-web', version:'3.2.1.RELEASE'
compile group:'org.slf4j', name:'slf4j-api', version:'1.7.2'
compile group:'ch.qos.logback', name:'logback-core', version:'1.0.9'
testCompile group:'junit', name:'junit', version:'4.11'
}
sending mail in php is not a one-step process. mail() returns true/false, but even if it returns true, it doesn't mean the message is going to be sent. all mail() does is add the message to the queue(using sendmail or whatever you set in php.ini)
there is no reliable way to check if the message has been sent in php. you will have to look through the mail server logs.
Use :
<select onchange="myFunction()">
function myFunction() {
document.querySelectorAll("input[type=submit]")[0].click();
}
I encountered the same problem when doing:
curl -L https://packagecloud.io/golang-migrate/migrate/gpgkey | apt-key add -
The above query needs to be executed using root privileges.
Writing it in following way solved the issue for me:
curl -L https://packagecloud.io/golang-migrate/migrate/gpgkey | sudo apt-key add -
If you write sudo
before curl
, you will get the Failed writing body
error.
Instructions as of Dec 2018:
Now when you open the shortcut it will open in a window without toolbar.
I resolved by removing @Basic(optional = false) property or just update boolean @Basic(optional = true)
addToCart(docId: string, prodId: string): Promise<void> {
return this.baseAngularFirestore.collection('carts').doc(docId).update({
products:
firestore.FieldValue.arrayUnion({
productId: prodId,
qty: 1
}),
});
}
bool IsPalindrome(const char* psz)
{
int i = 0;
int j;
if ((psz == NULL) || (psz[0] == '\0'))
{
return false;
}
j = strlen(psz) - 1;
while (i < j)
{
if (psz[i] != psz[j])
{
return false;
}
i++;
j--;
}
return true;
}
// STL string version:
bool IsPalindrome(const string& str)
{
if (str.empty())
return false;
int i = 0; // first characters
int j = str.length() - 1; // last character
while (i < j)
{
if (str[i] != str[j])
{
return false;
}
i++;
j--;
}
return true;
}
from p in context.ParentTable
join c in context.ChildTable on p.ParentId equals c.ChildParentId into j1
from j2 in j1.DefaultIfEmpty()
group j2 by p.ParentId into grouped
select new { ParentId = grouped.Key, Count = grouped.Count(t=>t.ChildId != null) }
I dont know about SmallSQL, but this works for MSSQL:
IF EXISTS (SELECT * FROM Table1 WHERE Column1='SomeValue')
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
ELSE
INSERT INTO Table1 VALUES (...)
Based on the where-condition, this updates the row if it exists, else it will insert a new one.
I hope that's what you were looking for.
You can add a class to each of your .row
divs to add some space in between them like so:
.spacer {
margin-top: 40px; /* define margin as you see fit */
}
You can then use it like so:
<div class="row spacer">
<div class="span4">...</div>
<div class="span4">...</div>
<div class="span4">...</div>
</div>
<div class="row spacer">
<div class="span4">...</div>
<div class="span4">...</div>
<div class="span4">...</div>
</div>
You could achieve this without having to import traceback:
try:
func1()
except Exception as ex:
trace = []
tb = ex.__traceback__
while tb is not None:
trace.append({
"filename": tb.tb_frame.f_code.co_filename,
"name": tb.tb_frame.f_code.co_name,
"lineno": tb.tb_lineno
})
tb = tb.tb_next
print(str({
'type': type(ex).__name__,
'message': str(ex),
'trace': trace
}))
Output:
{
'type': 'ZeroDivisionError',
'message': 'division by zero',
'trace': [
{
'filename': '/var/playground/main.py',
'name': '<module>',
'lineno': 16
},
{
'filename': '/var/playground/main.py',
'name': 'func1',
'lineno': 11
},
{
'filename': '/var/playground/main.py',
'name': 'func2',
'lineno': 7
},
{
'filename': '/var/playground/my.py',
'name': 'test',
'lineno': 2
}
]
}
When using a VM, I use these steps to inspect changes to the registry:
HKLM\SYSTEM
or HKLM\SOFTWARE
Now use your favourite diff program to compare the 'before' and 'after' snapshots.
This is a really annoying one. What I ended up using is this:
First, create a group of simple buttons with no data-toggle
attribute.
<div id="selector" class="btn-group">
<button type="button" class="btn active">Day</button>
<button type="button" class="btn">Week</button>
<button type="button" class="btn">Month</button>
<button type="button" class="btn">Year</button>
</div>
Next, write an event handler that simulates the radio button effect by 'activating' the clicked one and 'deactivating' all other buttons. (EDIT: Integrated Nick's cleaner version from the comments.)
$('#selector button').click(function() {
$(this).addClass('active').siblings().removeClass('active');
// TODO: insert whatever you want to do with $(this) here
});
Bash has built in features to access the last command executed. But that's the last whole command (e.g. the whole case
command), not individual simple commands like you originally requested.
!:0
= the name of command executed.
!:1
= the first parameter of the previous command
!:*
= all of the parameters of the previous command
!:-1
= the final parameter of the previous command
!!
= the previous command line
etc.
So, the simplest answer to the question is, in fact:
echo !!
...alternatively:
echo "Last command run was ["!:0"] with arguments ["!:*"]"
Try it yourself!
echo this is a test
echo !!
In a script, history expansion is turned off by default, you need to enable it with
set -o history -o histexpand
If you install TFS 2008 PowerTools you will get a "Find in Source Control" action in the Team Explorer right click menu.
There are 2 options to find matching text; string.match
or string.find
.
Both of these perform a regex search on the string to find matches.
string.find()
string.find(subject string, pattern string, optional start position, optional plain flag)
Returns the startIndex
& endIndex
of the substring found.
The plain
flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger)
being interpreted as a regex capture group matching for tiger
, it instead looks for (tiger)
within a string.
Going the other way, if you want to regex match but still want literal special characters (such as .()[]+-
etc.), you can escape them with a percentage; %(tiger%)
.
You will likely use this in combination with string.sub
str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
string.match()
string.match(s, pattern, optional index)
Returns the capture groups found.
str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
From @Johan La Rooy's solution, sorting the images using sorted(glob.glob('*.png'))
does not work for me, the output list is still not ordered by their names.
However, the sorted(glob.glob('*.png'), key=os.path.getmtime)
works perfectly.
I am a bit confused how can sorting by their names does not work here.
Thank @Martin Thoma for posting this great question and @Johan La Rooy for the helpful solutions.
One other easy way of doing it would be as follows (if you have a simple NetBeans project and not using maven for example).
Hi try the following code it will be useful to you,
((ImageView)findViewById(R.id.ImageViewButton)).setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
((ImageView) v.findViewById(R.id.ImageViewButton)).setImageResource(R.drawable.image_over);
if(event.getAction() == MotionEvent.ACTION_UP)
((ImageView) v.findViewById(R.id.ImageViewButton)).setImageResource(R.drawable.image_normal);
return false;
}
});
It's pretty much the same as running a query. In your original code you are creating a command object, putting it in the cmd
variable, and never use it. Here, however, you will use that instead of da.InsertCommand
.
Also, use a using
for all disposable objects, so that you are sure that they are disposed properly:
private void button1_Click(object sender, EventArgs e) {
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd = new SqlCommand("sp_Add_contact", con)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
cmd.Parameters.Add("@LastName", SqlDbType.VarChar).Value = txtLastName.Text;
con.Open();
cmd.ExecuteNonQuery();
}
}
}
Some quick but extremely useful additional information that I just learned from another post, but can't seem to find the documentation for (if anyone can share a link to it on MSDN that would be amazing):
The validation messages associated with these attributes will actually replace placeholders associated with the attributes. For example:
[MaxLength(100, "{0} can have a max of {1} characters")]
public string Address { get; set; }
Will output the following if it is over the character limit: "Address can have a max of 100 characters"
The placeholders I am aware of are:
Much thanks to bloudraak for initially pointing this out.
SELECT * FROM Orders where OrderID % 2 = 0;///this is for even numbers
SELECT * FROM Orders where OrderID % 2 != 0;///this is for odd numbers
Well, in Java an int is a primitive while an Integer is an Object. Meaning, if you made a new Integer:
Integer i = new Integer(6);
You could call some method on i:
String s = i.toString();//sets s the string representation of i
Whereas with an int:
int i = 6;
You cannot call any methods on it, because it is simply a primitive. So:
String s = i.toString();//will not work!!!
would produce an error, because int is not an object.
int is one of the few primitives in Java (along with char and some others). I'm not 100% sure, but I'm thinking that the Integer object more or less just has an int property and a whole bunch of methods to interact with that property (like the toString() method for example). So Integer is a fancy way to work with an int (Just as perhaps String is a fancy way to work with a group of chars).
I know that Java isn't C, but since I've never programmed in C this is the closest I could come to the answer. Hope this helps!
I've encountered this problem very recently. Unfortunately, I had to do 2 tables, one for the header and one for the body. It's probably not the best approach ever but here goes:
<html>_x000D_
<head>_x000D_
<title>oh hai</title>_x000D_
</head>_x000D_
<body>_x000D_
<table id="tableHeader">_x000D_
<tr>_x000D_
<th style="width:100px; background-color:#CCCCCC">col header</th>_x000D_
<th style="width:100px; background-color:#CCCCCC">col header</th>_x000D_
</tr>_x000D_
</table>_x000D_
<div style="height:50px; overflow:auto; width:250px">_x000D_
<table>_x000D_
<tr>_x000D_
<td style="height:50px; width:100px; background-color:#DDDDDD">data1</td>_x000D_
<td style="height:50px; width:100px; background-color:#DDDDDD">data1</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td style="height:50px; width:100px; background-color:#DDDDDD">data2</td>_x000D_
<td style="height:50px; width:100px; background-color:#DDDDDD">data2</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
This worked for me, it's probably not the elegant way but it does work. I'll investigate so see if I can do something better, but it allows for multiple tables.
Go read on the overflow propriety to see if it fits your need
fig = plt.figure()
ax = fig.add_subplot(111)
plt.xticks([0.4,0.14,0.2,0.2], fontsize = 50) # work on current fig
plt.show()
the x/yticks has the same properties as matplotlib.text
Look up \enlargethispage
in some LaTeX reference.