so simple try this
<div dir="ltr" style="text-align: left;" trbidi="on">_x000D_
<!-- begin snippet: js hide: false console: true babel: null -->
_x000D_
Actually I'd bet this would be rather simple to achieve. It probably wouldn't operate or look exactly like what Apple has going on but could be very close.
First of all, you'd need to determine the CGRect of the UIView that you will be presenting. Once you've determine that you would just need to grab an image of the part of the UI so that it can be blurred. Something like this...
- (UIImage*)getBlurredImage {
// You will want to calculate this in code based on the view you will be presenting.
CGSize size = CGSizeMake(200,200);
UIGraphicsBeginImageContext(size);
[view drawViewHierarchyInRect:(CGRect){CGPointZero, w, h} afterScreenUpdates:YES]; // view is the view you are grabbing the screen shot of. The view that is to be blurred.
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// Gaussian Blur
image = [image applyLightEffect];
// Box Blur
// image = [image boxblurImageWithBlur:0.2f];
return image;
}
Using the UIImage+ImageEffects
Category Apple's provided here, you'll get a gaussian blur that looks very much like the blur in iOS 7.
You could also use a box blur using the following boxBlurImageWithBlur:
UIImage category. This is based on an algorythem that you can find here.
@implementation UIImage (Blur)
-(UIImage *)boxblurImageWithBlur:(CGFloat)blur {
if (blur < 0.f || blur > 1.f) {
blur = 0.5f;
}
int boxSize = (int)(blur * 50);
boxSize = boxSize - (boxSize % 2) + 1;
CGImageRef img = self.CGImage;
vImage_Buffer inBuffer, outBuffer;
vImage_Error error;
void *pixelBuffer;
CGDataProviderRef inProvider = CGImageGetDataProvider(img);
CFDataRef inBitmapData = CGDataProviderCopyData(inProvider);
inBuffer.width = CGImageGetWidth(img);
inBuffer.height = CGImageGetHeight(img);
inBuffer.rowBytes = CGImageGetBytesPerRow(img);
inBuffer.data = (void*)CFDataGetBytePtr(inBitmapData);
pixelBuffer = malloc(CGImageGetBytesPerRow(img) * CGImageGetHeight(img));
if(pixelBuffer == NULL)
NSLog(@"No pixelbuffer");
outBuffer.data = pixelBuffer;
outBuffer.width = CGImageGetWidth(img);
outBuffer.height = CGImageGetHeight(img);
outBuffer.rowBytes = CGImageGetBytesPerRow(img);
error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend);
if (error) {
NSLog(@"JFDepthView: error from convolution %ld", error);
}
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef ctx = CGBitmapContextCreate(outBuffer.data,
outBuffer.width,
outBuffer.height,
8,
outBuffer.rowBytes,
colorSpace,
kCGImageAlphaNoneSkipLast);
CGImageRef imageRef = CGBitmapContextCreateImage (ctx);
UIImage *returnImage = [UIImage imageWithCGImage:imageRef];
//clean up
CGContextRelease(ctx);
CGColorSpaceRelease(colorSpace);
free(pixelBuffer);
CFRelease(inBitmapData);
CGImageRelease(imageRef);
return returnImage;
}
@end
Now that you are calculating the screen area to blur, passing it into the blur category and receiving a UIImage back that has been blurred, now all that is left is to set that blurred image as the background of the view you will be presenting. Like I said, this will not be a perfect match for what Apple is doing, but it should still look pretty cool.
Hope it helps.
If this question is from the interviewer then please DONT USE SORTING Technique or Don't use any built in methods like Arrays.sort or Collection.sort. The purpose of this questions is how optimal your solution is in terms of performance so the best option would be just implement with your own logic with O(n-1) implementation. The below code is strictly for beginners and not for experienced guys.
public void printLargest(){
int num[] ={ 900,90,6,7,5000,4,60000,20,3};
int largest = num[0];
int secondLargest = num[1];
for (int i=1; i<num.length; i++)
{
if(largest < num[i])
{
secondLargest = largest;
largest = num[i];
}
else if(secondLargest < num[i]){
secondLargest = num[i];
}
}
System.out.println("Largest : " +largest);
System.out.println("Second Largest : "+secondLargest);
}
To call a SOAP web Service from android , try to use this client
DON'T FORGET TO ADD ksoap2-android.jar in your java build path
public class WsClient {
private static final String SOAP_ACTION = "somme";
private static final String OPERATION_NAME = "somme";
private static final String WSDL_TARGET_NAMESPACE = "http://example.ws";
private static final String SOAP_ADDRESS = "http://192.168.1.2:8080/axis2/services/Calculatrice?wsdl";
public String caclculerSomme() {
String res = null;
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,
OPERATION_NAME);
request.addProperty("a", "5");
request.addProperty("b", "2");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
try {
httpTransport.call(SOAP_ACTION, envelope);
String result = envelope.getResponse().toString();
res = result;
System.out.println("############# resull is :" + result);
} catch (Exception exception) {
System.out.println("########### ERRER" + exception.getMessage());
}
return res;
}
}
just use scrollTo plugin
$("document").ready(function(){
$(window).scrollTo("#div")
})
Your question has 2 tasks to be performed. First to extract the Email attachments to a folder and saving or renaming it with a specific name.
If your search can be split to 2 searches you will get more hits. I could refer one page that explains how to save the attachment to a system folder <Link for the page to save attachments to a folder>.
Please post any page or code if you have found to save the attachment with specific name.
sed -i.bak 's/\(aaa=\).*/\1"xxx"/g' your_file
Have you tried what is on the sample. I am new to this but here is the command: puppet --test --trace --debug. I hope this helps.
Thanks for enlightening us Cypawer.
I also tried this app https://play.google.com/store/apps/details?id=com.oneguyinabasement.leapwifi
and it worked flawlessly.
Try this:
System.Configuration.ConfigurationFileMap fileMap = new ConfigurationFileMap(strConfigPath); //Path to your config file
System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
I understand that IE9 still won't be supporting CSS gradients. Which is a shame, because it's supporting loads of other great new stuff.
You might want to look into CSS3Pie as a way of getting all versions of IE to support various CSS3 features (including gradients, but also border-radius and box-shadow) with the minimum of fuss.
I believe CSS3Pie works with IE9 (I've tried it on the pre-release versions, but not yet on the current beta).
Facebook's watchman, available via Homebrew, also looks nice. It supports also filtering:
These two lines establish a watch on a source directory and then set up a trigger named "buildme" that will run a tool named "minify-css" whenever a CSS file is changed. The tool will be passed a list of the changed filenames.
$ watchman watch ~/src
$ watchman -- trigger ~/src buildme '*.css' -- minify-css
Notice that the path must be absolute.
LFTP is great, however it is Linux only. You can find the Windows port here. Never tried though.
Achtunq, it uses Cygwin, but everything is included in the bundle.
Using either powers of 1000 or kibibytes would be more standard-friendly:
def sizeof_fmt(num, use_kibibyte=True):
base, suffix = [(1000.,'B'),(1024.,'iB')][use_kibibyte]
for x in ['B'] + map(lambda x: x+suffix, list('kMGTP')):
if -base < num < base:
return "%3.1f %s" % (num, x)
num /= base
return "%3.1f %s" % (num, x)
P.S. Never trust a library that prints thousands with the K (uppercase) suffix :)
If you want to implement that yourself, the OAuth 2.0 flow for Web Server Applications is documented at https://developers.google.com/accounts/docs/OAuth2WebServer, in particular you should check the section about using a refresh token:
https://developers.google.com/accounts/docs/OAuth2WebServer#refresh
You're looking for $select.html()
Please check if postgres(or any other database service) is running properly.
As of Java 8 and Stream API you can use Arrays.stream
and Collectors.toList
:
String[] array = new String[]{"a", "b", "c"};
List<String> list = Arrays.stream(array).collect(Collectors.toList());
This is practical especially if you intend to perform further operations on the list.
String[] array = new String[]{"a", "bb", "ccc"};
List<String> list = Arrays.stream(array)
.filter(str -> str.length() > 1)
.map(str -> str + "!")
.collect(Collectors.toList());
Adapted from this post on Processing JSON with jq, you can use the select(bool)
like this:
$ jq '.[] | select(.location=="Stockholm")' json
{
"location": "Stockholm",
"name": "Walt"
}
{
"location": "Stockholm",
"name": "Donald"
}
Remember that collections in C# are zero-based (in other words, the first item in a collection is at position zero). If you have two items in your list, and you want to select the last item, use SelectedIndex = 1
.
#!/usr/bin/env python
import smtplib
class Gmail(object):
def __init__(self, email, password):
self.email = email
self.password = password
self.server = 'smtp.gmail.com'
self.port = 587
session = smtplib.SMTP(self.server, self.port)
session.ehlo()
session.starttls()
session.ehlo
session.login(self.email, self.password)
self.session = session
def send_message(self, subject, body):
''' This must be removed '''
headers = [
"From: " + self.email,
"Subject: " + subject,
"To: " + self.email,
"MIME-Version: 1.0",
"Content-Type: text/html"]
headers = "\r\n".join(headers)
self.session.sendmail(
self.email,
self.email,
headers + "\r\n\r\n" + body)
gm = Gmail('Your Email', 'Password')
gm.send_message('Subject', 'Message')
I was having the same sort of problem. Apparently it's simply because PHP doesn't recognise utf-8.
I was tearing my hair out at first when a '£' sign kept showing up as '£', despite it appearing ok in DreamWeaver. Eventually I remembered I had been having problems with links relative to the index file, when the pages, if viewed directly would work with slideshows, but not when used with an include (but that's beside the point. Anyway I wondered if this might be a similar problem, so instead of putting into the page that I was having problems with, I simply put it into the index.php file - problem fixed throughout.
Rotating image is one thing, proper image boundaries in another. Here is a code which can help anyone. I created this based on some search on internet long ago.
/// <summary>
/// Rotates image in radian angle
/// </summary>
/// <param name="bmpSrc"></param>
/// <param name="theta">in radian</param>
/// <param name="extendedBitmapBackground">Because of rotation returned bitmap can have different boundaries from original bitmap. This color is used for filling extra space in bitmap</param>
/// <returns></returns>
public static Bitmap RotateImage(Bitmap bmpSrc, double theta, Color? extendedBitmapBackground = null)
{
theta = Convert.ToSingle(theta * 180 / Math.PI);
Matrix mRotate = new Matrix();
mRotate.Translate(bmpSrc.Width / -2, bmpSrc.Height / -2, MatrixOrder.Append);
mRotate.RotateAt((float)theta, new Point(0, 0), MatrixOrder.Append);
using (GraphicsPath gp = new GraphicsPath())
{ // transform image points by rotation matrix
gp.AddPolygon(new Point[] { new Point(0, 0), new Point(bmpSrc.Width, 0), new Point(0, bmpSrc.Height) });
gp.Transform(mRotate);
PointF[] pts = gp.PathPoints;
// create destination bitmap sized to contain rotated source image
Rectangle bbox = BoundingBox(bmpSrc, mRotate);
Bitmap bmpDest = new Bitmap(bbox.Width, bbox.Height);
using (Graphics gDest = Graphics.FromImage(bmpDest))
{
if (extendedBitmapBackground != null)
{
gDest.Clear(extendedBitmapBackground.Value);
}
// draw source into dest
Matrix mDest = new Matrix();
mDest.Translate(bmpDest.Width / 2, bmpDest.Height / 2, MatrixOrder.Append);
gDest.Transform = mDest;
gDest.DrawImage(bmpSrc, pts);
return bmpDest;
}
}
}
private static Rectangle BoundingBox(Image img, Matrix matrix)
{
GraphicsUnit gu = new GraphicsUnit();
Rectangle rImg = Rectangle.Round(img.GetBounds(ref gu));
// Transform the four points of the image, to get the resized bounding box.
Point topLeft = new Point(rImg.Left, rImg.Top);
Point topRight = new Point(rImg.Right, rImg.Top);
Point bottomRight = new Point(rImg.Right, rImg.Bottom);
Point bottomLeft = new Point(rImg.Left, rImg.Bottom);
Point[] points = new Point[] { topLeft, topRight, bottomRight, bottomLeft };
GraphicsPath gp = new GraphicsPath(points, new byte[] { (byte)PathPointType.Start, (byte)PathPointType.Line, (byte)PathPointType.Line, (byte)PathPointType.Line });
gp.Transform(matrix);
return Rectangle.Round(gp.GetBounds());
}
When you make the call to gcc it should say
g++ -Wall -I/home/alwin/Development/Calculator/ -L/opt/lib main.cpp -lcalc -o calculator
not -libcalc.so
I have a similar problem with auto-generated makes.
You can create a soft link from your compile directory to the library directory. Then the library becomes "local".
cd /compile/directory
ln -s /path/to/libcalc.so libcalc.so
Just to clarify the problem here - the error is in the following bit of code:
<xsl:attribute name="src">
<xsl:copy-of select="/root/Image/node()"/>
</xsl:attribute>
The instruction xsl:copy-of takes a node or node-set and makes a copy of it - outputting a node or node-set. However an attribute cannot contain a node, only a textual value, so xsl:value-of would be a possible solution (as this returns the textual value of a node or nodeset).
A MUCH shorter solution (and perhaps more elegant) would be the following:
<img width="100" height="100" src="{/root/Image/node()}" class="CalloutRightPhoto"/>
The use of the {} in the attribute is called an Attribute Value Template, and can contain any XPATH expression.
Note, the same XPath can be used here as you have used in the xsl_copy-of as it knows to take the textual value when used in a Attribute Value Template.
Make sure you format the string like this or it wont work
$content = "BEGIN:VCALENDAR\n".
"VERSION:2.0\n".
"PRODID:-//hacksw/handcal//NONSGML v1.0//EN\n".
"BEGIN:VEVENT\n".
"UID:".uniqid()."\n".
"DTSTAMP:".$time."\n".
"DTSTART:".$time."\n".
"DTEND:".$time."\n".
"SUMMARY:".$summary."\n".
"END:VEVENT\n".
"END:VCALENDAR";
The other methods here didn't work for me, so here's what does work in Ubuntu 12.04 'precise'.
On Ubuntu and other Debian-derived platforms, dpkg is the typical way to get software package versions. For more recent versions than the one that @Tio refers to, use
dpkg -l | grep libopencv
If you have the development packages installed, like libopencv-core-dev
, you'll probably have .pc
files and can use pkg-config
:
pkg-config --modversion opencv
For example this plugIns:
Just search for under cursor in vimawesome.com
The key, as clagccs mentioned, is that the highlight does NOT conflict with your search: https://vim.fandom.com/wiki/Auto_highlight_current_word_when_idle
Screen-shot of how it does NOT conflict with search: Notes:
JPA is JSR i.e. Java Specification Requirement to implement Object Relational Mapping which has got no specific code for its implementation. It defines certain set of rules for for accessing, persisting and managing the data between Java objects and the relational databaseWith its introduction, EJB was replaced as It was criticized for being heavyweight by the Java developer community. Hibernate is one of the way JPA can be implemented using te guidelines.Hibernate is a high-performance Object/Relational persistence and query service which is licensed under the open source GNU Lesser General Public License (LGPL) .The benefit of this is that you can swap out Hibernate's implementation of JPA for another implementation of the JPA specification. When you use straight Hibernate you are locking into the implementation because other ORMs may use different methods/configurations and annotations, therefore you cannot just switch over to another ORM.
Check out the implode() function as an alternative. This will convert the array into a list. The first param is how you want the items separated. Here I have used a comma with a space after it.
$invite = implode(', ', $_POST['invite']);
echo $invite;
In some (very specific) situations this might be achieved by using a filter. For example, you can change a blue SVG image to purple by rotating the hue 45 degrees using filter: hue-rotate(45deg);
. Browser support is minimal but it's still an interesting technique.
How about this? I needed the exact same thing, I had to create one from scratch. It's PURE CSS, and works in IE9+ Feel-free to improve upon it.
Demo: http://www.d-k-j.com/Articles/Web_Development/Pure_CSS_5_Star_Rating_System_with_Radios/
<ul class="form">
<li class="rating">
<input type="radio" name="rating" value="0" checked /><span class="hide"></span>
<input type="radio" name="rating" value="1" /><span></span>
<input type="radio" name="rating" value="2" /><span></span>
<input type="radio" name="rating" value="3" /><span></span>
<input type="radio" name="rating" value="4" /><span></span>
<input type="radio" name="rating" value="5" /><span></span>
</li>
</ul>
CSS:
.form {
margin:0;
}
.form li {
list-style:none;
}
.hide {
display:none;
}
.rating input[type="radio"] {
position:absolute;
filter:alpha(opacity=0);
-moz-opacity:0;
-khtml-opacity:0;
opacity:0;
cursor:pointer;
width:17px;
}
.rating span {
width:24px;
height:16px;
line-height:16px;
padding:1px 22px 1px 0; /* 1px FireFox fix */
background:url(stars.png) no-repeat -22px 0;
}
.rating input[type="radio"]:checked + span {
background-position:-22px 0;
}
.rating input[type="radio"]:checked + span ~ span {
background-position:0 0;
}
The name
attribute on an input is used by its parent HTML <form>
s to include that element as a member of the HTTP form in a POST
request or the query string in a GET
request.
The id
should be unique as it should be used by JavaScript to select the element in the DOM for manipulation and used in CSS selectors.
if (list.Count > desiredIndex && list[desiredIndex] != null)
{
// logic
}
you could use datetime
library to get UTC time even local time.
import datetime
utc_time = datetime.datetime.utcnow()
print(utc_time.strftime('%Y%m%d %H%M%S'))
I cleared this error by deleting the red .framework
files that were located in a folder Frameworks
in the project navigator
. I think this also automatically deleted corresponding red entries in the Linked Frameworks and Libraries
section of the General
settings.
I have been cleaning / reinstalling pods in order to fix another issue. Perhaps these red framework files and entries were just leftover from a previous pod install?
Another reason can be that if you are running the service (API) and put a breakpoint in the service (and your code is stuck at some breakpoint (e.g Visual Studio solution is showing Debugging instead of Running)). and then hitting the API from the client code. So if the service code a paused on some breakpoint, you just hit F5 in VS.
You have multiple ways to set :
as the separator:
awk -F: '{print $1}'
awk -v FS=: '{print $1}'
awk '{print $1}' FS=:
awk 'BEGIN{FS=":"} {print $1}'
All of them are equivalent and will return 1
given a sample input "1:2:3":
$ awk -F: '{print $1}' <<< "1:2:3"
1
$ awk -v FS=: '{print $1}' <<< "1:2:3"
1
$ awk '{print $1}' FS=: <<< "1:2:3"
1
$ awk 'BEGIN{FS=":"} {print $1}' <<< "1:2:3"
1
BitmapFactory.decodeResource()
automatically scales the bitmap, so your bitmap may turn out fuzzy. To prevent scaling, do this:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
Bitmap source = BitmapFactory.decodeResource(context.getResources(),
R.drawable.resource_name, options);
or
InputStream is = context.getResources().openRawResource(R.drawable.resource_name)
bitmap = BitmapFactory.decodeStream(is);
There are two different Lambda integrations you can configure in API Gateway, such as Lambda integration and Lambda proxy integration. For Lambda integration, you can customise what you are going to pass to Lambda in the payload that you don't need to parse the body, but when you are using Lambda Proxy integration in API Gateway, API Gateway will proxy everything to Lambda in payload like this,
{
"message": "Hello me!",
"input": {
"path": "/test/hello",
"headers": {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, lzma, sdch, br",
"Accept-Language": "en-US,en;q=0.8",
"CloudFront-Forwarded-Proto": "https",
"CloudFront-Is-Desktop-Viewer": "true",
"CloudFront-Is-Mobile-Viewer": "false",
"CloudFront-Is-SmartTV-Viewer": "false",
"CloudFront-Is-Tablet-Viewer": "false",
"CloudFront-Viewer-Country": "US",
"Host": "wt6mne2s9k.execute-api.us-west-2.amazonaws.com",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 OPR/39.0.2256.48",
"Via": "1.1 fb7cca60f0ecd82ce07790c9c5eef16c.cloudfront.net (CloudFront)",
"X-Amz-Cf-Id": "nBsWBOrSHMgnaROZJK1wGCZ9PcRcSpq_oSXZNQwQ10OTZL4cimZo3g==",
"X-Forwarded-For": "192.168.100.1, 192.168.1.1",
"X-Forwarded-Port": "443",
"X-Forwarded-Proto": "https"
},
"pathParameters": {"proxy": "hello"},
"requestContext": {
"accountId": "123456789012",
"resourceId": "us4z18",
"stage": "test",
"requestId": "41b45ea3-70b5-11e6-b7bd-69b5aaebc7d9",
"identity": {
"cognitoIdentityPoolId": "",
"accountId": "",
"cognitoIdentityId": "",
"caller": "",
"apiKey": "",
"sourceIp": "192.168.100.1",
"cognitoAuthenticationType": "",
"cognitoAuthenticationProvider": "",
"userArn": "",
"userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 OPR/39.0.2256.48",
"user": ""
},
"resourcePath": "/{proxy+}",
"httpMethod": "GET",
"apiId": "wt6mne2s9k"
},
"resource": "/{proxy+}",
"httpMethod": "GET",
"queryStringParameters": {"name": "me"},
"stageVariables": {"stageVarName": "stageVarValue"},
"body": "{\"foo\":\"bar\"}",
"isBase64Encoded": false
}
}
For the example you are referencing, it is not getting the body from the original request. It is constructing the response body back to API Gateway. It should be in this format,
{
"statusCode": httpStatusCode,
"headers": { "headerName": "headerValue", ... },
"body": "...",
"isBase64Encoded": false
}
it is just that add below code in the index.html head tag
<html>
<head>
<base href="/">
...
that worked like a charm for me.
You can try running Autoruns, which would save you from having to edit the registry by hand. This is especially useful when you don't have the needed permissions.
If you want to use scrollWidth to get the "REAL" CONTENT WIDTH/HEIGHT (as content can be BIGGER than the css-defined width/height-Box) the scrollWidth/Height is very UNRELIABLE as some browser seem to "MOVE" the paddingRIGHT & paddingBOTTOM if the content is to big. They then place the paddings at the RIGHT/BOTTOM of the "too broad/high content" (see picture below).
==> Therefore to get the REAL CONTENT WIDTH in some browsers you have to substract BOTH paddings from the scrollwidth and in some browsers you only have to substract the LEFT Padding.
I found a solution for this and wanted to add this as a comment, but was not allowed. So I took the picture and made it a bit clearer in the regard of the "moved paddings" and the "unreliable scrollWidth". In the BLUE AREA you find my solution on how to get the "REAL" CONTENT WIDTH!
Hope this helps to make things even clearer!
you must use this way for path:
DB_PATH= context.getDatabasePath(DB_NAME).getPath();
' i modify the code for Datatable
For Each c as DataColumn in dt.Columns
For j=0 To _dataTable.Columns.Count-1
xlWorksheet.Cells (i+1, j+1) = _dataTable.Columns(j).ColumnName
Next
Next
Hope this could be help!
By using the List
property.
ListBox1.AddItem "foo"
ListBox1.List(ListBox1.ListCount - 1, 1) = "bar"
I've coded this recently, and thought it would make sense to share this here. The code makes use of the async library.
var fs = require('fs');
var async = require('async');
var scan = function(dir, suffix, callback) {
fs.readdir(dir, function(err, files) {
var returnFiles = [];
async.each(files, function(file, next) {
var filePath = dir + '/' + file;
fs.stat(filePath, function(err, stat) {
if (err) {
return next(err);
}
if (stat.isDirectory()) {
scan(filePath, suffix, function(err, results) {
if (err) {
return next(err);
}
returnFiles = returnFiles.concat(results);
next();
})
}
else if (stat.isFile()) {
if (file.indexOf(suffix, file.length - suffix.length) !== -1) {
returnFiles.push(filePath);
}
next();
}
});
}, function(err) {
callback(err, returnFiles);
});
});
};
You can use it like this:
scan('/some/dir', '.ext', function(err, files) {
// Do something with files that ends in '.ext'.
console.log(files);
});
Using Underscore.js:
var myArray = [
Object { key="11", value="1100", $$hashKey="00X"},
Object { key="22", value="2200", $$hashKey="018"}
];
var myObj = _.object(_.pluck(myArray, 'key'), _.pluck(myArray, 'value'));
There are two "sys" catalog views you can consult: sys.indexes
and sys.index_columns
.
Those will give you just about any info you could possibly want about indices and their columns.
EDIT: This query's getting pretty close to what you're looking for:
SELECT
TableName = t.name,
IndexName = ind.name,
IndexId = ind.index_id,
ColumnId = ic.index_column_id,
ColumnName = col.name,
ind.*,
ic.*,
col.*
FROM
sys.indexes ind
INNER JOIN
sys.index_columns ic ON ind.object_id = ic.object_id and ind.index_id = ic.index_id
INNER JOIN
sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id
INNER JOIN
sys.tables t ON ind.object_id = t.object_id
WHERE
ind.is_primary_key = 0
AND ind.is_unique = 0
AND ind.is_unique_constraint = 0
AND t.is_ms_shipped = 0
ORDER BY
t.name, ind.name, ind.index_id, ic.is_included_column, ic.key_ordinal;
I was having trouble with mobile touchscreen button styling. This will fix your hover-stick / active button problems.
body, html {
width: 600px;
}
p {
font-size: 20px;
}
button {
border: none;
width: 200px;
height: 60px;
border-radius: 30px;
background: #00aeff;
font-size: 20px;
}
button:active {
background: black;
color: white;
}
.delayed {
transition: all 0.2s;
transition-delay: 300ms;
}
.delayed:active {
transition: none;
}
_x000D_
<h1>Sticky styles for better touch screen buttons!</h1>
<button>Normal button</button>
<button class="delayed"><a href="https://www.google.com"/>Delayed style</a></button>
<p>The CSS :active psuedo style is displayed between the time when a user touches down (when finger contacts screen) on a element to the time when the touch up (when finger leaves the screen) occures. With a typical touch-screen tap interaction, the time of which the :active psuedo style is displayed can be very small resulting in the :active state not showing or being missed by the user entirely. This can cause issues with users not undertanding if their button presses have actually reigstered or not.</p>
<p>Having the the :active styling stick around for a few hundred more milliseconds after touch up would would improve user understanding when they have interacted with a button.</p>
_x000D_
d4 = dict(d1.items() + d2.items() + d3.items())
alternatively (and supposedly faster):
d4 = dict(d1)
d4.update(d2)
d4.update(d3)
Previous SO question that both of these answers came from is here.
You can install apps in simulator from Xcode 8.2
From Xcode 8.2,You can install an app (*.app) by dragging any previously built app bundle into the simulator window.
Note: You cannot install apps from the App Store in simulation environments.
I faced the same error and did some research to only see that there could be different scenarios to this error. Let me share my findings.
Scenario 1: There cannot be spaces beside the =
(equals) sign
$ export TEMP_ENV = example-value
-bash: export: `=': not a valid identifier
// this is the answer to the question
$ export TEMP_ENV =example-value
-bash: export: `=example-value': not a valid identifier
$ export TEMP_ENV= example-value
-bash: export: `example-value': not a valid identifier
Scenario 2: Object value assignment should not have spaces besides quotes
$ export TEMP_ENV={ "key" : "json example" }
-bash: export: `:': not a valid identifier
-bash: export: `json example': not a valid identifier
-bash: export: `}': not a valid identifier
Scenario 3: List value assignment should not have spaces between values
$ export TEMP_ENV=[1,2 ,3 ]
-bash: export: `,3': not a valid identifier
-bash: export: `]': not a valid identifier
I'm sharing these, because I was stuck for a couple of hours trying to figure out a workaround. Hopefully, it will help someone in need.
The code above exports data without the heading columns which is weird. Here's how to do it. You have to merge the two files later though using text a editor.
SELECT column_name FROM information_schema.columns WHERE table_schema = 'my_app_db' AND table_name = 'customers' INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 5.6/Uploads/customers_heading_cols.csv' FIELDS TERMINATED BY '' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY ',';
To put it on one line:
currentLoad = IIf(IsNumeric(oXLSheet2.Cells(4, 6).Value), CInt(oXLSheet2.Cells(4, 6).Value), 0)
<?php
include("config.php");
$id=$_GET['id'];
include("config.php");
if($insert = mysqli_query($con,"update consumer_closeconnection set close_status='Pending' where id="$id" "))
{
?>
<script>
window.location.href='ConsumerCloseConnection.php';
</script>
<?php
}
else
{
?>
<script>
window.location.href='ConsumerCloseConnection.php';
</script>
<?php
}
?>
i use jquery code for this. (Alternative solution)
$(document).ready(function() {
var margin = $(".topmenu-design").width()-$("#topmenu").width();
$("#topmenu").css('margin-left',margin/2);
});
index.php
<body>
...
<input id="Div7" name="Txt_Nombre" maxlenght="100px" placeholder="Nombre" />
<input id="Div8" name="Txt_Correo" maxlenght="100px" placeholder="Correo" />
<textarea id="Div9" name="Txt_Pregunta" placeholder="Pregunta" /></textarea>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$(".Txt_Enviar").click(function() { EnviarCorreo(); });
});
function EnviarCorreo()
{
jQuery.ajax({
type: "POST",
url: 'servicios.php',
data: {functionname: 'enviaCorreo', arguments: [$(".Txt_Nombre").val(), $(".Txt_Correo").val(), $(".Txt_Pregunta").val()]},
success:function(data) {
alert(data);
}
});
}
</script>
servicios.php
<?php
include ("correo.php");
$nombre = $_POST["Txt_Nombre"];
$correo = $_POST["Txt_Corro"];
$pregunta = $_POST["Txt_Pregunta"];
switch($_POST["functionname"]){
case 'enviaCorreo':
EnviaCorreoDesdeWeb($nombre, $correo, $pregunta);
break;
}
?>
correo.php
<?php
function EnviaCorreoDesdeWeb($nombre, $correo, $pregunta)
{
...
}
?>
This works for me https://www.nuget.org/packages/ASquare.WindowsTaskScheduler/
It is nicely designed Fluent API.
//This will create Daily trigger to run every 10 minutes for a duration of 18 hours
SchedulerResponse response = WindowTaskScheduler
.Configure()
.CreateTask("TaskName", "C:\\Test.bat")
.RunDaily()
.RunEveryXMinutes(10)
.RunDurationFor(new TimeSpan(18, 0, 0))
.SetStartDate(new DateTime(2015, 8, 8))
.SetStartTime(new TimeSpan(8, 0, 0))
.Execute();
-(void)sendingAnHTTPPOSTRequestOniOSWithUserEmailId: (NSString *)emailId withPassword: (NSString *)password{
//Init the NSURLSession with a configuration
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
//Create an URLRequest
NSURL *url = [NSURL URLWithString:@"http://www.example.com/apis/login_api"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
//Create POST Params and add it to HTTPBody
NSString *params = [NSString stringWithFormat:@"email=%@&password=%@",emailId,password];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
//Create task
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Handle your response here
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",responseDict);
}];
[dataTask resume];
}
If you are using the background image for the rounded corners then I would rather increase the padding style of the main div to give enough room for the rounded corners of the background image to be visible.
Try increasing the padding of the main div style:
#mainWrapperDivWithBGImage
{
background: url("myImageWithRoundedCorners.jpg") no-repeat scroll 0 0 transparent;
height: 248px;
margin: 0;
overflow: hidden;
padding: 10px 10px;
width: 996px;
}
P.S: I assume the rounded corners have a radius of 10px.
There is a function specifically for this. It is called numpy.pad
a = np.array([[1,2,3], [2,3,4]])
b = np.pad(a, ((0, 0), (0, 1)), mode='constant', constant_values=0)
print b
>>> array([[1, 2, 3, 0],
[2, 3, 4, 0]])
Here is what it says in the docstring:
Pads an array.
Parameters
----------
array : array_like of rank N
Input array
pad_width : {sequence, array_like, int}
Number of values padded to the edges of each axis.
((before_1, after_1), ... (before_N, after_N)) unique pad widths
for each axis.
((before, after),) yields same before and after pad for each axis.
(pad,) or int is a shortcut for before = after = pad width for all
axes.
mode : str or function
One of the following string values or a user supplied function.
'constant'
Pads with a constant value.
'edge'
Pads with the edge values of array.
'linear_ramp'
Pads with the linear ramp between end_value and the
array edge value.
'maximum'
Pads with the maximum value of all or part of the
vector along each axis.
'mean'
Pads with the mean value of all or part of the
vector along each axis.
'median'
Pads with the median value of all or part of the
vector along each axis.
'minimum'
Pads with the minimum value of all or part of the
vector along each axis.
'reflect'
Pads with the reflection of the vector mirrored on
the first and last values of the vector along each
axis.
'symmetric'
Pads with the reflection of the vector mirrored
along the edge of the array.
'wrap'
Pads with the wrap of the vector along the axis.
The first values are used to pad the end and the
end values are used to pad the beginning.
<function>
Padding function, see Notes.
stat_length : sequence or int, optional
Used in 'maximum', 'mean', 'median', and 'minimum'. Number of
values at edge of each axis used to calculate the statistic value.
((before_1, after_1), ... (before_N, after_N)) unique statistic
lengths for each axis.
((before, after),) yields same before and after statistic lengths
for each axis.
(stat_length,) or int is a shortcut for before = after = statistic
length for all axes.
Default is ``None``, to use the entire axis.
constant_values : sequence or int, optional
Used in 'constant'. The values to set the padded values for each
axis.
((before_1, after_1), ... (before_N, after_N)) unique pad constants
for each axis.
((before, after),) yields same before and after constants for each
axis.
(constant,) or int is a shortcut for before = after = constant for
all axes.
Default is 0.
end_values : sequence or int, optional
Used in 'linear_ramp'. The values used for the ending value of the
linear_ramp and that will form the edge of the padded array.
((before_1, after_1), ... (before_N, after_N)) unique end values
for each axis.
((before, after),) yields same before and after end values for each
axis.
(constant,) or int is a shortcut for before = after = end value for
all axes.
Default is 0.
reflect_type : {'even', 'odd'}, optional
Used in 'reflect', and 'symmetric'. The 'even' style is the
default with an unaltered reflection around the edge value. For
the 'odd' style, the extented part of the array is created by
subtracting the reflected values from two times the edge value.
Returns
-------
pad : ndarray
Padded array of rank equal to `array` with shape increased
according to `pad_width`.
Notes
-----
.. versionadded:: 1.7.0
For an array with rank greater than 1, some of the padding of later
axes is calculated from padding of previous axes. This is easiest to
think about with a rank 2 array where the corners of the padded array
are calculated by using padded values from the first axis.
The padding function, if used, should return a rank 1 array equal in
length to the vector argument with padded values replaced. It has the
following signature::
padding_func(vector, iaxis_pad_width, iaxis, kwargs)
where
vector : ndarray
A rank 1 array already padded with zeros. Padded values are
vector[:pad_tuple[0]] and vector[-pad_tuple[1]:].
iaxis_pad_width : tuple
A 2-tuple of ints, iaxis_pad_width[0] represents the number of
values padded at the beginning of vector where
iaxis_pad_width[1] represents the number of values padded at
the end of vector.
iaxis : int
The axis currently being calculated.
kwargs : dict
Any keyword arguments the function requires.
Examples
--------
>>> a = [1, 2, 3, 4, 5]
>>> np.pad(a, (2,3), 'constant', constant_values=(4, 6))
array([4, 4, 1, 2, 3, 4, 5, 6, 6, 6])
>>> np.pad(a, (2, 3), 'edge')
array([1, 1, 1, 2, 3, 4, 5, 5, 5, 5])
>>> np.pad(a, (2, 3), 'linear_ramp', end_values=(5, -4))
array([ 5, 3, 1, 2, 3, 4, 5, 2, -1, -4])
>>> np.pad(a, (2,), 'maximum')
array([5, 5, 1, 2, 3, 4, 5, 5, 5])
>>> np.pad(a, (2,), 'mean')
array([3, 3, 1, 2, 3, 4, 5, 3, 3])
>>> np.pad(a, (2,), 'median')
array([3, 3, 1, 2, 3, 4, 5, 3, 3])
>>> a = [[1, 2], [3, 4]]
>>> np.pad(a, ((3, 2), (2, 3)), 'minimum')
array([[1, 1, 1, 2, 1, 1, 1],
[1, 1, 1, 2, 1, 1, 1],
[1, 1, 1, 2, 1, 1, 1],
[1, 1, 1, 2, 1, 1, 1],
[3, 3, 3, 4, 3, 3, 3],
[1, 1, 1, 2, 1, 1, 1],
[1, 1, 1, 2, 1, 1, 1]])
>>> a = [1, 2, 3, 4, 5]
>>> np.pad(a, (2, 3), 'reflect')
array([3, 2, 1, 2, 3, 4, 5, 4, 3, 2])
>>> np.pad(a, (2, 3), 'reflect', reflect_type='odd')
array([-1, 0, 1, 2, 3, 4, 5, 6, 7, 8])
>>> np.pad(a, (2, 3), 'symmetric')
array([2, 1, 1, 2, 3, 4, 5, 5, 4, 3])
>>> np.pad(a, (2, 3), 'symmetric', reflect_type='odd')
array([0, 1, 1, 2, 3, 4, 5, 5, 6, 7])
>>> np.pad(a, (2, 3), 'wrap')
array([4, 5, 1, 2, 3, 4, 5, 1, 2, 3])
>>> def pad_with(vector, pad_width, iaxis, kwargs):
... pad_value = kwargs.get('padder', 10)
... vector[:pad_width[0]] = pad_value
... vector[-pad_width[1]:] = pad_value
... return vector
>>> a = np.arange(6)
>>> a = a.reshape((2, 3))
>>> np.pad(a, 2, pad_with)
array([[10, 10, 10, 10, 10, 10, 10],
[10, 10, 10, 10, 10, 10, 10],
[10, 10, 0, 1, 2, 10, 10],
[10, 10, 3, 4, 5, 10, 10],
[10, 10, 10, 10, 10, 10, 10],
[10, 10, 10, 10, 10, 10, 10]])
>>> np.pad(a, 2, pad_with, padder=100)
array([[100, 100, 100, 100, 100, 100, 100],
[100, 100, 100, 100, 100, 100, 100],
[100, 100, 0, 1, 2, 100, 100],
[100, 100, 3, 4, 5, 100, 100],
[100, 100, 100, 100, 100, 100, 100],
[100, 100, 100, 100, 100, 100, 100]])
If you're changing the layout of an existing ImageView, you should be able to simply get the current LayoutParams, change the width/height, and set it back:
android.view.ViewGroup.LayoutParams layoutParams = myImageView.getLayoutParams();
layoutParams.width = 30;
layoutParams.height = 30;
myImageView.setLayoutParams(layoutParams);
I don't know if that's your goal, but if it is, this is probably the easiest solution.
I'd recommend that you take a look at jQuery.
jQuery way:
$("html").addClass("myClass");
If you mean that you want to enable the submit after the user has typed at least one character, then you need to attach a key event that will check it for you.
Something like:
$("#fbss").keypress(function() {
if($(this).val().length > 1) {
// Enable submit button
} else {
// Disable submit button
}
});
It all depends on your definition of correct. There are many ways in which you can evaluate your coding style. Readability is an important one (for me). That is why I would use the my_function
way of writing function names and variable names.
Use the built in "InternalServerError" method (available in ApiController):
return InternalServerError();
//or...
return InternalServerError(new YourException("your message"));
I went through the answers here and elsewhere and still had issues. It turned that (like the op), I was running in kubernetes, and the app was fine, but kubernetes had an issue.
I forgot to have my app start based on my port environment variable. So, kubernetes/helm was telling it to run on 8443 and to liveness probe that, but it was running on some other port (like 8123) from my application.properties.
The kubernetes events (get events) showed the live-ness probe was failing, so kubernetes was killing the pod/app every 30 seconds or so.
I find it is most useful to use Runnable for all the reasons mentioned, but sometimes I like to extend Thread so I can create my own thread stopping method and call it directly on the thread I have created.
URL-encoded payload must be provided on the body
parameter of the http.NewRequest(method, urlStr string, body io.Reader)
method, as a type that implements io.Reader
interface.
Based on the sample code:
package main
import (
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
)
func main() {
apiUrl := "https://api.com"
resource := "/user/"
data := url.Values{}
data.Set("name", "foo")
data.Set("surname", "bar")
u, _ := url.ParseRequestURI(apiUrl)
u.Path = resource
urlStr := u.String() // "https://api.com/user/"
client := &http.Client{}
r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
resp, _ := client.Do(r)
fmt.Println(resp.Status)
}
resp.Status
is 200 OK
this way.
LIFO is the way browser parses CSS properties..If you are using Sass declare a variable called as
"$header-background: red;"
use it instead of directly assigning values like red or blue. When you want to override just reassign the value to
"$header-background:blue"
then
background-color:$header-background;
it should smoothly override. Using "!important" is not always the right choice..Its just a hotfix
It seems like these would be good to have because (I assume) if you could specify the number you're typing in is a short then java wouldn't have to cast it
Since the parsing of literals happens at compile time, this is absolutely irrelevant in regard to performance. The only reason having short
and byte
suffixes would be nice is that it lead to more compact code.
Chrome and Safari has a restriction on using ajax with local resources. That's why it's throwing an error like
Origin null is not allowed by Access-Control-Allow-Origin.
Solution: Use firefox or upload your data to a temporary server. If you still want to use Chrome, start it with the below option;
--allow-file-access-from-files
More info how to add the above parameter to your Chrome: Right click the Chrome icon on your task bar, right click the Google Chrome on the pop-up window and click properties and add the above parameter inside the Target textbox under Shortcut tab. It will like as below;
C:\Users\XXX_USER\AppData\Local\Google\Chrome\Application\chrome.exe --allow-file-access-from-files
Hope this will help!
Don't go there. As a long term Mac developer, I can assure you, no solution is really working well. I tried so many solutions, but they are all not too good. I think the problem is that Apple does not really document the meta data format for the necessary data.
Here's how I'm doing it for a long time, very successfully:
Create a new DMG, writeable(!), big enough to hold the expected binary and extra files like readme (sparse might work).
Mount the DMG and give it a layout manually in Finder or with whatever tools suits you for doing that (see FileStorm link at the bottom for a good tool). The background image is usually an image we put into a hidden folder (".something") on the DMG. Put a copy of your app there (any version, even outdated one will do). Copy other files (aliases, readme, etc.) you want there, again, outdated versions will do just fine. Make sure icons have the right sizes and positions (IOW, layout the DMG the way you want it to be).
Unmount the DMG again, all settings should be stored by now.
Write a create DMG script, that works as follows:
This method may not sound optimal, but trust me, it works really well in practice. You can put the original DMG (DMG template) even under version control (e.g. SVN), so if you ever accidentally change/destroy it, you can just go back to a revision where it was still okay. You can add the DMG template to your Xcode project, together with all other files that belong onto the DMG (readme, URL file, background image), all under version control and then create a target (e.g. external target named "Create DMG") and there run the DMG script of above and add your old main target as dependent target. You can access files in the Xcode tree using ${SRCROOT} in the script (is always the source root of your product) and you can access build products by using ${BUILT_PRODUCTS_DIR} (is always the directory where Xcode creates the build results).
Result: Actually Xcode can produce the DMG at the end of the build. A DMG that is ready to release. Not only you can create a relase DMG pretty easy that way, you can actually do so in an automated process (on a headless server if you like), using xcodebuild from command line (automated nightly builds for example).
Regarding the initial layout of the template, FileStorm is a good tool for doing it. It is commercial, but very powerful and easy to use. The normal version is less than $20, so it is really affordable. Maybe one can automate FileStorm to create a DMG (e.g. via AppleScript), never tried that, but once you have found the perfect template DMG, it's really easy to update it for every release.
Alternative with single condition
SELECT * FROM table
WHERE YEAR(date_created) * 12 + MONTH(date_created)
= YEAR(CURRENT_DATE) * 12 + MONTH(CURRENT_DATE) - 1
You can't. XSS protection. Cross site contents can not be read by javascript. No major browser will allow you that. I'm sorry, but this is a design flaw, you should drop the idea.
EDIT
Note that if you have editing access to the website loaded into the iframe, you can use postMessage (also see the browser compatibility)
How i solved
# yum update
# yum install -y https://centos7.iuscommunity.org/ius-release.rpm
# yum install -y python36u python36u-libs python36u-devel python36u-pip
# pip3.6 install pipenv
I hope it will help Someone to resolve "gcc" issue.
See also The Platinium Searcher, which is similar to The Silver Searcher and it's written in Go.
Example:
pt -e 'text to search'
That doesn't work because a member function pointer cannot be handled like a normal function pointer, because it expects a "this" object argument.
Instead you can pass a static member function as follows, which are like normal non-member functions in this regard:
m_cRedundencyManager->Init(&CLoggersInfra::Callback, this);
The function can be defined as follows
static void Callback(int other_arg, void * this_pointer) {
CLoggersInfra * self = static_cast<CLoggersInfra*>(this_pointer);
self->RedundencyManagerCallBack(other_arg);
}
You (or Joomla) is likely including this file multiple times. Enclose your function in a conditional block:
if (!function_exists('parseDate')) {
// ... proceed to declare your function
}
You could create a color using the static FromArgb method:
Color redColor = Color.FromArgb(255, 0, 0);
You can also specify the alpha using the following overload.
Many suggestions here, most along the lines of git checkout $revision -- $file
. A couple of obscure alternatives:
git show $revision:$file > $file
And also, I use this a lot just to see a particular version temporarily:
git show $revision:$file
or
git show $revision:$file | vim -R -
(OBS: $file
needs to be prefixed with ./
if it is a relative path for git show $revision:$file
to work)
And the even more weird:
git archive $revision $file | tar -x0 > $file
I've been testing this myself, and looking at all the answers on this post and I don't think they answer this question very well. I experimented myself in order to get a good answer (code below). You CAN fire either event with both ActionListener and ItemListener 100% of the time when a state is changed in either a radio button or a check box, or any other kind of Swing item I'm assuming since it is type Object. The ONLY difference I can tell between these two listeners is the type of Event Object that gets returned with the listener is different. AND you get a better event type with a checkbox using an ItemListener as opposed to an ActionListener.
The return types of an ActionEvent and an ItemEvent will have different methods stored that may be used when an Event Type gets fired. In the code below the comments show the difference in .get methods for each Class returned Event type.
The code below sets up a simple JPanel with JRadioButtons, JCheckBoxes, and a JLabel display that changes based on button configs. I set all the RadioButtons and CheckBoxes up with both an Action Listener and an Item Listener. Then I wrote the Listener classes below with ActionListener fully commented because I tested it first in this experiment. You will notice that if you add this panel to a frame and display, all radiobuttons and checkboxes always fire regardless of the Listener type, just comment out the methods in one and try the other and vice versa.
Return Type into the implemented methods is the MAIN difference between the two. Both Listeners fire events the same way. Explained a little better in comment above is the reason a checkbox should use an ItemListener over ActionListener due to the Event type that is returned.
package EventHandledClasses;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class RadioButtonsAndCheckBoxesTest extends JPanel{
JLabel display;
String funny, serious, political;
JCheckBox bold,italic;
JRadioButton funnyQuote, seriousQuote, politicalQuote;
ButtonGroup quotes;
public RadioButtonsAndCheckBoxesTest(){
funny = "You are not ugly, you were just born... different";
serious = "Recommend powdered soap in prison!";
political = "Trump can eat a little Bernie, but will choke on his Birdie";
display = new JLabel(funny);
Font defaultFont = new Font("Ariel",Font.PLAIN,20);
display.setFont(defaultFont);
bold = new JCheckBox("Bold",false);
bold.setOpaque(false);
italic = new JCheckBox("Italic",false);
italic.setOpaque(false);
//Color itemBackground =
funnyQuote = new JRadioButton("Funny",true);
funnyQuote.setOpaque(false);
seriousQuote = new JRadioButton("Serious");
seriousQuote.setOpaque(false);
politicalQuote = new JRadioButton("Political");
politicalQuote.setOpaque(false);
quotes = new ButtonGroup();
quotes.add(funnyQuote);
quotes.add(seriousQuote);
quotes.add(politicalQuote);
JPanel primary = new JPanel();
primary.setPreferredSize(new Dimension(550, 100));
Dimension standard = new Dimension(500, 30);
JPanel radioButtonsPanel = new JPanel();
radioButtonsPanel.setPreferredSize(standard);
radioButtonsPanel.setBackground(Color.green);
radioButtonsPanel.add(funnyQuote);
radioButtonsPanel.add(seriousQuote);
radioButtonsPanel.add(politicalQuote);
JPanel checkBoxPanel = new JPanel();
checkBoxPanel.setPreferredSize(standard);
checkBoxPanel.setBackground(Color.green);
checkBoxPanel.add(bold);
checkBoxPanel.add(italic);
primary.add(display);
primary.add(radioButtonsPanel);
primary.add(checkBoxPanel);
//Add Action Listener To test Radio Buttons
funnyQuote.addActionListener(new ActionListen());
seriousQuote.addActionListener(new ActionListen());
politicalQuote.addActionListener(new ActionListen());
//Add Item Listener to test Radio Buttons
funnyQuote.addItemListener(new ItemListen());
seriousQuote.addItemListener(new ItemListen());
politicalQuote.addItemListener(new ItemListen());
//Add Action Listener to test Check Boxes
bold.addActionListener(new ActionListen());
italic.addActionListener(new ActionListen());
//Add Item Listener to test Check Boxes
bold.addItemListener(new ItemListen());
italic.addItemListener(new ItemListen());
//adds primary JPanel to this JPanel Object
add(primary);
}
private class ActionListen implements ActionListener{
public void actionPerformed(ActionEvent e) {
/*
Different Get Methods from ItemEvent
e.getWhen()
e.getModifiers()
e.getActionCommand()*/
/*int font=Font.PLAIN;
if(bold.isSelected()){
font += Font.BOLD;
}
if(italic.isSelected()){
font += Font.ITALIC;
}
display.setFont(new Font("Ariel",font,20));
if(funnyQuote.isSelected()){
display.setText(funny);
}
if(seriousQuote.isSelected()){
display.setText(serious);
}
if(politicalQuote.isSelected()){
display.setText(political);
}*/
}
}
private class ItemListen implements ItemListener {
public void itemStateChanged(ItemEvent arg0) {
/*
Different Get Methods from ActionEvent
arg0.getItemSelectable()
arg0.getStateChange()
arg0.getItem()*/
int font=Font.PLAIN;
if(bold.isSelected()){
font += Font.BOLD;
}
if(italic.isSelected()){
font += Font.ITALIC;
}
display.setFont(new Font("Ariel",font,20));
if(funnyQuote.isSelected()){
display.setText(funny);
}
if(seriousQuote.isSelected()){
display.setText(serious);
}
if(politicalQuote.isSelected()){
display.setText(political);
}
}
}
}
You also can lead your initial string, which you are going to check for pattern matching, to lower case. And use in your pattern lower case symbols respectively.
Based on your comments in this answer, I do what you're trying to do like this:
module.exports = function (app, db) {
var module = {};
module.auth = function (req, res) {
// This will be available 'outside'.
// Authy stuff that can be used outside...
};
// Other stuff...
module.pickle = function(cucumber, herbs, vinegar) {
// This will be available 'outside'.
// Pickling stuff...
};
function jarThemPickles(pickle, jar) {
// This will be NOT available 'outside'.
// Pickling stuff...
return pickleJar;
};
return module;
};
I structure pretty much all my modules like that. Seems to work well for me.
with open("input", "rb") as input:
with open("output", "wb") as output:
while True:
data = input.read(1024)
if data == "":
break
output.write(data)
The above will read 1 kilobyte at a time, and write it. You can support incredibly large files this way, as you won't need to read the entire file into memory.
If you like php, take a look at php.JS - JavaScript explode
Or in normal JavaScript functionality: `
var vInputString = "0000000020C90037:TEMP:data";
var vArray = vInputString.split(":");
var vRes = vArray[1] + ":" + vArray[2]; `
a.sort(function(a,b){return a - b})
These can be confusing.... check this link out.
ok, you may use substr in correlation to instr to find the starting position of your string
select
dbms_lob.substr(
product_details,
length('NEW.PRODUCT_NO'), --amount
dbms_lob.instr(product_details,'NEW.PRODUCT_NO') --offset
)
from my_table
where dbms_lob.instr(product_details,'NEW.PRODUCT_NO')>=1;
Depending on your needs, you may also want to check out the classes CountDownLatch and CyclicBarrier in the java.util.concurrent package. They can be useful if you want your threads to wait for each other, or if you want more fine-grained control over the way your threads execute (e.g., waiting in their internal execution for another thread to set some state). You could also use a CountDownLatch to signal all of your threads to start at the same time, instead of starting them one by one as you iterate through your loop. The standard API docs have an example of this, plus using another CountDownLatch to wait for all threads to complete their execution.
I've seen occasional problems with Eclipse forgetting that built-in classes (including Object
and String
) exist. The way I've resolved them is to:
This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.
The execmgr.log
will show the commandline and ccmcache folder used for installation. Typically, required apps don't show on appenforce.log
and some clients will have outdated appenforce
or no ppenforce.log
files.
execmgr.log
also shows required hidden uninstall actions as well.
You may want to save the blog link. I still reference it from time to time.
Just run
docker restart $(docker ps -q)
Update
For Docker 1.13.1
use docker restart $(docker ps -a -q)
as in answer lower.
The issue is that a notebooks is not a plain python file. The steps to import the .ipynb
file are outlined in the following: Importing notebook
I am pasting the code, so if you need it...you can just do a quick copy and paste. Notice that at the end I have the import primes
statement. You'll have to change that of course. The name of my file is primes.ipynb
. From this point on you can use the content inside that file as you would do regularly.
Wish there was a simpler method, but this is straight from the docs.
Note: I am using jupyter not ipython.
import io, os, sys, types
from IPython import get_ipython
from nbformat import current
from IPython.core.interactiveshell import InteractiveShell
def find_notebook(fullname, path=None):
"""find a notebook, given its fully qualified name and an optional path
This turns "foo.bar" into "foo/bar.ipynb"
and tries turning "Foo_Bar" into "Foo Bar" if Foo_Bar
does not exist.
"""
name = fullname.rsplit('.', 1)[-1]
if not path:
path = ['']
for d in path:
nb_path = os.path.join(d, name + ".ipynb")
if os.path.isfile(nb_path):
return nb_path
# let import Notebook_Name find "Notebook Name.ipynb"
nb_path = nb_path.replace("_", " ")
if os.path.isfile(nb_path):
return nb_path
class NotebookLoader(object):
"""Module Loader for Jupyter Notebooks"""
def __init__(self, path=None):
self.shell = InteractiveShell.instance()
self.path = path
def load_module(self, fullname):
"""import a notebook as a module"""
path = find_notebook(fullname, self.path)
print ("importing Jupyter notebook from %s" % path)
# load the notebook object
with io.open(path, 'r', encoding='utf-8') as f:
nb = current.read(f, 'json')
# create the module and add it to sys.modules
# if name in sys.modules:
# return sys.modules[name]
mod = types.ModuleType(fullname)
mod.__file__ = path
mod.__loader__ = self
mod.__dict__['get_ipython'] = get_ipython
sys.modules[fullname] = mod
# extra work to ensure that magics that would affect the user_ns
# actually affect the notebook module's ns
save_user_ns = self.shell.user_ns
self.shell.user_ns = mod.__dict__
try:
for cell in nb.worksheets[0].cells:
if cell.cell_type == 'code' and cell.language == 'python':
# transform the input to executable Python
code = self.shell.input_transformer_manager.transform_cell(cell.input)
# run the code in themodule
exec(code, mod.__dict__)
finally:
self.shell.user_ns = save_user_ns
return mod
class NotebookFinder(object):
"""Module finder that locates Jupyter Notebooks"""
def __init__(self):
self.loaders = {}
def find_module(self, fullname, path=None):
nb_path = find_notebook(fullname, path)
if not nb_path:
return
key = path
if path:
# lists aren't hashable
key = os.path.sep.join(path)
if key not in self.loaders:
self.loaders[key] = NotebookLoader(path)
return self.loaders[key]
sys.meta_path.append(NotebookFinder())
import primes
You can use rgba()
in css to define a color instead of rgb()
. Like this:
style='background-color: rgba(128,128,128, 0.7);
Gives you the same color as rgb(128,128,128)
but with a 70% opacity so the stuff behind only shows thru 30%. CSS3 but it's worked in most browsers since 2008. Sorry, no #rrggbb syntax that I know of. Play with the numbers - you can wash out with white, shadow out with gray, whatever you want to dilute with.
OK so you make a a rectangle in semi-transparent gray (or whatever color) and lay it on top of your image, maybe with position:absolute and a z-index higher than zero, and you put it just before your image and the default location for the rectangle will be the same upper-left corner of your image. Should work.
Try setting a custom CultureInfo for CurrentCulture and CurrentUICulture.
Globalization.CultureInfo customCulture = new Globalization.CultureInfo("en-US", true);
customCulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd h:mm tt";
System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = customCulture;
DateTime newDate = System.Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd h:mm tt"));
Have you tried using JsonSlurper?
Example usage:
def slurper = new JsonSlurper()
def result = slurper.parseText('{"person":{"name":"Guillaume","age":33,"pets":["dog","cat"]}}')
assert result.person.name == "Guillaume"
assert result.person.age == 33
assert result.person.pets.size() == 2
assert result.person.pets[0] == "dog"
assert result.person.pets[1] == "cat"
#inner {
width: 50%;
margin: 0 auto;
}
As other people have answered, you need to do;
myDropDown.Items.Remove(ListItem li);
but if you want the page to refresh asynchronously, the dropdown needs to be inside an asp:UpdatePanel
after you do the Remove
call, you need to call:
yourPanel.Update();
You can pass the value to the function using this.value
, where this
points to the button
<input type="button" value="mybutton1" onclick="dosomething(this.value)">
And then access that value in the function
function dosomething(val){
console.log(val);
}
In (the current) IPython 3.2.0 (Python 2 or 3)
Open the configuration file within the hidden folder .ipython
~/.ipython/profile_default/ipython_kernel_config.py
add the following line
c.IPKernelApp.matplotlib = 'inline'
add it straight after
c = get_config()
If you have many fields in select statement and you want latest value for all of those fields through optimized code:
select * from
(select * from table_name
order by id,rev desc) temp
group by id
Another alternative: HigLabo
https://higlabo.codeplex.com/documentation
Good discussion: https://higlabo.codeplex.com/discussions/479250
//====Imap sample================================//
//You can set default value by Default property
ImapClient.Default.UserName = "your server name";
ImapClient cl = new ImapClient("your server name");
cl.UserName = "your name";
cl.Password = "pass";
cl.Ssl = false;
if (cl.Authenticate() == true)
{
Int32 MailIndex = 1;
//Get all folder
List<ImapFolder> l = cl.GetAllFolders();
ImapFolder rFolder = cl.SelectFolder("INBOX");
MailMessage mg = cl.GetMessage(MailIndex);
}
//Delete selected mail from mailbox
ImapClient pop = new ImapClient("server name", 110, "user name", "pass");
pop.AuthenticateMode = Pop3AuthenticateMode.Pop;
Int64[] DeleteIndexList = new.....//It depend on your needs
cl.DeleteEMail(DeleteIndexList);
//Get unread message list from GMail
using (ImapClient cl = new ImapClient("imap.gmail.com"))
{
cl.Port = 993;
cl.Ssl = true;
cl.UserName = "xxxxx";
cl.Password = "yyyyy";
var bl = cl.Authenticate();
if (bl == true)
{
//Select folder
ImapFolder folder = cl.SelectFolder("[Gmail]/All Mail");
//Search Unread
SearchResult list = cl.ExecuteSearch("UNSEEN UNDELETED");
//Get all unread mail
for (int i = 0; i < list.MailIndexList.Count; i++)
{
mg = cl.GetMessage(list.MailIndexList[i]);
}
}
//Change mail read state as read
cl.ExecuteStore(1, StoreItem.FlagsReplace, "UNSEEN")
}
//Create draft mail to mailbox
using (ImapClient cl = new ImapClient("imap.gmail.com"))
{
cl.Port = 993;
cl.Ssl = true;
cl.UserName = "xxxxx";
cl.Password = "yyyyy";
var bl = cl.Authenticate();
if (bl == true)
{
var smg = new SmtpMessage("from mail address", "to mail addres list"
, "cc mail address list", "This is a test mail.", "Hi.It is my draft mail");
cl.ExecuteAppend("GMail/Drafts", smg.GetDataText(), "\\Draft", DateTimeOffset.Now);
}
}
//Idle
using (var cl = new ImapClient("imap.gmail.com", 993, "user name", "pass"))
{
cl.Ssl = true;
cl.ReceiveTimeout = 10 * 60 * 1000;//10 minute
if (cl.Authenticate() == true)
{
var l = cl.GetAllFolders();
ImapFolder r = cl.SelectFolder("INBOX");
//You must dispose ImapIdleCommand object
using (var cm = cl.CreateImapIdleCommand()) Caution! Ensure dispose command object
{
//This handler is invoked when you receive a mesage from server
cm.MessageReceived += (Object o, ImapIdleCommandMessageReceivedEventArgs e) =>
{
foreach (var mg in e.MessageList)
{
String text = String.Format("Type is {0} Number is {1}", mg.MessageType, mg.Number);
Console.WriteLine(text);
}
};
cl.ExecuteIdle(cm);
while (true)
{
var line = Console.ReadLine();
if (line == "done")
{
cl.ExecuteDone(cm);
break;
}
}
}
}
}
Here comes another vote in favor of PHPKB knowledge base software. We came to know about PHPKB from this post on StackOverflow and bought it as recommended by Julien and Ricardo. I am glad to inform that it was a right decision. Although we had to get certain features customized according to our needs but their support team exceeded our expectations. So, I just thought of sharing the news here. We are fully satisfied with PHPKB knowledge base software.
I moved Android folder path to another path and taked this error.
I resolved to this problem in below.
I was changed to Gradle path in system variables. But not path in user variables. You must change to path in system variables
None of the suggestions worked for me until I ran the command "gradle cleanIdeaModule ideaModule" info here: https://docs.gradle.org/current/userguide/idea_plugin.html
Stop using (HTTP 1.0) | Replaced with (HTTP 1.1 since 1999) |
---|---|
Expires: [date] | Cache-Control: max-age=[seconds] |
Pragma: no-cache | Cache-Control: no-cache |
If it's after 1999, and you're still using Expires or Pragma, you're doing it wrong.
I'm looking at you Stackoverflow:
200 OK Pragma: no-cache Content-Type: application/json X-Frame-Options: SAMEORIGIN X-Request-Guid: a3433194-4a03-4206-91ea-6a40f9bfd824 Strict-Transport-Security: max-age=15552000 Content-Length: 54 Accept-Ranges: bytes Date: Tue, 03 Apr 2018 19:03:12 GMT Via: 1.1 varnish Connection: keep-alive X-Served-By: cache-yyz8333-YYZ X-Cache: MISS X-Cache-Hits: 0 X-Timer: S1522782193.766958,VS0,VE30 Vary: Fastly-SSL X-DNS-Prefetch-Control: off Cache-Control: private
tl;dr: Pragma
is a legacy of HTTP/1.0 and hasn't been needed since Internet Explorer 5, or Netscape 4.7. Unless you expect some of your users to be using IE5: it's safe to stop using it.
[date]
(deprecated - HTTP 1.0)[seconds]
And the conditional requests:
Etag: W/“1d2e7–1648e509289”
If-None-Match: W/“1d2e7–1648e509289”
304 Not Modified
last-modified: Thu, 09 May 2019 19:15:47 GMT
If-Modified-Since: Fri, 13 Jul 2018 10:49:23 GMT
304 Not Modified
last-modified: Thu, 09 May 2019 19:15:47 GMT
Hmmm hi to the 10 years old party ?
Why not put some condition in your for ?
var condition = true
for (var i = 0 ; i < Args.length && condition ; i++) {
for (var j = 0 ; j < Args[i].length && condition ; j++) {
if (Args[i].obj[j] == "[condition]") {
condition = false
}
}
}
Like this you stop when you want
In my case, using Typescript, we can use some() which go through the array and stop when condition is met So my code become like this :
Args.some((listObj) => {
return listObj.some((obj) => {
return !(obj == "[condition]")
})
})
Like this, the loop stopped right after the condition is met
Reminder : This code run in TypeScript
I would go with Lev, but it's worth pointing out that if you end up with more complex searches that using re.finditer may be worth bearing in mind (but re's often cause more trouble than worth - but sometimes handy to know)
test = "ooottat"
[ (i.start(), i.end()) for i in re.finditer('o', test)]
# [(0, 1), (1, 2), (2, 3)]
[ (i.start(), i.end()) for i in re.finditer('o+', test)]
# [(0, 3)]
You can align it like that:
print('{:>8} {:>8} {:>8}'.format(*words))
where >
means "align to right" and 8
is the width for specific value.
And here is a proof:
>>> for line in [[1, 128, 1298039], [123388, 0, 2]]:
print('{:>8} {:>8} {:>8}'.format(*line))
1 128 1298039
123388 0 2
Ps. *line
means the line
list will be unpacked, so .format(*line)
works similarly to .format(line[0], line[1], line[2])
(assuming line
is a list with only three elements).
Use modulo
whenever a number x is a multiple of some number y, then always x % y equal to 0, which can be used as a check. So use
if (j % 4 == 0)
Another solution could be to use Number object parser like this:
let result = Number(new Date("2012-02-10T13:19:11+0000"));_x000D_
let resultWithGetTime = (new Date("2012-02-10T13:19:11+0000")).getTime();_x000D_
console.log(result);_x000D_
console.log(resultWithGetTime);
_x000D_
This converts to milliseconds just like getTime()
on Date
object
I know it's old news but to add my two cents. By default I use the commands LIKE[cd]
rather than just [c]
. The [d]
compares letters with accent symbols. This works especially well in my Warcraft App where people spell their name "Vòódòó" making it nearly impossible to search for their name in a tableview. The [d]
strips their accent symbols during the predicate. So a predicate of @"name LIKE[CD] %@", object.name
where object.name == @"voodoo"
will return the object containing the name Vòódòó.
From the Apple documentation: like[cd] means “case- and diacritic-insensitive like.”) For a complete description of the string syntax and a list of all the operators available, see Predicate Format String Syntax.
You can use this:
struct Person : Codable {
let name: String
let lastName: String
let age: Int
}
func loadJson(fileName: String) -> Person? {
let decoder = JSONDecoder()
guard
let url = Bundle.main.url(forResource: fileName, withExtension: "json"),
let data = try? Data(contentsOf: url),
let person = try? decoder.decode(Person.self, from: data)
else {
return nil
}
return person
}
$('form button[type="submit"]').on('click', function () {
$(this).parents('form').submit();
});
Try this:
if(myString != "-1")
The opperand is !=
and not =!
You can also use Equals
if(!myString.Equals("-1"))
Note the !
before myString
I think you need something a bit more generic. Try this:
public static System.Boolean IsNumeric (System.Object Expression)
{
if(Expression == null || Expression is DateTime)
return false;
if(Expression is Int16 || Expression is Int32 || Expression is Int64 || Expression is Decimal || Expression is Single || Expression is Double || Expression is Boolean)
return true;
try
{
if(Expression is string)
Double.Parse(Expression as string);
else
Double.Parse(Expression.ToString());
return true;
} catch {} // just dismiss errors but return false
return false;
}
}
Hope it helps!
If your object is not polymorphic (and a stack implementation likely isn't), then as per other answers here, what you want is the copy constructor. Please note that there are differences between copy construction and assignment in C++; if you want both behaviors (and the default versions don't fit your needs), you'll have to implement both functions.
If your object is polymorphic, then slicing can be an issue and you might need to jump through some extra hoops to do proper copying. Sometimes people use as virtual method called clone() as a helper for polymorphic copying.
Finally, note that getting copying and assignment right, if you need to replace the default versions, is actually quite difficult. It is usually better to set up your objects (via RAII) in such a way that the default versions of copy/assign do what you want them to do. I highly recommend you look at Meyer's Effective C++, especially at items 10,11,12.
Notice: Trying to get property of non-object in C:\wamp\www\phone\pages\init.php on line 22
@22 is
<?php echo $sidemenu->mname."<br />";?>
$sidemenu
is not an object, and you are trying to access one of its properties.
That is the reason for your error.
For a reason I don't yet understand, after I used <%@include file="includes/footer.jsp" %>
in my index.jsp
then in the other jsp files like register.jsp
I had to use <%@ include file="footer.jsp"%>
. As you see there was no more need to use full path, STS had store my initial path.
partial answer: pear HTTP_UPLOAD can be usefull http://pear.php.net/manual/en/package.http.http-upload.examples.php
there is a full example for multiple files
JSR-305 is a "Java Specification Request" to extend the specification. @Nullable
etc. were part of it; however it appears to be "dormant" (or frozen) ever since (See this SO question). So to use these annotations, you have to add the library yourself.
FindBugs was renamed to SpotBugs and is being developed under that name.
For maven this is the current annotation-only dependency (other integrations here):
<dependency>
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs-annotations</artifactId>
<version>4.2.0</version>
</dependency>
If you wish to use the full plugin, refer to the documentation of SpotBugs.
If your case is that the style is display none you can also use the ngStyle directive and modify the display directly, I did that for a bootstrap DropDown the UL on it is set to display none.
So I created a click event for "manually" toggling the UL to display
<div class="dropdown">
<button class="btn btn-default" (click)="manualtoggle()" id="dropdownMenu1" >
Seleccione una Ubicación
<span class="caret"></span>
</button>
<ul class="dropdown-menu" [ngStyle]="{display:displayddl}">
<li *ngFor="let object of Array" (click)="selectLocation(location)">{{object.Value}}</li>
</ul>
</div>
Then on the component I have showDropDown:bool attribute that I toggle every time, and based on int, set the displayDDL for the style as follows
showDropDown:boolean;
displayddl:string;
manualtoggle(){
this.showDropDown = !this.showDropDown;
this.displayddl = this.showDropDown ? "inline" : "none";
}
Even if fileno(FILE *)
may return a file descriptor, be VERY careful not to bypass stdio's buffer. If there is buffer data (either read or unflushed write), reads/writes from the file descriptor might give you unexpected results.
To answer one of the side questions, to convert a file descriptor to a FILE pointer, use fdopen(3)
You can use file redirection to redirected the sorted output:
sort input-file > output_file
Or you can use the -o
, --output=FILE
option of sort to indicate the same input and output file:
sort -o file file
Without repeating the filename (with bash brace expansion)
sort -o file{,}
?? Note: A common mistake is to try to redirect the output to the same input file
(e.g. sort file > file
). This does not work as the shell is making the redirections (not the sort(1) program) and the input file (as being the output also) will be erased just before giving the sort(1) program the opportunity of reading it.
seq -w
will detect the max input width and normalize the width of the output.
for num in $(seq -w 01 05); do
...
done
At time of writing this didn't work on the newest versions of OSX, so you can either install macports and use its version of seq
, or you can set the format explicitly:
seq -f '%02g' 1 3
01
02
03
But given the ugliness of format specifications for such a simple problem, I prefer the solution Henk and Adrian gave, which just uses Bash. Apple can't screw this up since there's no generic "unix" version of Bash:
echo {01..05}
Or:
for number in {01..05}; do ...; done
<meta http-equiv="refresh" content="5;URL='form2.html'">
I often had this problem myself. To avoid dependencies on small projects, I often write a small utility function when I don't need commons io or such. Here is the code to load the content of the file in a string buffer :
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("path/to/textfile.txt"), "UTF-8"));
for (int c = br.read(); c != -1; c = br.read()) sb.append((char)c);
System.out.println(sb.toString());
Specifying the encoding is important in that case, because you might have edited your file in UTF-8, and then put it in a jar, and the computer that opens the file may have CP-1251 as its native file encoding (for example); so in this case you never know the target encoding, therefore the explicit encoding information is crucial. Also the loop to read the file char by char seems inefficient, but it is used on a BufferedReader, and so actually quite fast.
You may do as follows. one line of code will be enough
let array = $('ul>li').toArray().map(item => $(item).html());
Get the interested element
get children
get the array from toArray() method
filter out the results you want
let array = $('ul>li').toArray().map(item => $(item).html());_x000D_
console.log(array);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<ul>_x000D_
<li>text1</li>_x000D_
<li>text2</li>_x000D_
<li>text3</li>_x000D_
</ul>
_x000D_
VonC mentioned in his answer how to remote debug from Eclipse.
I would like to add that the JAVA_OPTS
settings are already in run.conf.bat
. You just have to uncomment them:
in JBOSS_HOME\bin\run.conf.bat
on Windows:
rem # Sample JPDA settings for remote socket debugging
set "JAVA_OPTS=%JAVA_OPTS% -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n"
The Linux version is similar and is located at JBOSS_HOME/bin/run.conf
Some of the following was gleaned off of this site. This is what I did to duplicate a record in a table with any number of fields:
This also assumes you have an AI field at the beginning of the table
function duplicateRow( $id = 1 ){
dbLink();//my db connection
$qColumnNames = mysql_query("SHOW COLUMNS FROM table") or die("mysql error");
$numColumns = mysql_num_rows($qColumnNames);
for ($x = 0;$x < $numColumns;$x++){
$colname[] = mysql_fetch_row($qColumnNames);
}
$sql = "SELECT * FROM table WHERE tableId = '$id'";
$row = mysql_fetch_row(mysql_query($sql));
$sql = "INSERT INTO table SET ";
for($i=1;$i<count($colname)-4;$i++){//i set to 1 to preclude the id field
//we set count($colname)-4 to avoid the last 4 fields (good for our implementation)
$sql .= "`".$colname[$i][0]."` = '".$row[$i]. "', ";
}
$sql .= " CreateTime = NOW()";// we need the new record to have a new timestamp
mysql_query($sql);
$sql = "SELECT MAX(tableId) FROM table";
$res = mysql_query($sql);
$row = mysql_fetch_row($res);
return $row[0];//gives the new ID from auto incrementing
}
G'day,
Vim's regexp processing is not too brilliant. I've found that the regexp syntax for sed is about the right match for vim's capabilities.
I usually set the search highlighting on (:set hlsearch) and then play with the regexp after entering a slash to enter search mode.
Edit: Mark, that trick to minimise greedy matching is also covered in Dale Dougherty's excellent book "Sed & Awk" (sanitised Amazon link).
Chapter Three "Understanding Regular Expression Syntax" is an excellent intro to the more primitive regexp capabilities involved with sed and awk. Only a short read and highly recommended.
HTH
cheers,
Here is an implementation in Kotlin
try {
val inputStream: InputStream = this.getResources().openRawResource(R.raw.**)
val inputStreamReader = InputStreamReader(inputStream)
val sb = StringBuilder()
var line: String?
val br = BufferedReader(inputStreamReader)
line = br.readLine()
while (line != null) {
sb.append(line)
line = br.readLine()
}
br.close()
var content : String = sb.toString()
Log.d(TAG, content)
} catch (e:Exception){
Log.d(TAG, e.toString())
}
http://www.scala-lang.org/docu/files/api/scala/Enumeration.html
Example use
object Main extends App {
object WeekDay extends Enumeration {
type WeekDay = Value
val Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value
}
import WeekDay._
def isWorkingDay(d: WeekDay) = ! (d == Sat || d == Sun)
WeekDay.values filter isWorkingDay foreach println
}
With Chris's inspiring post here:
https://css-tricks.com/different-transitions-for-hover-on-hover-off/
I managed to come up with this:
#banner
{
display:block;
width:100%;
background-repeat:no-repeat;
background-position:center bottom;
background-image:url(../images/image1.jpg);
/* HOVER OFF */
@include transition(background-image 0.5s ease-in-out);
&:hover
{
background-image:url(../images/image2.jpg);
/* HOVER ON */
@include transition(background-image 0.5s ease-in-out);
}
}
Presumably from this site:
Internal Fragmentation Internal fragmentation occurs when the memory allocator leaves extra space empty inside of a block of memory that has been allocated for a client. This usually happens because the processor’s design stipulates that memory must be cut into blocks of certain sizes -- for example, blocks may be required to be evenly be divided by four, eight or 16 bytes. When this occurs, a client that needs 57 bytes of memory, for example, may be allocated a block that contains 60 bytes, or even 64. The extra bytes that the client doesn’t need go to waste, and over time these tiny chunks of unused memory can build up and create large quantities of memory that can’t be put to use by the allocator. Because all of these useless bytes are inside larger memory blocks, the fragmentation is considered internal.
External Fragmentation External fragmentation happens when the memory allocator leaves sections of unused memory blocks between portions of allocated memory. For example, if several memory blocks are allocated in a continuous line but one of the middle blocks in the line is freed (perhaps because the process that was using that block of memory stopped running), the free block is fragmented. The block is still available for use by the allocator later if there’s a need for memory that fits in that block, but the block is now unusable for larger memory needs. It cannot be lumped back in with the total free memory available to the system, as total memory must be contiguous for it to be useable for larger tasks. In this way, entire sections of free memory can end up isolated from the whole that are often too small for significant use, which creates an overall reduction of free memory that over time can lead to a lack of available memory for key tasks.
function initialize() {
var location = new google.maps.LatLng(44.5403, -78.5463);
var mapCanvas = document.getElementById('map_canvas');
var map_options = {
center: location,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(map_canvas, map_options);
new google.maps.Marker({
position: location,
map: map
});
}
google.maps.event.addDomListener(window, 'load', initialize);
CSS for that td: white-space: nowrap;
should solve it.
This approach is without using
max()
function
a = [1,2,3,4,6,7,99,88,999]
max_num = 0
for i in a:
if i > max_num:
max_num = i
print(max_num)
Also if you want to find the index of the resulting max,
print(a.index(max_num))
Direct approach by using function max()
max() function returns the item with the highest value, or the item with the highest value in an iterable
Example: when you have to find max on integers/numbers
a = (1, 5, 3, 9)
print(max(a))
>> 9
Example: when you have string
x = max("Mike", "John", "Vicky")
print(x)
>> Vicky
It basically returns the name with the highest value, ordered alphabetically.
Here's another approach that runs slower (about 1000ms) than the above answer, but has an interesting idea :-)
Instead of iterating through each property chain, it just picks the last property and uses a look-up-table for the rest to store the intermediate results. This look-up-table will be iterated until there are no property chains left and all values reside on uncocatenated properties.
JSON.unflatten = function(data) {
"use strict";
if (Object(data) !== data || Array.isArray(data))
return data;
var regex = /\.?([^.\[\]]+)$|\[(\d+)\]$/,
props = Object.keys(data),
result, p;
while(p = props.shift()) {
var m = regex.exec(p),
target;
if (m.index) {
var rest = p.slice(0, m.index);
if (!(rest in data)) {
data[rest] = m[2] ? [] : {};
props.push(rest);
}
target = data[rest];
} else {
target = result || (result = (m[2] ? [] : {}));
}
target[m[2] || m[1]] = data[p];
}
return result;
};
It currently uses the data
input parameter for the table, and puts lots of properties on it - a non-destructive version should be possible as well. Maybe a clever lastIndexOf
usage performs better than the regex (depends on the regex engine).
You could do this if firstname and surname are separated by space:
SELECT SUBSTRING(FirstAndSurnameCol, 0, CHARINDEX(' ', FirstAndSurnameCol)) Firstname,
SUBSTRING(FirstAndSurnameCol, CHARINDEX(' ', FirstAndSurnameCol)+1, LEN(FirstAndSurnameCol)) Surname FROM ...
Please Note: The original poster was not specifically asking about PHP. All the php centric answers make large assumptions not relevant to the actual question.
The default error log as opposed to the scripts error logs usually has the (more) specific error. often it will be permissions denied or even an interpreter that can't be found.
This means the fault almost always lies with your script. e.g you uploaded a perl script but didnt give it execute permissions? or perhaps it was corrupted in a linux environment if you write the script in windows and then upload it to the server without the line endings being converted you will get this error.
in perl if you forget
print "content-type: text/html\r\n\r\n";
you will get this error
There are many reasons for it. so please first check your error log and then provide some more information.
The default error log is often in /var/log/httpd/error_log
or /var/log/apache2/error.log
.
The reason you look at the default error logs (as indicated above) is because errors don't always get posted into the custom error log as defined in the virtual host.
Assumes linux and not necessarily perl
following script will use to create any kind of file, with user input as extension
import sys
def create():
print("creating new file")
name=raw_input ("enter the name of file:")
extension=raw_input ("enter extension of file:")
try:
name=name+"."+extension
file=open(name,'a')
file.close()
except:
print("error occured")
sys.exit(0)
create()
You need to use the full property name for each:
background-color: #6DB3F2;
background-image: url('images/checked.png');
Or, you can use the background shorthand and specify it all in one line:
background: url('images/checked.png'), #6DB3F2;
start-all.sh & stop-all.sh : Used to start and stop hadoop daemons all at once. Issuing it on the master machine will start/stop the daemons on all the nodes of a cluster. Deprecated as you have already noticed.
start-dfs.sh, stop-dfs.sh and start-yarn.sh, stop-yarn.sh : Same as above but start/stop HDFS and YARN daemons separately on all the nodes from the master machine. It is advisable to use these commands now over start-all.sh & stop-all.sh
hadoop-daemon.sh namenode/datanode and yarn-deamon.sh resourcemanager : To start individual daemons on an individual machine manually. You need to go to a particular node and issue these commands.
Use case : Suppose you have added a new DN to your cluster and you need to start the DN daemon only on this machine,
bin/hadoop-daemon.sh start datanode
Note : You should have ssh enabled if you want to start all the daemons on all the nodes from one machine.
Hope this answers your query.
I had similar issue, my problem was with the side padding, and the solution was with, text-indent, I wasn't realize that text indent effect the placeholder side position.
input{
text-indent: 10px;
}
It's "a reference to the object in the current context" effectively. For example, to print out "this object" you might write:
System.out.println(this);
Note that your usage of "global variable" is somewhat off... if you're using this.variableName
then by definition it's not a global variable - it's a variable specific to this particular instance.
/
means the root of the current drive;
./
means the current directory;
../
means the parent of the current directory.
Be aware that you're currently testing for object identity (is
only returns True
if both operands are represented by the same object in memory - this is not always the case with two object that compare equal with ==
). If you are doing this on purpose, then you could rewrite your code as
some_dict = {key: value for key, value in some_dict.items()
if value is not value_to_remove}
But this may not do what you want:
>>> some_dict = {1: "Hello", 2: "Goodbye", 3: "You say yes", 4: "I say no"}
>>> value_to_remove = "You say yes"
>>> some_dict = {key: value for key, value in some_dict.items() if value is not value_to_remove}
>>> some_dict
{1: 'Hello', 2: 'Goodbye', 3: 'You say yes', 4: 'I say no'}
>>> some_dict = {key: value for key, value in some_dict.items() if value != value_to_remove}
>>> some_dict
{1: 'Hello', 2: 'Goodbye', 4: 'I say no'}
So you probably want !=
instead of is not
.
Follow it...
<form action="index.php" method="POST">
<input type="number" name="array[]" value="1">
<input type="number" name="array[]" value="2">
<input type="number" name="array[]" value="3"> <!--taking array input by input name array[]-->
<input type="number" name="array[]" value="4">
<input type="submit" name="submit">
</form>
<?php
$a=$_POST['array'];
echo "Input :" .$a[3]; // Displaying Selected array Value
foreach ($a as $v) {
print_r($v); //print all array element.
}
?>
I had a similar symptom. In my case though, my idiocy was in unintentionally also having an empty index.html file in the web root folder. Apache was serving this rather than index.php when I didn't explicitly request index.php, since DirectoryIndex
was configured as follows in mods-available/dir.conf
:
DirectoryIndex index.html index.cgi index.pl index.php index.xhtml index.htm
That is, 'index.html' appears ahead of 'index.php' in the priority list. Removing the index.html file from the web root naturally resolved the problem. D'oh!
InnoDB works slightly different that MyISAM and they both are viable options. You should use what you think it fits the project.
Some keypoints will be:
Notes:
Notes2: - I am reading this book "High performance MySQL", the author says "InnoDB loads data and creates indexes slower than MyISAM", this could also be a very important factor when deciding what to use.
MariaDB running on Raspbian - the file containing bind-address is hard to pinpoint. MariaDB have some not-very-helpful-info on the subject.
I used
# sudo grep -R bind-address /etc
to locate where the damn thing is.
I also had to set the privileges and hosts in the mysql like everyone above pointed out.
And also had some fun time opening the 3306 port for remote connections to my Raspberry Pi - finally used iptables-persistent.
All works great now.
It's possible, but you have to add some JVM flags when you start your application.
You have to add remote debug configuration: Edit configuration -> Remote.
Then you'lll find in displayed dialog window parametrs that you have to add to program execution, like:
-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005
Then when your application is launched you can attach your debugger. If you want your application to wait until debugger is connected just change suspend flag to y (suspend=y
)
You can not "attach" a SASS/SCSS file to an HTML document.
SASS/SCSS is a CSS preprocessor that runs on the server and compiles to CSS code that your browser understands.
There are client-side alternatives to SASS that can be compiled in the browser using javascript such as LESS CSS, though I advise you compile to CSS for production use.
It's as simple as adding 2 lines of code to your HTML file.
<link rel="stylesheet/less" type="text/css" href="styles.less" />
<script src="less.js" type="text/javascript"></script>
There are a few important informations missing from your question:
$ vim --version
?If your Vim was built with clipboard support, you are supposed to use the clipboard register like this, in normal mode:
gg"+yG
If your Vim doesn't have clipboard support, you can manage to copy text from Vim to your OS clipboard via other programs. This pretty much depends on your OS but you didn't say what it is so we can't really help.
However, if your Vim is crippled, the best thing to do is to install a proper build with clipboard support but I can't tell you how either because I don't know what OS you use.
edit
On debian based systems, the following command will install a proper Vim with clipboard, ruby, python… support.
$ sudo apt-get install vim-gnome
I've also used the InternalsVisibleToAttribute method. It's worth mentioning too that, if you feel uncomfortable making your previously private methods internal in order to achieve this, then maybe they should not be the subject of direct unit tests anyway.
After all, you're testing the behaviour of your class, rather than it's specific implementation - you can change the latter without changing the former and your tests should still pass.
Let consider that your data are in the file values.txt
and that you want to import them in the database table myTable
then the following query does the job
COPY myTable FROM 'value.txt' (DELIMITER('|'));
https://www.postgresql.org/docs/current/static/sql-copy.html
Floats and doubles are approximate. If you create a BigDecimal and pass a float into the constructor you see what the float actually equals:
groovy:000> new BigDecimal(1.0F)
===> 1
groovy:000> new BigDecimal(1.01F)
===> 1.0099999904632568359375
this probably isn't how you want to represent $1.01.
The problem is that the IEEE spec doesn't have a way to exactly represent all fractions, some of them end up as repeating fractions so you end up with approximation errors. Since accountants like things to come out exactly to the penny, and customers will be annoyed if they pay their bill and after the payment is processed they owe .01 and they get charged a fee or can't close their account, it's better to use exact types like decimal (in C#) or java.math.BigDecimal in Java.
It's not that the error isn't controllable if you round: see this article by Peter Lawrey. It's just easier not to have to round in the first place. Most applications that handle money don't call for a lot of math, the operations consist of adding things or allocating amounts to different buckets. Introducing floating point and rounding just complicates things.
In our case, we were using Hibernate and we had many variables referencing the same Hibernate mapped entity. We were creating and saving these references in a loop. Each reference opened a cursor and kept it open.
We discovered this by using a query to check the number of open cursors while running our code, stepping through with a debugger and selectively commenting things out.
As to why each new reference opened another cursor - the entity in question had collections of other entities mapped to it and I think this had something to do with it (perhaps not just this alone but in combination with how we had configured the fetch mode and cache settings). Hibernate itself has had bugs around failing to close open cursors, though it looks like these have been fixed in later versions.
Since we didn't really need to have so many duplicate references to the same entity anyway, the solution was to stop creating and holding onto all those redundant references. Once we did that the problem when away.
I've solved this by adding this into my bash ~/.profile
:
function gitb() { git checkout -b $1 && git push --set-upstream origin $1; }
Then to start up a new local + remote branch, I write:
gitb feature/mynewbranch
This creates the branch and does the first push, not just to setup tracking (so that later git pull
and git push
work without extra arguments), but actually confirming that the target repo doesn't already have such branch in it.
The no-js
class gets removed by a javascript script, so you can modify/display/hide things using css if js is disabled.
Here is yet another explanation of how the factorial calculation using recursion works.
Let's modify source code slightly:
int factorial(int n) {
if (n <= 1)
return 1;
else
return n * factorial(n - 1);
}
Here is calculation of 3! in details:
Source: RECURSION (Java, C++) | Algorithms and Data Structures
Bear in mind that it is only worth using anything other than a full table scan to find these values if the number of blocks that contain a row that matches the predicate is significantly smaller than the total number of blocks in the table. That is why Oracle will often decline the use of an index in order to full scan when you use LIKE '%x%' where x is a very small string. For example if the optimizer believes that using an index would still require single-block reads on (say) 20% of the table blocks then a full table scan is probably a better option than an index scan.
Sometimes you know that your predicate is much more selective than the optimizer can estimate. In such a case you can look into supplying an optimizer hint to perform an index fast full scan on the relevant column (particularly if the index is a much smaller segment than the table).
SELECT /*+ index_ffs(users (users.last_name)) */
*
FROM users
WHERE last_name LIKE "%z%"
I have come to this question and the one below several times.
how to call scalar function in sql server 2008
Each time, I try entering the Function using the syntax shown here in SQL Server Management Studio, or SSMS, to see the results, and each time I get the errors.
For me, that is because my result set is in tabular data format. Therefore, to see the results in SSMS, I have to call it like this:
SELECT * FROM dbo.Afisho_rankimin_TABLE(5);
I understand that the author's question involved a scalar function, so this answer is only to help others who come to StackOverflow often when they have a problem with a query (like me).
I hope this helps others.
Here we go,
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con; //database connection
cmd.CommandText = "WRITE_STORED_PROC_NAME"; // Stored procedure name
cmd.CommandType = CommandType.StoredProcedure; // set it to stored proc
//add parameter if necessary
cmd.Parameters.Add("@userId", SqlDbType.Int).Value = courseid;
SqlDataAdapter adap = new SqlDataAdapter(cmd);
adap.Fill(ds, "Course");
return ds;
You can't use it in the way you describe. The point about generic types, is that although you may not know them at "coding time", the compiler needs to be able to resolve them at compile time. Why? Because under the hood, the compiler will go away and create a new type (sometimes called a closed generic type) for each different usage of the "open" generic type.
In other words, after compilation,
DoesEntityExist<int>
is a different type to
DoesEntityExist<string>
This is how the compiler is able to enfore compile-time type safety.
For the scenario you describe, you should pass the type as an argument that can be examined at run time.
The other option, as mentioned in other answers, is that of using reflection to create the closed type from the open type, although this is probably recommended in anything other than extreme niche scenarios I'd say.
In my experience most developers naturally migrate towards white box testing. Since we need to ensure that the underlying algorithm is "correct", we tend to focus more on the internals. But, as has been pointed out, both white and black box testing is important.
Therefore, I prefer to have testers focus more on the Black Box tests, to cover for the fact that most developers don't really do it, and frequently aren't very good at it.
That isn't to say that testers should be kept in the dark about how the system works, just that I prefer them to focus more on the problem domain and how actual users interact with the system, not whether the function SomeMethod(int x) will correctly throw an exception if x is equal to 5.
I usually add to index changes I don't want to stash and then stash with --keep-index
option.
git add app/controllers/cart_controller.php
git stash --keep-index
git reset
Last step is optional, but usually you want it. It removes changes from index.
Warning
As noted in the comments, this puts everything into the stash, both staged and unstaged. The --keep-index
just leaves the index alone after the stash is done. This can cause merge conflicts when you later pop the stash.
Some compilers support compound literals as an extention, allowing this construct:
Customer customerRecords[2];
customerRecords[0] = (Customer){25, "Bob Jones"};
customerRecords[1] = (Customer){26, "Jim Smith"};
But it's rather unportable.
You need to use "\n"
not '\n'
in your gsub. The different quote marks behave differently.
Double quotes "
allow character expansion and expression interpolation ie. they let you use escaped control chars like \n
to represent their true value, in this case, newline, and allow the use of #{expression}
so you can weave variables and, well, pretty much any ruby expression you like into the text.
While on the other hand, single quotes '
treat the string literally, so there's no expansion, replacement, interpolation or what have you.
In this particular case, it's better to use either the .delete
or .tr
String method to delete the newlines.
When you evaluate the code, it is very clear that (==) compares according to memory address, while equals(Object o) compares hashCode() of the instances. That's why it is said do not break the contract between equals() and hashCode() if you do not face surprises later.
String s1 = new String("Ali");
String s2 = new String("Veli");
String s3 = new String("Ali");
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
System.out.println(s3.hashCode());
System.out.println("(s1==s2):" + (s1 == s2));
System.out.println("(s1==s3):" + (s1 == s3));
System.out.println("s1.equals(s2):" + (s1.equals(s2)));
System.out.println("s1.equal(s3):" + (s1.equals(s3)));
/*Output
96670
3615852
96670
(s1==s2):false
(s1==s3):false
s1.equals(s2):false
s1.equal(s3):true
*/
Usually you make the thing you don't want duplicates of unique, and allow the database itself to refuse the insert.
Otherwise, you can use INSERT INTO, see How to avoid duplicates in INSERT INTO SELECT query in SQL Server?
Use inputstream once don't use it multiple times and Do inputstream.close()
according to mysql documentation none of these works! People pay attention! so we will upload test.sql into the test_db type this into the shell:
mysql --user=user_name --password=yourpassword test_db < d:/test.sql
Try resetting your network settings
Settings -> General -> Reset -> Reset Network Settings
And try deleting the contents of your mac/pc lockdown folder. Here's the link, follow the steps on "Reset the Lockdown folder".
http://support.apple.com/kb/ts2529
This one worked for me.
numpy.random.randint
accepts a third argument (size
) , in which you can specify the size of the output array. You can use this to create your DataFrame
-
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
Here - np.random.randint(0,100,size=(100, 4))
- creates an output array of size (100,4)
with random integer elements between [0,100)
.
Demo -
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
which produces:
A B C D
0 45 88 44 92
1 62 34 2 86
2 85 65 11 31
3 74 43 42 56
4 90 38 34 93
5 0 94 45 10
6 58 23 23 60
.. .. .. .. ..
The only thing that springs to mind for this is to use a proxy server based in Europe. Either have your colleague set one up [if possible] or find a free proxy. A quick Google search came up with http://www.anonymousinet.com/ as the top result.
First, you should avoid having files with the same name as the module itself. It may break other imports.
When you import a file, first the interpreter checks the current directory and then searchs global directories.
Inside examples
or tests
you can call:
from ..api import api
Just try like this:
HTML in PHP :
$link_address1 = 'index.php';
echo "<a href='".$link_address1."'>Index Page</a>";
$link_address2 = 'page2.php';
echo "<a href='".$link_address2."'>Page 2</a>";
Easiest way
$link_address1 = 'index.php';
echo "<a href='$link_address1'>Index Page</a>";
$link_address2 = 'page2.php';
echo "<a href='$link_address2'>Page 2</a>";
this will create a retrofit object with Logging. without creating separate objects.
private static final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(new OkHttpClient().newBuilder()
.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.readTimeout(READ_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.writeTimeout(WRITE_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.connectTimeout(CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
You want to access MySQL with root user but you're not providing root's correct password.
If you need to set a new password for root, MySQL's site has great documentation on how to do it: http://dev.mysql.com/doc/refman/5.7/en/resetting-permissions.html
I'll not show the process in here because MySql documentation on the above link it's clear and concise.
Simply Run Your Visual Studio 2013 as Administration ... Copy the content of your Xml file.. Go to Visual Studio 2013 > Edit > Paste Special > Paste Xml as C# Classes It will create your c# classes according to your Xml file content.
"kill" will only kill one screen window. To "kill" the complete session, use quit
.
$ screen -X -S [session # you want to kill] quit
For dead sessions use: $ screen -wipe
Try this example and see if it fits your needs, there are three main aspects to it.
Line.Stretch is set to fill.
For horizontal lines the VerticalAlignment of the line is set Bottom, and for VerticalLines the HorizontalAlignment is set to Right.
We then need to tell the line how many rows or columns to span, this is done by binding to either RowDefinitions or ColumnDefintions count property.
<Style x:Key="horizontalLineStyle" TargetType="Line" BasedOn="{StaticResource lineStyle}">
<Setter Property="X2" Value="1" />
<Setter Property="VerticalAlignment" Value="Bottom" />
<Setter Property="Grid.ColumnSpan"
Value="{Binding
Path=ColumnDefinitions.Count,
RelativeSource={RelativeSource AncestorType=Grid}}"/>
</Style>
<Style x:Key="verticalLineStyle" TargetType="Line" BasedOn="{StaticResource lineStyle}">
<Setter Property="Y2" Value="1" />
<Setter Property="HorizontalAlignment" Value="Right" />
<Setter Property="Grid.RowSpan"
Value="{Binding
Path=RowDefinitions.Count,
RelativeSource={RelativeSource AncestorType=Grid}}"/>
</Style>
</Grid.Resources>
<Grid.RowDefinitions>
<RowDefinition Height="20"/>
<RowDefinition Height="20"/>
<RowDefinition Height="20"/>
<RowDefinition Height="20"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="20"/>
</Grid.ColumnDefinitions>
<Line Grid.Column="0" Style="{StaticResource verticalLineStyle}"/>
<Line Grid.Column="1" Style="{StaticResource verticalLineStyle}"/>
<Line Grid.Column="2" Style="{StaticResource verticalLineStyle}"/>
<Line Grid.Column="3" Style="{StaticResource verticalLineStyle}"/>
<Line Grid.Row="0" Style="{StaticResource horizontalLineStyle}"/>
<Line Grid.Row="1" Style="{StaticResource horizontalLineStyle}"/>
<Line Grid.Row="2" Style="{StaticResource horizontalLineStyle}"/>
<Line Grid.Row="3" Style="{StaticResource horizontalLineStyle}"/>
The File
object has a length
method:
f = new File("your/file/name");
f.length();
The easiest might be:
Array(1, 2, 3) :+ 4
Actually, Array can be implcitly transformed in a WrappedArray
git revert
doesn't take a filename parameter. Do you want git checkout
?
It seems to work fine in Google Chrome. Which browser are you using? Here the proof http://jsfiddle.net/CN8XL/
Anyhow you can also access to the input value parameter through the document.FormName.checkyear.value
. You have to wrap in the input in a <form>
tag like with the proper name
attribute, like shown below:
<form name="FormName">
<input type="hidden" name="checkyear" id="checkyear" value="">
</form>
Have you considered using the jQuery Library? Here are the docs for .val()
function.
There is obviously another process listening on the port. You might find out that process by using the following command:
$ lsof -i :8000
or change your tornado app's port. tornado's error info not Explicitly on this.
Here's a flow chart that illustrates a for loop:
The equivalent C code would be
for(i = 2; i <= 6; i = i + 2) {
printf("%d\t", i + 1);
}
I found this and several other examples on one of Tenouk's C Laboratory practice worksheets.
I'm sure this is a duplicate, but I can't find a question with the same answer.
Add HorizontalContentAlignment="Stretch"
to your ListBox. That should do the trick. Just be careful with auto-complete because it is so easy to get HorizontalAlignment
by mistake.
You can change the code when you decompiled it, but it has to be recompiled to a class
file, the decompiler outputs java
code, this has to be recompiled with the same classpath as the original jar
/class
file
If anyone is using Maven, you'll need to add the dependency in the POM.XML file. The latest version as of this post is below:
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
For me the issue was that the WSGI script wasn't executable.
sudo chmod a+x django.wsgi
or just
sudo chmod u+x django.wsgi
so long as you have the correct owner
I had the same problem.
My height changed to its original height while my slide was animating to the left, ( in a responsive website )
so I fixed it with CSS only :
.carousel .item.left img{
width: 100% !important;
}
This is because, the line new_list = my_list
assigns a new reference to the variable my_list
which is new_list
This is similar to the C
code given below,
int my_list[] = [1,2,3,4];
int *new_list;
new_list = my_list;
You should use the copy module to create a new list by
import copy
new_list = copy.deepcopy(my_list)