Some explanation ignore a condition about the retain cycle [If a group of objects is connected by a circle of strong relationships, they keep each other alive even if there are no strong references from outside the group.] For more information, read the document
I know it's an old question but today got the same error and non of the above solutions worked.
Have fixed it however by setting option:
Project -> Architecture -> Build Active Architecture Only
to Yes
and project compiles and builds properly
Contrary to Martin's answer, casting to int (or ignoring the warning) isn't always safe even if you know your array doesn't have more than 2^31-1 elements. Not when compiling for 64-bit.
For example:
NSArray *array = @[@"a", @"b", @"c"];
int i = (int) [array indexOfObject:@"d"];
// indexOfObject returned NSNotFound, which is NSIntegerMax, which is LONG_MAX in 64 bit.
// We cast this to int and got -1.
// But -1 != NSNotFound. Trouble ahead!
if (i == NSNotFound) {
// thought we'd get here, but we don't
NSLog(@"it's not here");
}
else {
// this is what actually happens
NSLog(@"it's here: %d", i);
// **** crash horribly ****
NSLog(@"the object is %@", array[i]);
}
In Swift this problem can be solved by adding the following code in your
viewDidLoad
method.
tableView.registerClass(UITableViewCell.classForKeyedArchiver(), forCellReuseIdentifier: "your_reuse_identifier")
SIGABRT means in general that there is an uncaught exception. There should be more information on the console.
well i found a solution to this problem for who want to work with xCode 4. All what you have to do is importing frameworks from the SimulatorSDK folder /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk/System/Library/Frameworks
i don't know if it works when you try to test your app on a real iDevice, but i'm sure that it works on simulator.
ENJOY
There are a number of commonly used touch events (or gestures) that you can be notified of when you add a Gesture Recognizer to your view. They following gesture types are supported by default:
UITapGestureRecognizer
Tap (touching the screen briefly one or more times)UILongPressGestureRecognizer
Long touch (touching the screen for a long time)UIPanGestureRecognizer
Pan (moving your finger across the screen)UISwipeGestureRecognizer
Swipe (moving finger quickly)UIPinchGestureRecognizer
Pinch (moving two fingers together or apart - usually to zoom)UIRotationGestureRecognizer
Rotate (moving two fingers in a circular direction)In addition to these, you can also make your own custom gesture recognizer.
Drag a gesture recognizer from the object library onto your view.
Control drag from the gesture in the Document Outline to your View Controller code in order to make an Outlet and an Action.
This should be set by default, but also make sure that User Action Enabled is set to true for your view.
To add a gesture programmatically, you (1) create a gesture recognizer, (2) add it to a view, and (3) make a method that is called when the gesture is recognized.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// 1. create a gesture recognizer (tap gesture)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:)))
// 2. add the gesture recognizer to a view
myView.addGestureRecognizer(tapGesture)
}
// 3. this method is called when a tap is recognized
@objc func handleTap(sender: UITapGestureRecognizer) {
print("tap")
}
}
Notes
sender
parameter is optional. If you don't need a reference to the gesture then you can leave it out. If you do so, though, remove the (sender:)
after the action method name.handleTap
method was arbitrary. Name it whatever you want using action: #selector(someMethodName(sender:))
.You can study the gesture recognizers that I added to these views to see how they work.
Here is the code for that project:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tapView: UIView!
@IBOutlet weak var doubleTapView: UIView!
@IBOutlet weak var longPressView: UIView!
@IBOutlet weak var panView: UIView!
@IBOutlet weak var swipeView: UIView!
@IBOutlet weak var pinchView: UIView!
@IBOutlet weak var rotateView: UIView!
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Tap
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
tapView.addGestureRecognizer(tapGesture)
// Double Tap
let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap))
doubleTapGesture.numberOfTapsRequired = 2
doubleTapView.addGestureRecognizer(doubleTapGesture)
// Long Press
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(gesture:)))
longPressView.addGestureRecognizer(longPressGesture)
// Pan
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(gesture:)))
panView.addGestureRecognizer(panGesture)
// Swipe (right and left)
let swipeRightGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(gesture:)))
let swipeLeftGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(gesture:)))
swipeRightGesture.direction = UISwipeGestureRecognizerDirection.right
swipeLeftGesture.direction = UISwipeGestureRecognizerDirection.left
swipeView.addGestureRecognizer(swipeRightGesture)
swipeView.addGestureRecognizer(swipeLeftGesture)
// Pinch
let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(handlePinch(gesture:)))
pinchView.addGestureRecognizer(pinchGesture)
// Rotate
let rotateGesture = UIRotationGestureRecognizer(target: self, action: #selector(handleRotate(gesture:)))
rotateView.addGestureRecognizer(rotateGesture)
}
// Tap action
@objc func handleTap() {
label.text = "Tap recognized"
// example task: change background color
if tapView.backgroundColor == UIColor.blue {
tapView.backgroundColor = UIColor.red
} else {
tapView.backgroundColor = UIColor.blue
}
}
// Double tap action
@objc func handleDoubleTap() {
label.text = "Double tap recognized"
// example task: change background color
if doubleTapView.backgroundColor == UIColor.yellow {
doubleTapView.backgroundColor = UIColor.green
} else {
doubleTapView.backgroundColor = UIColor.yellow
}
}
// Long press action
@objc func handleLongPress(gesture: UILongPressGestureRecognizer) {
label.text = "Long press recognized"
// example task: show an alert
if gesture.state == UIGestureRecognizerState.began {
let alert = UIAlertController(title: "Long Press", message: "Can I help you?", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
// Pan action
@objc func handlePan(gesture: UIPanGestureRecognizer) {
label.text = "Pan recognized"
// example task: drag view
let location = gesture.location(in: view) // root view
panView.center = location
}
// Swipe action
@objc func handleSwipe(gesture: UISwipeGestureRecognizer) {
label.text = "Swipe recognized"
// example task: animate view off screen
let originalLocation = swipeView.center
if gesture.direction == UISwipeGestureRecognizerDirection.right {
UIView.animate(withDuration: 0.5, animations: {
self.swipeView.center.x += self.view.bounds.width
}, completion: { (value: Bool) in
self.swipeView.center = originalLocation
})
} else if gesture.direction == UISwipeGestureRecognizerDirection.left {
UIView.animate(withDuration: 0.5, animations: {
self.swipeView.center.x -= self.view.bounds.width
}, completion: { (value: Bool) in
self.swipeView.center = originalLocation
})
}
}
// Pinch action
@objc func handlePinch(gesture: UIPinchGestureRecognizer) {
label.text = "Pinch recognized"
if gesture.state == UIGestureRecognizerState.changed {
let transform = CGAffineTransform(scaleX: gesture.scale, y: gesture.scale)
pinchView.transform = transform
}
}
// Rotate action
@objc func handleRotate(gesture: UIRotationGestureRecognizer) {
label.text = "Rotate recognized"
if gesture.state == UIGestureRecognizerState.changed {
let transform = CGAffineTransform(rotationAngle: gesture.rotation)
rotateView.transform = transform
}
}
}
Notes
UIButton *btn;
btn.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
I'm not quite sure what your problem is, but you need to specify the parameter name like so.
-(void) changeCellText:(NSIndexPath *) nowIndex{
UILabel *content = (UILabel *)[[(UITableViewCell *)[(UITableView *)self cellForRowAtIndexPath:nowIndex] contentView] viewWithTag:contentTag];
content.text = [formatter stringFromDate:checkInDate.date];
}
Well I know this might be a big change or even not suitable for your project, but did you consider not performing the push until you already have the data? That way you only need to draw the view once and the user experience will also be better - the push will move in already loaded.
The way you do this is in the UITableView
didSelectRowAtIndexPath
you asynchronously ask for the data. Once you receive the response, you manually perform the segue and pass the data to your viewController in prepareForSegue
.
Meanwhile you may want to show some activity indicator, for simple loading indicator check https://github.com/jdg/MBProgressHUD
Actually
{
@synchronized(self) {
return [[myString retain] autorelease];
}
}
transforms directly into:
// needs #import <objc/objc-sync.h>
{
objc_sync_enter(self)
id retVal = [[myString retain] autorelease];
objc_sync_exit(self);
return retVal;
}
This API available since iOS 2.0 and imported using...
#import <objc/objc-sync.h>
Wrap a Missing Filter in the Must-Not section of a Bool Filter. It will only return documents where the field exists, and if you set the "null_value" property to true, values that are explicitly not null.
{
"query":{
"filtered":{
"query":{
"match_all":{}
},
"filter":{
"bool":{
"must":{},
"should":{},
"must_not":{
"missing":{
"field":"field1",
"existence":true,
"null_value":true
}
}
}
}
}
}
}
I use IReport to install font:
tools -> options -> fonts -> click install font
Then select the font and click
-> export as extension and type name myfont.jar
add this jar and also spring.jar* to your build path.
*copy spring.jar from Jaspersoft\iReport-3.7.0\ireport\modules\ext
There is no annotation to set default value.
You can set default value only on java class level:
public class JavaObject
{
public String notNullMember;
public String optionalMember = "Value";
}
The following code is a straight-up interpretation of the definition:
import math
def average(x):
assert len(x) > 0
return float(sum(x)) / len(x)
def pearson_def(x, y):
assert len(x) == len(y)
n = len(x)
assert n > 0
avg_x = average(x)
avg_y = average(y)
diffprod = 0
xdiff2 = 0
ydiff2 = 0
for idx in range(n):
xdiff = x[idx] - avg_x
ydiff = y[idx] - avg_y
diffprod += xdiff * ydiff
xdiff2 += xdiff * xdiff
ydiff2 += ydiff * ydiff
return diffprod / math.sqrt(xdiff2 * ydiff2)
Test:
print pearson_def([1,2,3], [1,5,7])
returns
0.981980506062
This agrees with Excel, this calculator, SciPy (also NumPy), which return 0.981980506 and 0.9819805060619657, and 0.98198050606196574, respectively.
R:
> cor( c(1,2,3), c(1,5,7))
[1] 0.9819805
EDIT: Fixed a bug pointed out by a commenter.
If you want to run on a specific port 60535 while developing locally but want to run app on port 80 in stage/prod environment servers, this does it.
Add to environmentVariables section in launchSettings.json
"ASPNETCORE_DEVELOPER_OVERRIDES": "Developer-Overrides",
and then modify Program.cs to
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseKestrel(options =>
{
var devOverride = Environment.GetEnvironmentVariable("ASPNETCORE_DEVELOPER_OVERRIDES");
if (!string.IsNullOrWhiteSpace(devOverride))
{
options.ListenLocalhost(60535);
}
else
{
options.ListenAnyIP(80);
}
})
.UseStartup<Startup>()
.UseNLog();
});
It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.
It is indeed possible to have PHP render partials and whole views, but I would not recommend it.
To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.
I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.
Using PHP to render the view:
/user/account
if($loggedIn)
{
echo "<p>Logged in as ".$user."</p>";
}
else
{
echo "Please log in.";
}
How the same problem can be solved with an API centric approach by outputting JSON like this:
api/auth/
{
authorized:true,
user: {
username: 'Joe',
securityToken: 'secret'
}
}
and in Angular you could do a get, and handle the response client side.
$http.post("http://example.com/api/auth", {})
.success(function(data) {
$scope.isLoggedIn = data.authorized;
});
To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.
The identity (===)
operator behaves identically to the equality (==)
operator except no type conversion is done, and the types must be the same to be considered equal.
This works successfully.
INSERT INTO DestinationDB.dbo.DestinationTable (col1,col1)
SELECT Src-col1,Src-col2 FROM SourceDB.dbo.SourceTable
For a servlet or a JSP page you can get querystring key/value pairs by using request.getParameter("paramname")
String name = request.getParameter("name");
There are other ways of doing it but that's the way I do it in all the servlets and jsp pages that I create.
public static void main(String[] args) {
int hex = 0x123456;
int r = (hex & 0xFF0000) >> 16;
int g = (hex & 0xFF00) >> 8;
int b = (hex & 0xFF);
}
If you don't have the latest Homebrew: I "fixed" this in the past by forcing Homebrew to run as root, which could only be done by changing the ownership of the Homebrew executables to root. At some point, they removed this feature.
And I know they'll give lots of warnings saying it shouldn't run as root, but c'mon, it doesn't work properly otherwise.
A double quote to the left of the text you want to comment.
Example:
" this is how a comment looks like in ~/.vimrc
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
formatter.setLenient(false);
try {
Date date= formatter.parse("02/03/2010");
} catch (ParseException e) {
//If input date is in different format or invalid.
}
formatter.setLenient(false) will enforce strict matching.
If you are using Joda-Time -
private boolean isValidDate(String dateOfBirth) {
boolean valid = true;
try {
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
DateTime dob = formatter.parseDateTime(dateOfBirth);
} catch (Exception e) {
valid = false;
}
return valid;
}
ANDROID_HOME
is deprecated now instead of using ANDROID_HOME
use ANDROID_SDK_ROOT
as per Google android documentation -
ANDROID_SDK_ROOT
sets the path to the SDK installation directory. Once set, the value does not typically change, and can be shared by multiple users on the same machine. ANDROID_HOME, which also points to the SDK installation directory, is deprecated.
If you continue to use it, the following rules apply:
ANDROID_HOME
is defined and contains a valid SDK installation, its value is used instead of the value in ANDROID_SDK_ROOT
.ANDROID_HOME
is not defined, the value in ANDROID_SDK_ROOT
is used.ANDROID_HOME
is defined but does not exist or does not contain a valid SDK installation, the value in ANDROID_SDK_ROOT
is used instead.For details follow this Android Documentation link
Regarding the issue about multiple return values in general I usually use a small helper class that wraps a single return value and is passed as parameter to the method:
public class ReturnParameter<T> {
private T value;
public ReturnParameter() { this.value = null; }
public ReturnParameter(T initialValue) { this.value = initialValue; }
public void set(T value) { this.value = value; }
public T get() { return this.value; }
}
(for primitive datatypes I use minor variations to directly store the value)
A method that wants to return multiple values would then be declared as follows:
public void methodThatReturnsTwoValues(ReturnParameter<ClassA> nameForFirstValueToReturn, ReturnParameter<ClassB> nameForSecondValueToReturn) {
//...
nameForFirstValueToReturn.set("...");
nameForSecondValueToReturn.set("...");
//...
}
Maybe the major drawback is that the caller has to prepare the return objects in advance in case he wants to use them (and the method should check for null pointers)
ReturnParameter<ClassA> nameForFirstValue = new ReturnParameter<ClassA>();
ReturnParameter<ClassB> nameForSecondValue = new ReturnParameter<ClassB>();
methodThatReturnsTwoValues(nameForFirstValue, nameForSecondValue);
Advantages (in comparison to other solutions proposed):
I would like to offer a minor improvement on the last loop answer given in the previous post (that post is correct and should still be accepted). The implicit assumption made when labeling the last example is that plt.label(LIST)
puts label number X in LIST
with the line corresponding to the Xth time plot
was called. I have run into problems with this approach before. The recommended way to build legends and customize their labels per matplotlibs documentation ( http://matplotlib.org/users/legend_guide.html#adjusting-the-order-of-legend-item) is to have a warm feeling that the labels go along with the exact plots you think they do:
...
# Plot several different functions...
labels = []
plotHandles = []
for i in range(1, num_plots + 1):
x, = plt.plot(some x vector, some y vector) #need the ',' per ** below
plotHandles.append(x)
labels.append(some label)
plt.legend(plotHandles, labels, 'upper left',ncol=1)
dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))
na.omit(dat)
x1 x2
1 1 100
3 3 300
5 5 500
You'll have to pass the new ordinal position to insert
using len
in this case:
In [62]:
a=[1,2,3,4]
a.insert(len(a),5)
a
Out[62]:
[1, 2, 3, 4, 5]
It is possible you use the bash program, with the parameter -c for execute the commands:
bashCommand = "cwm --rdf test.rdf --ntriples > test.nt"
output = subprocess.check_output(['bash','-c', bashCommand])
Also:
maps.google.com has a navigation service which can provide you route information in KML format.
To get kml file we need to form url with start and destination locations:
public static String getUrl(double fromLat, double fromLon,
double toLat, double toLon) {// connect to map web service
StringBuffer urlString = new StringBuffer();
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr=");// from
urlString.append(Double.toString(fromLat));
urlString.append(",");
urlString.append(Double.toString(fromLon));
urlString.append("&daddr=");// to
urlString.append(Double.toString(toLat));
urlString.append(",");
urlString.append(Double.toString(toLon));
urlString.append("&ie=UTF8&0&om=0&output=kml");
return urlString.toString();
}
Next you will need to parse xml (implemented with SAXParser) and fill data structures:
public class Point {
String mName;
String mDescription;
String mIconUrl;
double mLatitude;
double mLongitude;
}
public class Road {
public String mName;
public String mDescription;
public int mColor;
public int mWidth;
public double[][] mRoute = new double[][] {};
public Point[] mPoints = new Point[] {};
}
Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:
public static String getUrl(double fromLat, double fromLon,
double toLat, double toLon)
then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:
public static Road getRoute(InputStream is)
Full source code RoadProvider.java
class MapPathScreen extends MainScreen {
MapControl map;
Road mRoad = new Road();
public MapPathScreen() {
double fromLat = 49.85, fromLon = 24.016667;
double toLat = 50.45, toLon = 30.523333;
String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
map = new MapControl();
add(new LabelField(mRoad.mName));
add(new LabelField(mRoad.mDescription));
add(map);
}
protected void onUiEngineAttached(boolean attached) {
super.onUiEngineAttached(attached);
if (attached) {
map.drawPath(mRoad);
}
}
private InputStream getConnection(String url) {
HttpConnection urlConnection = null;
InputStream is = null;
try {
urlConnection = (HttpConnection) Connector.open(url);
urlConnection.setRequestMethod("GET");
is = urlConnection.openInputStream();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
}
See full code on J2MEMapRouteBlackBerryEx on Google Code
public class MapRouteActivity extends MapActivity {
LinearLayout linearLayout;
MapView mapView;
private Road mRoad;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
new Thread() {
@Override
public void run() {
double fromLat = 49.85, fromLon = 24.016667;
double toLat = 50.45, toLon = 30.523333;
String url = RoadProvider
.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
mHandler.sendEmptyMessage(0);
}
}.start();
}
Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
TextView textView = (TextView) findViewById(R.id.description);
textView.setText(mRoad.mName + " " + mRoad.mDescription);
MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
};
};
private InputStream getConnection(String url) {
InputStream is = null;
try {
URLConnection conn = new URL(url).openConnection();
is = conn.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
}
See full code on J2MEMapRouteAndroidEx on Google Code
you can use _.range([optional] start, end)
. It creates a new Minified list containing an interval of numbers from start (inclusive) until the end (exclusive). Here I am using lodash.js ._range()
method.
Example:
CODE
var dayOfMonth = _.range(1,32); // It creates a new list from 1 to 31.
//HTML Now, you can use it in For loop
<div *ngFor="let day of dayOfMonth">{{day}}</div>
Update: Please see marked answer as a better solution to implement this. The following solution is no longer required.
Converting the json date to this format "mm/dd/yyyy HH:MM:ss"
dateFormat is a jasondate format.js file found at blog.stevenlevithan.com
var _meetStartTime = dateFormat(now, "mm/dd/yyyy HH:MM:ss");
The following uses EventTrigger
to show the Popup
. This means we don't need a ToggleButton
for state binding.
In this example the Click
event of a Button
is used. You can adapt it to use another element/event combination.
<Button x:Name="OpenPopup">Popup
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames
Storyboard.TargetName="ContextPopup"
Storyboard.TargetProperty="IsOpen">
<DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="True" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Button.Triggers>
</Button>
<Popup x:Name="ContextPopup"
PlacementTarget="{Binding ElementName=OpenPopup}"
StaysOpen="False">
<Label>Popupcontent...</Label>
</Popup>
Please note that the Popup
is referencing the Button
by name and vice versa. So x:Name="..."
is required on both, the Popup
and the Button
.
It can actually be further simplified by replacing the Storyboard
stuff with a custom SetProperty
EventTrigger Action described in this SO Answer
This more of a very important comment
Key to understanding why vitaminwater's answer works are three things:
contentOffset
is likely nothing but: func setContentOffset(offset: CGPoint)
{
CGRect bounds = self.bounds
bounds.origin = offset
self.bounds = bounds
}
For more see objc scrollview and understanding scrollview
Combining the three together you'd easily understand that you need allow the the textView's intrinsic contentSize to work along AutoLayout constraints of the textView to drive the logic. It's almost as if you're textView is functioning like a UILabel
To make that happen you need to disable scrolling which basically means the scrollView's size, the contentSize's size and in case of adding a containerView, then the containerView's size would all be the same. When they're the same you have NO scrolling. And you'd have 0
contentOffset
. Having 0
contentOffSet
means you've not scrolled down. Not even a 1 point down! As a result the textView will be all stretched out.
It's also worth nothing that 0
contentOffset
means that the scrollView's bounds and frame are identical.
If you scroll down 5 points then your contentOffset would be 5
, while your scrollView.bounds.origin.y - scrollView.frame.origin.y
would be equal to 5
You can use the files from debug folder,however if you look at app debug informations with some inspection software,you can clearly see "Symbols File Name" which can reveals not wanted informations in path to the original exe file.
You can use this method to create hidden text field with/without form. If you need form just pass form with object status = true
.
You can also add multiple hidden fields. Use this way:
CustomizePPT.setHiddenFields(
{
"hidden" :
{
'fieldinFORM' : 'thisdata201' ,
'fieldinFORM2' : 'this3' //multiple hidden fields
.
.
.
.
.
'nNoOfFields' : 'nthData'
},
"form" :
{
"status" : "true",
"formID" : "form3"
}
} );
var CustomizePPT = new Object();_x000D_
CustomizePPT.setHiddenFields = function(){ _x000D_
var request = [];_x000D_
var container = '';_x000D_
console.log(arguments);_x000D_
request = arguments[0].hidden;_x000D_
console.log(arguments[0].hasOwnProperty('form'));_x000D_
if(arguments[0].hasOwnProperty('form') == true)_x000D_
{_x000D_
if(arguments[0].form.status == 'true'){_x000D_
var parent = document.getElementById("container");_x000D_
container = document.createElement('form');_x000D_
parent.appendChild(container);_x000D_
Object.assign(container, {'id':arguments[0].form.formID});_x000D_
}_x000D_
}_x000D_
else{_x000D_
container = document.getElementById("container");_x000D_
}_x000D_
_x000D_
//var container = document.getElementById("container");_x000D_
Object.keys(request).forEach(function(elem)_x000D_
{_x000D_
if($('#'+elem).length <= 0){_x000D_
console.log("Hidden Field created");_x000D_
var input = document.createElement('input');_x000D_
Object.assign(input, {"type" : "text", "id" : elem, "value" : request[elem]});_x000D_
container.appendChild(input);_x000D_
}else{_x000D_
console.log("Hidden Field Exists and value is below" );_x000D_
$('#'+elem).val(request[elem]);_x000D_
}_x000D_
});_x000D_
};_x000D_
_x000D_
CustomizePPT.setHiddenFields( { "hidden" : {'fieldinFORM' : 'thisdata201' , 'fieldinFORM2' : 'this3'}, "form" : {"status" : "true","formID" : "form3"} } );_x000D_
CustomizePPT.setHiddenFields( { "hidden" : {'withoutFORM' : 'thisdata201','withoutFORM2' : 'this2'}});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id='container'>_x000D_
_x000D_
</div>
_x000D_
=IF(ISNUMBER(SEARCH(LEFT(H2,3),I2)),"YES","NO")))
In case your data are stored as a Pandas DataFrame
, you can use remove_stopwords
from textero that use the NLTK stopwords list by default.
import pandas as pd
import texthero as hero
df['text_without_stopwords'] = hero.remove_stopwords(df['text'])
I had the same issues but nothing worked. What I did was I added this to the selector:
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
SELECT min (id) AS 'ID', min(sku) AS 'SKU', Product
FROM TestData
WHERE sku LIKE 'FOO%' -- If you want only the sku that matchs with FOO%
GROUP BY product
ORDER BY 'ID'
Well, after studying several examples on the Internet describing how to output messages from a GUI in Qt to stdout, I have refined a working stand-alone example on redirecting messages to a console, via qDebug() and installing qInstallMessageHandler(). The console will be showed at the same time as the GUI and can be hidden if deemed necessary. The code is easy to integrate with existing code in your project. Here is the full sample and feel free to use it in any way as you like, as long as you adhere to the License GNU GPL v2. You have to use a form of some sort and a MainWindow I think - otherwise the sample will run, but probably crash when forced to quit. Note: there is no way to quit via a close button or a menu close because I have tested those alternatives and the application will crash eventually every now and then. Without the close button the application will be stable and you can close it down from the main window. Enjoy!
#include "mainwindow.h"
#include <QApplication>
//GNU GPL V2, 2015-02-07
#include <QMessageBox>
#include <windows.h>
#define CONSOLE_COLUMNS 80
#define CONSOLE_ROWS 5000
#define YOURCONSOLETITLE "Your_Console_Title"
typedef struct{
CONSOLE_SCREEN_BUFFER_INFOEX conScreenBuffInfoEX;
HANDLE con_screenbuf;
HWND hwndConsole;
HMENU consoleMenu ;
QString consoleTitle;
QMessageBox mBox;
QString localMsg;
QString errorMessage;
WINBOOL errorCode;
} consoleT;
static consoleT *console;
BOOL WINAPI catchCTRL( DWORD ctrlMsg ){
if( ctrlMsg == CTRL_C_EVENT ){
HWND hwndWin = GetConsoleWindow();
ShowWindow(hwndWin,SW_FORCEMINIMIZE);
}
return TRUE;
}
void removeCloseMenu(){
int i;
for( i = 0; i < 10; i++){
console->hwndConsole = FindWindowW( NULL, console->consoleTitle.toStdWString().data());
if(console->hwndConsole != NULL)
break;
}
if( !(console->errorCode = 0) && (console->hwndConsole == NULL))
console->errorMessage += QString("\nFindWindowW error: %1 \n").arg(console->errorCode);
if( !(console->errorCode = 0) && !(console->consoleMenu = GetSystemMenu( console->hwndConsole, FALSE )) )
console->errorMessage += QString("GetSystemMenu error: %1 \n").arg(console->errorCode);
if(!(console->errorCode = DeleteMenu( console->consoleMenu, SC_CLOSE, MF_BYCOMMAND )))
console->errorMessage += QString("DeleteMenu error: %1 \n").arg(console->errorCode);
}
void initialiseConsole(){
console->conScreenBuffInfoEX.cbSize = sizeof(CONSOLE_SCREEN_BUFFER_INFOEX);
console->consoleMenu = NULL;
console->consoleTitle = YOURCONSOLETITLE;
console->con_screenbuf = INVALID_HANDLE_VALUE;
console->errorCode = 0;
console->errorMessage = "";
console->hwndConsole = NULL;
console->localMsg = "";
if(!(console->errorCode = FreeConsole()))
console->errorMessage += QString("\nFreeConsole error: %1 \n").arg(console->errorCode);
if(!(console->errorCode = AllocConsole()))
console->errorMessage += QString("\nAllocConsole error: %1 \n").arg(console->errorCode);
if( (console->errorCode = -1) && (INVALID_HANDLE_VALUE ==(console->con_screenbuf = CreateConsoleScreenBuffer( GENERIC_WRITE | GENERIC_READ,0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL))))
console->errorMessage += QString("\nCreateConsoleScreenBuffer error: %1 \n").arg(console->errorCode);
if(!(console->errorCode = SetConsoleActiveScreenBuffer(console->con_screenbuf)))
console->errorMessage += QString("\nSetConsoleActiveScreenBuffer error: %1 \n").arg(console->errorCode);
if(!(console->errorCode = GetConsoleScreenBufferInfoEx(console->con_screenbuf, &console->conScreenBuffInfoEX)))
console->errorMessage += QString("\nGetConsoleScreenBufferInfoEx error: %1 \n").arg(console->errorCode);
console->conScreenBuffInfoEX.dwSize.X = CONSOLE_COLUMNS;
console->conScreenBuffInfoEX.dwSize.Y = CONSOLE_ROWS;
if(!(console->errorCode = SetConsoleScreenBufferInfoEx(console->con_screenbuf, &console->conScreenBuffInfoEX)))
console->errorMessage += QString("\nSetConsoleScreenBufferInfoEx error: %1 \n").arg(console->errorCode);
if(!(console->errorCode = SetConsoleTitleW(console->consoleTitle.toStdWString().data())))
console->errorMessage += QString("SetConsoleTitle error: %1 \n").arg(console->errorCode);
SetConsoleCtrlHandler(NULL, FALSE);
SetConsoleCtrlHandler(catchCTRL, TRUE);
removeCloseMenu();
if(console->errorMessage.length() > 0){
console->mBox.setText(console->errorMessage);
console->mBox.show();
}
}
void messageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg){
if((console->con_screenbuf != INVALID_HANDLE_VALUE)){
switch (type) {
case QtDebugMsg:
console->localMsg = console->errorMessage + "Debug: " + msg;
WriteConsoleW(console->con_screenbuf, console->localMsg.toStdWString().data(), console->localMsg.toStdWString().length(), NULL, NULL );
WriteConsoleA(console->con_screenbuf, "\n--\n", 4, NULL, NULL );
break;
case QtWarningMsg:
console->localMsg = console->errorMessage + "Warning: " + msg;
WriteConsoleW(console->con_screenbuf, console->localMsg.toStdWString().data(), console->localMsg.toStdWString().length() , NULL, NULL );
WriteConsoleA(console->con_screenbuf, "\n--\n", 4, NULL, NULL );
break;
case QtCriticalMsg:
console->localMsg = console->errorMessage + "Critical: " + msg;
WriteConsoleW(console->con_screenbuf, console->localMsg.toStdWString().data(), console->localMsg.toStdWString().length(), NULL, NULL );
WriteConsoleA(console->con_screenbuf, "\n--\n", 4, NULL, NULL );
break;
case QtFatalMsg:
console->localMsg = console->errorMessage + "Fatal: " + msg;
WriteConsoleW(console->con_screenbuf, console->localMsg.toStdWString().data(), console->localMsg.toStdWString().length(), NULL, NULL );
WriteConsoleA(console->con_screenbuf, "\n--\n", 4, NULL, NULL );
abort();
}
}
}
int main(int argc, char *argv[])
{
qInstallMessageHandler(messageHandler);
QApplication a(argc, argv);
console = new consoleT();
initialiseConsole();
qDebug() << "Hello World!";
MainWindow w;
w.show();
return a.exec();
}
Declare an instance of MyClass, and then call the member function on that instance:
MyClass m;
m.printInformation();
I have been load testing a server application (on linux) by using a test program with 20 threads.
In 959,000 connect / close cycles I had 44,000 failed connections and many thousands of sockets in TIME_WAIT.
I set SO_LINGER to 0 before the close call and in subsequent runs of the test program had no connect failures and less than 20 sockets in TIME_WAIT.
Array initializer support for type inference were changed in Visual Basic 10 vs Visual Basic 9.
In previous version of VB it was required to put empty parens to signify an array. Also, it would define the array as object array unless otherwise was stated:
' Integer array
Dim i as Integer() = {1, 2, 3, 4}
' Object array
Dim o() = {1, 2, 3}
Check more info:
Also be sure to check out the OWASP Top 10 List for a categorization of all the main attack vectors/vulnerabilities.
These things are fascinating to read about. Learning to think like an attacker will train you of what to think about as you're writing your own code.
You should use the current sys
catalog views (if you're on SQL Server 2005 or newer - the sysobjects
views are deprecated and should be avoided) - check out the extensive MSDN SQL Server Books Online documentation on catalog views here.
There are quite a few views you might be interested in:
sys.default_constraints
for default constraints on columnssys.check_constraints
for check constraints on columnssys.key_constraints
for key constraints (e.g. primary keys)sys.foreign_keys
for foreign key relationsand a lot more - check it out!
You can query and join those views to get the info needed - e.g. this will list the tables, columns and all default constraints defined on them:
SELECT
TableName = t.Name,
ColumnName = c.Name,
dc.Name,
dc.definition
FROM sys.tables t
INNER JOIN sys.default_constraints dc ON t.object_id = dc.parent_object_id
INNER JOIN sys.columns c ON dc.parent_object_id = c.object_id AND c.column_id = dc.parent_column_id
ORDER BY t.Name
use chomp
or strip
functions from Ruby:
"abcd\n".chomp => "abcd"
"abcd\n".strip => "abcd"
Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin
not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors
at your server side.
You can fetch request using mode: 'cors'
. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.
So in both condition you need to configure cors
in your server or you need to use custom proxy server.
I had a great deal of trouble linking to MySQL from a 64 bit laptop, running Windows 7, using MS Access 2010. I found the previous article very helpful, but still could not connect using odbc 3.5.1. As I had previously linked a 32 bit machine using Connector/ODBC 5.1.13, I downloaded that version and set it up using the instructions above. Success. The answer seems to be to try different versions of Connector.odbc.
All the other answers are correct: use call. For example:
call "msbuild.bat"
History
In ancient DOS versions it was not possible to recursively execute batch files. Then the call command was introduced that called another cmd shell to execute the batch file and returned execution back to the calling cmd shell when finished.
Obviously in later versions no other cmd shell was necessary anymore.
In the early days many batch files depended on the fact that calling a batch file would not return to the calling batch file. Changing that behaviour without additional syntax would have broken many systems like batch menu systems (using batch files for menu structures).
As in many cases with Microsoft, backward compatibility therefore is the reason for this behaviour.
Tips
If your batch files have spaces in their names, use quotes around the name:
call "unit tests.bat"
By the way: if you do not have all the names of the batch files, you could also use for to do this (it does not guarantee the correct order of batch file calls; it follows the order of the file system):
FOR %x IN (*.bat) DO call "%x"
You can also react on errorlevels after a call. Use:
exit /B 1 # Or any other integer value in 0..255
to give back an errorlevel. 0 denotes correct execution. In the calling batch file you can react using
if errorlevel neq 0 <batch command>
Use if errorlevel 1
if you have an older Windows than NT4/2000/XP to catch all errorlevels 1 and greater.
To control the flow of a batch file, there is goto :-(
if errorlevel 2 goto label2
if errorlevel 1 goto label1
...
:label1
...
:label2
...
As others pointed out: have a look at build systems to replace batch files.
SQL Server Management Studio provides an Import/Export wizard tool which have an option to automatically create tables.
You can access it by right clicking on the Database in Object Explorer and selecting Tasks->Import Data...
From there wizard should be self-explanatory and easy to navigate. You choose your CSV as source, desired destination, configure columns and run the package.
If you need detailed guidance, there are plenty of guides online, here is a nice one: http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/
There is a JDK socket tutorial here, which covers both the server and client end. That looks exactly like what you want.
(from that tutorial) This sets up to read from an echo server:
echoSocket = new Socket("taranis", 7);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
taking a stream of bytes and converts to strings via the reader and using a default encoding (not advisable, normally).
Error handling and closing sockets/streams omitted from the above, but check the tutorial.
If you want to avoid duplicates in future. Create another column say id2.
UPDATE tablename SET id2 = id;
Now add the unique on two columns:
alter table tablename add unique index(columnname, id2);
Maybe you want to try this way, but Apple might warn you about accessing private ivar:
[self.myTextField setValue:[UIColor darkGrayColor]
forKeyPath:@"_placeholderLabel.textColor"];
NOTE
This is not working on iOS 7 anymore, according to Martin Alléus.
Without seeing said object list, I believe you should be binding to the DataGrid's ItemsSource
property, not its DataContext
.
<DataGrid x:Name="Imported" VerticalAlignment="Top" ItemsSource="{Binding Source=list}" AutoGenerateColumns="False" CanUserResizeColumns="True">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
<DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
</DataGrid.Columns>
</DataGrid>
(This assumes that the element [UserControl, etc.] that contains the DataGrid has its DataContext bound to an object that contains the list
collection. The DataGrid is derived from ItemsControl
, which relies on its ItemsSource
property to define the collection it binds its rows to. Hence, if list
isn't a property of an object bound to your control's DataContext, you might need to set both DataContext={Binding list}
and ItemsSource={Binding list}
on the DataGrid...)
Don't set the style object itself, set the background color property of the style object that is a property of the element.
And yes, even though you said no, jquery and tablesorter with its zebra stripe plugin can do this all for you in 3 lines of code.
And just setting the class attribute would be better since then you have non-hard-coded control over the styling which is more organized
You could do the following:
pg_dump -h <host ip address> -U <host db user name> -t <host table> > <host database> | psql -h localhost -d <local database> -U <local db user>
@mixin box-shadow($args...) {
@each $pre in -webkit-, -moz-, -ms-, -o- {
#{$pre + box-shadow}: $args;
}
#{box-shadow}: #{$args};
}
And now you can reuse your box-shadow even smarter:
.myShadow {
@include box-shadow(2px 2px 5px #555, inset 0 0 0);
}
First, create staticfiles folder. Inside that folder create css, js, and img folder.
settings.py
import os
PROJECT_DIR = os.path.dirname(__file__)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(PROJECT_DIR, 'myweblabdev.sqlite'),
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(PROJECT_DIR, 'staticfiles'),
)
main urls.py
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from myweblab import settings
admin.autodiscover()
urlpatterns = patterns('',
.......
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
template
{% load static %}
<link rel="stylesheet" href="{% static 'css/style.css' %}">
I think you could do it using a specs file.
Under MinGW you could run
gcc -dumpspecs > specs
Where it says
*cpp:
%{posix:-D_POSIX_SOURCE} %{mthreads:-D_MT}
You change it to
*cpp:
%{posix:-D_POSIX_SOURCE} %{mthreads:-D_MT} -std=c++11
And then place it in
/mingw/lib/gcc/mingw32/<version>/specs
I'm sure you could do the same without a MinGW build. Not sure where to place the specs file though.
The folder is probably either /gcc/lib/ or /gcc/.
What if you have your data in CSV format and convert it to HTML for display on the web page? You may use the http://code.google.com/p/js-tables/ plugin. Check this example http://code.google.com/p/js-tables/wiki/Table As you are already using jQuery library I have assumed you are able to add other javascript toolkit libraries.
If the data is in CSV format, you should be able to use the generic 'application/octetstream' mime type. All the 3 mime types you have tried are dependent on the software installed on the clients computer.
You could do this but the T
generic parameter needs to be declared at the containing class:
public class Foo<T>
{
public List<T> NewList { get; set; }
}
There's an Excel OLEDB data provider built into Windows; you can use this to 'query' the Excel sheet via ADO.NET and write the results to a CSV file. There's a small amount of coding required, but you shouldn't need to install anything on the machine.
This is no longer possible. GitHub has explicitly disabled JavaScript hotlinking, and newer versions of browsers respect that setting.
Heads up: nosniff header support coming to Chrome and Firefox
Use jquery event call. Write the below line where you want to trigger onChange of any element.
$("#element_id").change();
element_id is the ID of the element whose onChange you want to trigger.
Avoid the use of
element.fireEvent("onchange");
Because it has very less support. Refer this document for its support.
try this..
$(element).find("option:contains(" + theText+ ")").attr('selected', 'selected');
I was getting the error:
NameError: uninitialized constant
Then I noticed that I had accidentally created a plural model so I went back and renamed the model file to singular and also changed the class name in the model file to singular and that solved it.
/*this code is written in Turbo C++
For Visual Studio, code is in comment*/
int a[10],ct=0,x=10,y=10; //x,y can be any value, but within the range of
//array declared
randomize(); //there is no need to use this Visual Studio
for(int i=0;i<10;i++)
{ a[i]=random(10); //use a[i]=rand()%10 for Visual Studio
}
cout<<"\n\n";
do
{ ct=0;
for(i=0;i<x;i++)
{ for(int j=0;j<y;j++)
{ if(a[i]==a[j]&&i!=j)
{ a[j]=random(10); //use a[i]=rand()%10 for Visual Studio
}
else
{ ct++;
}
}
}
}while(!(ct==(x*y)));
Well I'm not a pro in C++, but learnt it in school. I am using this algo for past 1 year to store different random values in a 1D array, but this will also work in 2D array after some changes. Any suggestions about the code are welcome.
Just add AsEnumerable() andToList() , so it looks like this
db.Favorites
.Where(x => x.userId == userId)
.Join(db.Person, x => x.personId, y => y.personId, (x, y).ToList().AsEnumerable()
ToList().AsEnumerable()
Nope. Extension method definitions require an instance of the type you're extending. It's unfortunate; I'm not sure why it's required...
Here's a very nice Gist that covers all the possible cases: https://gist.github.com/nepsilon/156387acf9e1e72d48fa35c4fabef0b4
Overview:
git rebase -i HEAD~X
# X is the number of commits to go back
# Move to the line of your commit, change pick into edit,
# then change your commit message:
git commit --amend
# Finish the rebase with:
git rebase --continue
For clean code, you might make use of the javascript file here: http://rafael.adm.br/css_browser_selector/ By including the line:
<script src="css_browser_selector.js" type="text/javascript"></script>
You can write subsequent css with the following simple pattern:
.ie7 [thing] {
background-color: orange
}
.chrome [thing] {
background-color: gray
}
The last suggestion is the correct solution. Just to repeat, first set android:focusable="true"
in the layout xml
file, then requestFocus()
on the view in your code.
With jquery you can easy detect copy, paste, etc by binding the function:
$("#textA").bind('copy', function() {
$('span').text('copy behaviour detected!')
});
$("#textA").bind('paste', function() {
$('span').text('paste behaviour detected!')
});
$("#textA").bind('cut', function() {
$('span').text('cut behaviour detected!')
});
More information here: http://www.mkyong.com/jquery/how-to-detect-copy-paste-and-cut-behavior-with-jquery/
Writing and Reading file content
def writeTempFile(text = ''):
filePath = "/temp/file1.txt"
if not text: # If blank return file content
f = open(filePath, "r")
slug = f.read()
return slug
else:
f = open(filePath, "a") # Create a blank file
f.seek(0) # sets point at the beginning of the file
f.truncate() # Clear previous content
f.write(text) # Write file
f.close() # Close file
return text
It Worked for me
The two methods previously described are not enough today. I personnally use :
input[type="text"]{
background-color: transparent;
border: 0px;
outline: none;
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
width:5px;
color:transparent;
cursor:default;
}
It also removes the shadow set on some browsers, hide the text that could be input and make the cursor behave as if the input was not there.
You may want to set width to 0px also.
First off, you need to implement INotifyPropertyChanged
interface in your view model and raise the PropertyChanged
event in the setter of the Rule
property. Otherwise no control that binds to the SelectedRule
property will "know" when it has been changed.
Then, your XAML
<TextBlock Text="{Binding Path=SelectedRule.Name}" />
is perfectly valid if this TextBlock
is outside the ListBox
's ItemTemplate
and has the same DataContext
as the ListBox
.
You could perhaps use something like
interface EnumWithId {
public int getId();
}
enum Foo implements EnumWithId {
...
}
That would reduce the need for reflection in your utility class.
The right thing would be to use a "if defined" statement, which is used to test for the existence of a variable. For example:
IF DEFINED somevariable echo Value exists
In this particular case, the negative form should be used:
IF NOT DEFINED somevariable echo Value missing
PS: the variable name should be used without "%" caracters.
Both are shorthands for longer expressions.
?:
is short for $a ? $a : $b
. This expression will evaluate to $a if $a evaluates to TRUE.
??
is short for isset($a) ? $a : $b
. This expression will evaluate to $a if $a is set and not null.
Their use cases overlaps when $a is undefined or null. When $a is undefined ??
will not produce an E_NOTICE, but the results are the same. When $a is null the result is the same.
Use this, one function solve all problems of comma and quote:
public static DataTable CsvToDataTable(string strFilePath)
{
if (File.Exists(strFilePath))
{
string[] Lines;
string CSVFilePathName = strFilePath;
Lines = File.ReadAllLines(CSVFilePathName);
while (Lines[0].EndsWith(","))
{
Lines[0] = Lines[0].Remove(Lines[0].Length - 1);
}
string[] Fields;
Fields = Lines[0].Split(new char[] { ',' });
int Cols = Fields.GetLength(0);
DataTable dt = new DataTable();
//1st row must be column names; force lower case to ensure matching later on.
for (int i = 0; i < Cols; i++)
dt.Columns.Add(Fields[i], typeof(string));
DataRow Row;
int rowcount = 0;
try
{
string[] ToBeContinued = new string[]{};
bool lineToBeContinued = false;
for (int i = 1; i < Lines.GetLength(0); i++)
{
if (!Lines[i].Equals(""))
{
Fields = Lines[i].Split(new char[] { ',' });
string temp0 = string.Join("", Fields).Replace("\"\"", "");
int quaotCount0 = temp0.Count(c => c == '"');
if (Fields.GetLength(0) < Cols || lineToBeContinued || quaotCount0 % 2 != 0)
{
if (ToBeContinued.GetLength(0) > 0)
{
ToBeContinued[ToBeContinued.Length - 1] += "\n" + Fields[0];
Fields = Fields.Skip(1).ToArray();
}
string[] newArray = new string[ToBeContinued.Length + Fields.Length];
Array.Copy(ToBeContinued, newArray, ToBeContinued.Length);
Array.Copy(Fields, 0, newArray, ToBeContinued.Length, Fields.Length);
ToBeContinued = newArray;
string temp = string.Join("", ToBeContinued).Replace("\"\"", "");
int quaotCount = temp.Count(c => c == '"');
if (ToBeContinued.GetLength(0) >= Cols && quaotCount % 2 == 0 )
{
Fields = ToBeContinued;
ToBeContinued = new string[] { };
lineToBeContinued = false;
}
else
{
lineToBeContinued = true;
continue;
}
}
//modified by Teemo @2016 09 13
//handle ',' and '"'
//Deserialize CSV following Excel's rule:
// 1: If there is commas in a field, quote the field.
// 2: Two consecutive quotes indicate a user's quote.
List<int> singleLeftquota = new List<int>();
List<int> singleRightquota = new List<int>();
//combine fileds if number of commas match
if (Fields.GetLength(0) > Cols)
{
bool lastSingleQuoteIsLeft = true;
for (int j = 0; j < Fields.GetLength(0); j++)
{
bool leftOddquota = false;
bool rightOddquota = false;
if (Fields[j].StartsWith("\""))
{
int numberOfConsecutiveQuotes = 0;
foreach (char c in Fields[j]) //start with how many "
{
if (c == '"')
{
numberOfConsecutiveQuotes++;
}
else
{
break;
}
}
if (numberOfConsecutiveQuotes % 2 == 1)//start with odd number of quotes indicate system quote
{
leftOddquota = true;
}
}
if (Fields[j].EndsWith("\""))
{
int numberOfConsecutiveQuotes = 0;
for (int jj = Fields[j].Length - 1; jj >= 0; jj--)
{
if (Fields[j].Substring(jj,1) == "\"") // end with how many "
{
numberOfConsecutiveQuotes++;
}
else
{
break;
}
}
if (numberOfConsecutiveQuotes % 2 == 1)//end with odd number of quotes indicate system quote
{
rightOddquota = true;
}
}
if (leftOddquota && !rightOddquota)
{
singleLeftquota.Add(j);
lastSingleQuoteIsLeft = true;
}
else if (!leftOddquota && rightOddquota)
{
singleRightquota.Add(j);
lastSingleQuoteIsLeft = false;
}
else if (Fields[j] == "\"") //only one quota in a field
{
if (lastSingleQuoteIsLeft)
{
singleRightquota.Add(j);
}
else
{
singleLeftquota.Add(j);
}
}
}
if (singleLeftquota.Count == singleRightquota.Count)
{
int insideCommas = 0;
for (int indexN = 0; indexN < singleLeftquota.Count; indexN++)
{
insideCommas += singleRightquota[indexN] - singleLeftquota[indexN];
}
if (Fields.GetLength(0) - Cols >= insideCommas) //probabaly matched
{
int validFildsCount = insideCommas + Cols; //(Fields.GetLength(0) - insideCommas) may be exceed the Cols
String[] temp = new String[validFildsCount];
int totalOffSet = 0;
for (int iii = 0; iii < validFildsCount - totalOffSet; iii++)
{
bool combine = false;
int storedIndex = 0;
for (int iInLeft = 0; iInLeft < singleLeftquota.Count; iInLeft++)
{
if (iii + totalOffSet == singleLeftquota[iInLeft])
{
combine = true;
storedIndex = iInLeft;
break;
}
}
if (combine)
{
int offset = singleRightquota[storedIndex] - singleLeftquota[storedIndex];
for (int combineI = 0; combineI <= offset; combineI++)
{
temp[iii] += Fields[iii + totalOffSet + combineI] + ",";
}
temp[iii] = temp[iii].Remove(temp[iii].Length - 1, 1);
totalOffSet += offset;
}
else
{
temp[iii] = Fields[iii + totalOffSet];
}
}
Fields = temp;
}
}
}
Row = dt.NewRow();
for (int f = 0; f < Cols; f++)
{
Fields[f] = Fields[f].Replace("\"\"", "\""); //Two consecutive quotes indicate a user's quote
if (Fields[f].StartsWith("\""))
{
if (Fields[f].EndsWith("\""))
{
Fields[f] = Fields[f].Remove(0, 1);
if (Fields[f].Length > 0)
{
Fields[f] = Fields[f].Remove(Fields[f].Length - 1, 1);
}
}
}
Row[f] = Fields[f];
}
dt.Rows.Add(Row);
rowcount++;
}
}
}
catch (Exception ex)
{
throw new Exception( "row: " + (rowcount+2) + ", " + ex.Message);
}
//OleDbConnection connection = new OleDbConnection(string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}; Extended Properties=""text;HDR=Yes;FMT=Delimited"";", FilePath + FileName));
//OleDbCommand command = new OleDbCommand("SELECT * FROM " + FileName, connection);
//OleDbDataAdapter adapter = new OleDbDataAdapter(command);
//DataTable dt = new DataTable();
//adapter.Fill(dt);
//adapter.Dispose();
return dt;
}
else
return null;
//OleDbConnection connection = new OleDbConnection(string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}; Extended Properties=""text;HDR=Yes;FMT=Delimited"";", strFilePath));
//OleDbCommand command = new OleDbCommand("SELECT * FROM " + strFileName, connection);
//OleDbDataAdapter adapter = new OleDbDataAdapter(command);
//DataTable dt = new DataTable();
//adapter.Fill(dt);
//return dt;
}
How about writing the data to a ByteArrayOutputStream instead of a FileOutputStream?
Otherwise, you could serialize the object using XMLEncoder, persist the XML, then deserialize via XMLDecoder.
Use this StreamWriter
constructor with 2nd parameter - true
.
I think that you need to import this:
import 'rxjs/add/operator/map'
Or more generally this if you want to have more methods for observables. WARNING: This will import all 50+ operators and add them to your application, thus affecting your bundle size and load times.
import 'rxjs/Rx';
See this issue for more details.
Simple Way to change the seek bar color ...
<ProgressBar
android:id="@+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:theme="@style/Progress_color"/>
Style : Progress_color
<style name="Progress_color">
<item name="colorAccent">@color/white</item> <!-- Whatever color you want-->
</style>
java class change ProgressDrawable()
seek_bar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.MULTIPLY);
Disabled means that no data from that form element will be submitted when the form is submitted. Read-only means any data from within the element will be submitted, but it cannot be changed by the user.
For example:
<input type="text" name="yourname" value="Bob" readonly="readonly" />
This will submit the value "Bob" for the element "yourname".
<input type="text" name="yourname" value="Bob" disabled="disabled" />
This will submit nothing for the element "yourname".
return database.rawQuery("SELECT * FROM " + DbHandler.TABLE_ORDER_DETAIL +
" ORDER BY "+DbHandler.KEY_ORDER_CREATED_AT + " DESC"
, new String[] {});
Use inputstream once don't use it multiple times and Do inputstream.close()
IMO, you cannot create an empty Date(java.util)
. You can create a Date
object with null
value and can put a null check.
Date date = new Date(); // Today's date and current time
Date date2 = new Date(0); // Default date and time
Date date3 = null; //Date object with null as value.
if(null != date3) {
// do your work.
}
For Sybase the following works (with http://python-sybase.sourceforge.net)
import pandas.io.sql as psql
import Sybase
df = psql.frame_query("<Query>", con=Sybase.connect("<dsn>", "<user>", "<pwd>"))
To answer Philipp's concern ( in the comments ), slicing works ok for unicode strings too
>>> greek=u"aß?de??????µ???p??st?f???"
>>> print len(greek)
25
>>> print greek[:10]
aß?de?????
If you want to run the above code as a script, put this line at the top
# -*- coding: utf-8 -*-
If your editor doesn't save in utf-8, substitute the correct encoding
Not sure when this changed, but with the latest version of typescript, you just need to use import moment from 'moment';
and everything else should work as normal.
Looks like moment recent fixed their import. As of at least 2.24.0
you'll want to use import * as moment from 'moment';
simple do id:("12345") OR id:("7890") .... and so on
This worked for me on Ubuntu:
Stop MySQL server:
/etc/init.d/mysql stop
Start MySQL from the commandline:
/usr/sbin/mysqld
In another terminal enter mysql and issue:
grant all privileges on *.* to 'root'@'%' with grant option;
You may also want to add
grant all privileges on *.* to 'root'@'localhost' with grant option;
and optionally use a password as well.
flush privileges;
and then exit your MySQL prompt and then kill the mysqld server running in the foreground. Restart with
/etc/init.d/mysql start
{ "scripts" :
{ "build": "node build.js"}
}
npm run build
ORnpm run-script build
{
"name": "build",
"version": "1.0.0",
"scripts": {
"start": "node build.js"
}
}
npm start
NB: you were missing the
{ brackets }
and the node command
folder structure is fine:
+ build
- package.json
- build.js
The simplest general function to find the positive modulo would be this- It would work on both positive and negative values of x.
int modulo(int x,int N){
return (x % N + N) %N;
}
This means that you must declare strict mode by writing "use strict"
at the beginning of the file or the function to use block-scope declarations.
EX:
function test(){
"use strict";
let a = 1;
}
I've had this sort of problem.....
The solve: cmd
/ powershell
run as ADMINISTRATOR! I always forget.
Notice: In powershell
, you need to put .\
for example:
.\httpd -k shutdown .\httpd -k stop .\httpd -k uninstall
Result: Removing the apache2.4
service The Apache2.4
service has been removed successfully.
Try with simple c++ code in VC++.
#include <windows.h>
#include <iostream>
#pragma comment(lib, "winmm.lib")
int main(int argc, char* argv[])
{
std::cout<<"Sound playing... enjoy....!!!";
PlaySound("C:\\temp\\sound_test.wav", NULL, SND_FILENAME); //SND_FILENAME or SND_LOOP
return 0;
}
You can easily install 1.8 via PPA. Which can be done by:
$ sudo add-apt-repository ppa:webupd8team/java
$ sudo apt-get update
$ sudo apt-get install oracle-java8-installer
Then check the running version:
$ java -version
If you must do it manually there's already an answer for that on AskUbuntu here.
Using java.net.URI class:
public String getDecodedURL(String encodedUrl) {
try {
URI uri = new URI(encodedUrl);
return uri.getScheme() + ":" + uri.getSchemeSpecificPart();
} catch (Exception e) {
return "";
}
}
Please note that exception handling can be better, but it's not much relevant for this example.
the window.top
property should be able to give what you need.
E.g.
alert(top.location.href)
try this code below :
var currentLocation = document.location;
muzLoc = String(currentLocation).substring(0,45);
prodLoc = String(currentLocation).substring(0,48);
techLoc = String(currentLocation).substring(0,47);
Here's a simple solution with lambdas:
root = Tk()
root.attributes("-fullscreen", True)
root.bind("<F11>", lambda event: root.attributes("-fullscreen",
not root.attributes("-fullscreen")))
root.bind("<Escape>", lambda event: root.attributes("-fullscreen", False))
root.mainloop()
This will make the screen exit fullscreen when escape is pressed, and toggle fullscreen when F11 is pressed.
It means the CPU attempted to execute an instruction it didn't understand. This could be caused by corruption I guess, or maybe it's been compiled for the wrong architecture (in which case I would have thought the O/S would refuse to run the executable). Not entirely sure what the root issue is.
Know the master key yourself. Don't hard code it.
Use py-bcrypt
(bcrypt), powerful hashing technique to generate a password yourself.
Basically you can do this (an idea...)
import bcrypt
from getpass import getpass
master_secret_key = getpass('tell me the master secret key you are going to use')
salt = bcrypt.gensalt()
combo_password = raw_password + salt + master_secret_key
hashed_password = bcrypt.hashpw(combo_password, salt)
save salt and hashed password somewhere so whenever you need to use the password, you are reading the encrypted password, and test against the raw password you are entering again.
This is basically how login should work these days.
I have found the SMB2 protocol introduced in Vista to lock the access databases. It can be disabled by the following regedit:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\LanmanServer\Parameters] "Smb2"=dword:00000000
See this thread for an explanation: VIM for Windows - What do I type to save and exit from a file?
As I wrote there: to learn Vimming, you could use one of the quick reference cards:
Also note How can I set up an editor to work with Git on Windows? if you're not comfortable in using Vim but want to use another editor for your commit messages.
If your commit message is not too long, you could also type
git commit -a -m "your message here"
var jQueryObject = $('<div></div>').html( string ).children();
This creates a dummy jQuery object in which you can put the string as HTML. Then, you get the children only.
I know this question is very old, but I was making similar thing in my kotlin app recently. So here is an example if anyone needs it:
val dfs = DecimalFormatSymbols.getInstance(Locale.getDefault())
val bigD = BigDecimal("1e+30")
val formattedBigD = DecimalFormat("#,##0.#",dfs).format(bigD)
Result displaying $formattedBigD:
1,000,000,000,000,000,000,000,000,000,000
I tried to optimise SBF's and Michael's code a bit to make it more compact.
I am relying on PowerShell's type coercion where it automatically converts strings to enum values, so I didn't define the lookup dictionary.
I also pulled out the block that adds the new path to the list based on a condition, so that work is done once and stored in a variable for re-use.
It is then applied permanently or just to the Session depending on the $PathContainer
parameter.
We can put the block of code in a function or a ps1 file that we call directly from the command prompt. I went with DevEnvAddPath.ps1.
param(
[Parameter(Position=0,Mandatory=$true)][String]$PathChange,
[ValidateSet('Machine', 'User', 'Session')]
[Parameter(Position=1,Mandatory=$false)][String]$PathContainer='Session',
[Parameter(Position=2,Mandatory=$false)][Boolean]$PathPrepend=$false
)
[String]$ConstructedEnvPath = switch ($PathContainer) { "Session"{${env:Path};} default{[Environment]::GetEnvironmentVariable('Path', $containerType);} };
$PathPersisted = $ConstructedEnvPath -split ';';
if ($PathPersisted -notcontains $PathChange) {
$PathPersisted = $(switch ($PathPrepend) { $true{,$PathChange + $PathPersisted;} default{$PathPersisted + $PathChange;} }) | Where-Object { $_ };
$ConstructedEnvPath = $PathPersisted -join ";";
}
if ($PathContainer -ne 'Session')
{
# Save permanently to Machine, User
[Environment]::SetEnvironmentVariable("Path", $ConstructedEnvPath, $PathContainer);
}
# Update the current session
${env:Path} = $ConstructedEnvPath;
I do something similar for a DevEnvRemovePath.ps1.
param(
[Parameter(Position=0,Mandatory=$true)][String]$PathChange,
[ValidateSet('Machine', 'User', 'Session')]
[Parameter(Position=1,Mandatory=$false)][String]$PathContainer='Session'
)
[String]$ConstructedEnvPath = switch ($PathContainer) { "Session"{${env:Path};} default{[Environment]::GetEnvironmentVariable('Path', $containerType);} };
$PathPersisted = $ConstructedEnvPath -split ';';
if ($PathPersisted -contains $PathChange) {
$PathPersisted = $PathPersisted | Where-Object { $_ -ne $PathChange };
$ConstructedEnvPath = $PathPersisted -join ";";
}
if ($PathContainer -ne 'Session')
{
# Save permanently to Machine, User
[Environment]::SetEnvironmentVariable("Path", $ConstructedEnvPath, $PathContainer);
}
# Update the current session
${env:Path} = $ConstructedEnvPath;
So far, they seem to work.
The system doesn't record queries in that way. If you know you want to do that ahead of time though, you can use SQL Profiler to record what is coming in and track queries during the time Profiler is running.
Most answers are duplicates, it might be useful to group them. Basically two simple options have been proposed.
The first option has 4 different aliases, some of which are quite short :
EXPLAIN db_name.table_name;
DESCRIBE db_name.table_name;
SHOW FIELDS FROM db_name.table_name;
SHOW COLUMNS FROM db_name.table_name;
(NB : as an alternative to db_name.table_name
, one can use a second FROM
: db_name FROM table_name
).
This gives something like :
+------------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------------+--------------+------+-----+---------+-------+
| product_id | int(11) | NO | PRI | NULL | |
| name | varchar(255) | NO | MUL | NULL | |
| description | text | NO | | NULL | |
| meta_title | varchar(255) | NO | | NULL | |
+------------------+--------------+------+-----+---------+-------+
The second option is a bit longer :
SELECT
COLUMN_NAME, DATA_TYPE
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_SCHEMA = 'db_name'
AND
TABLE_NAME = 'table_name';
It is also less talkative :
+------------------+-----------+
| column_name | DATA_TYPE |
+------------------+-----------+
| product_id | int |
| name | varchar |
| description | text |
| meta_title | varchar |
+------------------+-----------+
It has the advantage of allowing selection per column, though, using AND COLUMN_NAME = 'column_name'
(or like
).
Without the need of a method:
// html element, will display'active' class if showMobile is true
//clicking on the elment will toggle showMobileMenu to true and false alternatively
<div id="mobile-toggle"
:class="{ active: showMobileMenu }"
@click="showMobileMenu = !showMobileMenu">
</div>
//in your vue.js app
data: {
showMobileMenu: false
}
From a sqlite prompt:
sqlite> .read db.sql
Or:
cat db.sql | sqlite3 database.db
Also, your SQL is invalid - you need ;
on the end of your statements:
create table server(name varchar(50),ipaddress varchar(15),id init);
create table client(name varchar(50),ipaddress varchar(15),id init);
The first <img />
is invalid - src
is a required attribute. data-src
is an attribute than can be leveraged by, say, JavaScript, but has no presentational meaning.
At least in PostgreSQL you can use the column number in the resultset in your GROUP BY clause:
SELECT
itemName as ItemName,
substring(itemName, 1,1) as FirstLetter,
Count(itemName)
FROM table1
GROUP BY 1, 2
Of course this starts to be a pain if you are doing this interactively and you edit the query to change the number or order of columns in the result. But still.
//Just use a List
//create the list
public final List<Object> myObjects;
//instantiate the list
myObjects = new ArrayList<Object>();
//add objects to the list
Object object = myObject;
myObjects.add(object);
//remove the object calling this method if you have more than 1 objects still works with 1
//object too.
private void removeObject(){
int len = myObjects.size();
for(int i = 0;i<len; i++){
Objects object = myObjects.get(i);
myObjects.remove(object);
}
}
var string = 'hello world';
var arr = string.split(''); // converted the string to an array and then checked:
if(arr[i] === ' '){
console.log(i);
}
I know regex can do the trick too!
Generating random integers between 0 and 9.
import numpy
X = numpy.random.randint(0, 10, size=10)
print(X)
Output:
[4 8 0 4 9 6 9 9 0 7]
For WampServer 2.5 (Apache 2.4.9 and PHP 5.5.12):
In default I've had php_intl
enabled (you can enable it when you left click on the wamp icon in the system tray > PHP > PHP extensions
and check if is it marked)
To have it properly working, I've had to copy:
C:\wamp\bin\php\php5.5.12\icu**51.dll
(total 8 files)
to
C:\wamp\bin\apache\apache2.4.9\bin
Then just restart the wamp and everything was just fine.
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
Source: W3Schools
Edit: as @zcrar70 noted, the above code is incorrect, please see the following answer Javascript getCookie functions
I have the same issue width php storm version 2017.3. This fix it for me: intellij support forum
It was an error width @angular language service: https://www.npmjs.com/package/@angular/language-service
PHPUnit's current "best practices" for exception testing seem.. lackluster (docs).
Since I wanted more than the current expectException
implementation, I made a trait to use on my test cases. It's only ~50 lines of code.
assert
syntaxassertNotThrows
Throwable
errorsI published the AssertThrows
trait to Github and packagist so it can be installed with composer.
Just to illustrate the spirit behind the syntax:
<?php
// Using simple callback
$this->assertThrows(MyException::class, [$obj, 'doSomethingBad']);
// Using anonymous function
$this->assertThrows(MyException::class, function() use ($obj) {
$obj->doSomethingBad();
});
Pretty neat?
Please see below for a more comprehensive usage example:
<?php
declare(strict_types=1);
use Jchook\AssertThrows\AssertThrows;
use PHPUnit\Framework\TestCase;
// These are just for illustration
use MyNamespace\MyException;
use MyNamespace\MyObject;
final class MyTest extends TestCase
{
use AssertThrows; // <--- adds the assertThrows method
public function testMyObject()
{
$obj = new MyObject();
// Test a basic exception is thrown
$this->assertThrows(MyException::class, function() use ($obj) {
$obj->doSomethingBad();
});
// Test custom aspects of a custom extension class
$this->assertThrows(MyException::class,
function() use ($obj) {
$obj->doSomethingBad();
},
function($exception) {
$this->assertEquals('Expected value', $exception->getCustomThing());
$this->assertEquals(123, $exception->getCode());
}
);
// Test that a specific exception is NOT thrown
$this->assertNotThrows(MyException::class, function() use ($obj) {
$obj->doSomethingGood();
});
}
}
?>
I would just change the webpage to whatever you are using for error handling:
getWindow().requestFeature(Window.FEATURE_PROGRESS);
webview.getSettings().setJavaScriptEnabled(true);
final Activity activity = this;
webview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
// Activities and WebViews measure progress with different scales.
// The progress meter will automatically disappear when we reach 100%
activity.setProgress(progress * 1000);
}
});
webview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String
failingUrl) {
Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
webview.loadUrl("http://slashdot.org/");
this can all be found on http://developer.android.com/reference/android/webkit/WebView.html
_MSC_VER
and possibly _MSC_FULL_VER
is what you need. You can also examine visualc.hpp in any recent boost install for some usage examples.
Some values for the more recent versions of the compiler are:
MSVC++ 14.24 _MSC_VER == 1924 (Visual Studio 2019 version 16.4)
MSVC++ 14.23 _MSC_VER == 1923 (Visual Studio 2019 version 16.3)
MSVC++ 14.22 _MSC_VER == 1922 (Visual Studio 2019 version 16.2)
MSVC++ 14.21 _MSC_VER == 1921 (Visual Studio 2019 version 16.1)
MSVC++ 14.2 _MSC_VER == 1920 (Visual Studio 2019 version 16.0)
MSVC++ 14.16 _MSC_VER == 1916 (Visual Studio 2017 version 15.9)
MSVC++ 14.15 _MSC_VER == 1915 (Visual Studio 2017 version 15.8)
MSVC++ 14.14 _MSC_VER == 1914 (Visual Studio 2017 version 15.7)
MSVC++ 14.13 _MSC_VER == 1913 (Visual Studio 2017 version 15.6)
MSVC++ 14.12 _MSC_VER == 1912 (Visual Studio 2017 version 15.5)
MSVC++ 14.11 _MSC_VER == 1911 (Visual Studio 2017 version 15.3)
MSVC++ 14.1 _MSC_VER == 1910 (Visual Studio 2017 version 15.0)
MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015 version 14.0)
MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013 version 12.0)
MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012 version 11.0)
MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010 version 10.0)
MSVC++ 9.0 _MSC_FULL_VER == 150030729 (Visual Studio 2008, SP1)
MSVC++ 9.0 _MSC_VER == 1500 (Visual Studio 2008 version 9.0)
MSVC++ 8.0 _MSC_VER == 1400 (Visual Studio 2005 version 8.0)
MSVC++ 7.1 _MSC_VER == 1310 (Visual Studio .NET 2003 version 7.1)
MSVC++ 7.0 _MSC_VER == 1300 (Visual Studio .NET 2002 version 7.0)
MSVC++ 6.0 _MSC_VER == 1200 (Visual Studio 6.0 version 6.0)
MSVC++ 5.0 _MSC_VER == 1100 (Visual Studio 97 version 5.0)
The version number above of course refers to the major version of your Visual studio you see in the about box, not to the year in the name. A thorough list can be found here. Starting recently, Visual Studio will start updating its ranges monotonically, meaning you should check ranges, rather than exact compiler values.
cl.exe /?
will give a hint of the used version, e.g.:
c:\program files (x86)\microsoft visual studio 11.0\vc\bin>cl /?
Microsoft (R) C/C++ Optimizing Compiler Version 17.00.50727.1 for x86
.....
It does 5 things:
this
variable point to the newly created object.this
is mentioned.null
object reference. In this case, that object reference is returned instead.Note: constructor function refers to the function after the new
keyword, as in
new ConstructorFunction(arg1, arg2)
Once this is done, if an undefined property of the new object is requested, the script will check the object's [[prototype]] object for the property instead. This is how you can get something similar to traditional class inheritance in JavaScript.
The most difficult part about this is point number 2. Every object (including functions) has this internal property called [[prototype]]. It can only be set at object creation time, either with new, with Object.create, or based on the literal (functions default to Function.prototype, numbers to Number.prototype, etc.). It can only be read with Object.getPrototypeOf(someObject). There is no other way to set or read this value.
Functions, in addition to the hidden [[prototype]] property, also have a property called prototype, and it is this that you can access, and modify, to provide inherited properties and methods for the objects you make.
Here is an example:
ObjMaker = function() {this.a = 'first';};
// ObjMaker is just a function, there's nothing special about it that makes
// it a constructor.
ObjMaker.prototype.b = 'second';
// like all functions, ObjMaker has an accessible prototype property that
// we can alter. I just added a property called 'b' to it. Like
// all objects, ObjMaker also has an inaccessible [[prototype]] property
// that we can't do anything with
obj1 = new ObjMaker();
// 3 things just happened.
// A new, empty object was created called obj1. At first obj1 was the same
// as {}. The [[prototype]] property of obj1 was then set to the current
// object value of the ObjMaker.prototype (if ObjMaker.prototype is later
// assigned a new object value, obj1's [[prototype]] will not change, but you
// can alter the properties of ObjMaker.prototype to add to both the
// prototype and [[prototype]]). The ObjMaker function was executed, with
// obj1 in place of this... so obj1.a was set to 'first'.
obj1.a;
// returns 'first'
obj1.b;
// obj1 doesn't have a property called 'b', so JavaScript checks
// its [[prototype]]. Its [[prototype]] is the same as ObjMaker.prototype
// ObjMaker.prototype has a property called 'b' with value 'second'
// returns 'second'
It's like class inheritance because now, any objects you make using new ObjMaker()
will also appear to have inherited the 'b' property.
If you want something like a subclass, then you do this:
SubObjMaker = function () {};
SubObjMaker.prototype = new ObjMaker(); // note: this pattern is deprecated!
// Because we used 'new', the [[prototype]] property of SubObjMaker.prototype
// is now set to the object value of ObjMaker.prototype.
// The modern way to do this is with Object.create(), which was added in ECMAScript 5:
// SubObjMaker.prototype = Object.create(ObjMaker.prototype);
SubObjMaker.prototype.c = 'third';
obj2 = new SubObjMaker();
// [[prototype]] property of obj2 is now set to SubObjMaker.prototype
// Remember that the [[prototype]] property of SubObjMaker.prototype
// is ObjMaker.prototype. So now obj2 has a prototype chain!
// obj2 ---> SubObjMaker.prototype ---> ObjMaker.prototype
obj2.c;
// returns 'third', from SubObjMaker.prototype
obj2.b;
// returns 'second', from ObjMaker.prototype
obj2.a;
// returns 'first', from SubObjMaker.prototype, because SubObjMaker.prototype
// was created with the ObjMaker function, which assigned a for us
I read a ton of rubbish on this subject before finally finding this page, where this is explained very well with nice diagrams.
Here is a hint Hint for gradle users without admin rights: add this line to your jaxb-task:
System.setProperty('javax.xml.accessExternalSchema', 'all')
it will look like this:
jaxb {
System.setProperty('javax.xml.accessExternalSchema', 'all')
xsdDir = "${project.name}/xsd"
xjc {
taskClassname = "com.sun.tools.xjc.XJCTask"
args = ["-npa", "-no-header"]
}
}
This should work (which you have tried)
$this->db->where_not_in('emailsToCampaigns.campaignId', $campaignId);
The top answer worked fine but I suggest saving your JSON data into a variable before posting it is a little bit cleaner when sending a long form or dealing with large data in general.
var Data = {_x000D_
"name":"jonsa",_x000D_
"e-mail":"[email protected]",_x000D_
"phone":1223456789_x000D_
};_x000D_
_x000D_
_x000D_
$.ajax({_x000D_
type: 'POST',_x000D_
url: '/form/',_x000D_
data: Data,_x000D_
success: function(data) { alert('data: ' + data); },_x000D_
contentType: "application/json",_x000D_
dataType: 'json'_x000D_
});
_x000D_
To delete rows empty in table
syntax:
DELETE FROM table_name
WHERE column_name IS NULL;
example:
Table name: data ---> column name: pkdno
DELETE FROM data
WHERE pkdno IS NULL;
Answer: 5 rows deleted. (sayso)
set /a number=%random% %% [maximum]-[minimum]
example "
set /a number=%random% %% 100-50
will give a random number between 100 and 50. Be sure to only use one percentage sign as the operand if you are not using the line in a batch script!
You have a class on your CSS that is overwriting your width and height, the class reads as such:
.postItem img {
height: auto;
width: 450px;
}
Remove that and your width/height properties on the img
tag should work.
This is an old question, but I think will worth it to share how to create an arrow using this triangle technique.
Lets create 2 triangles, for the second one we will use the :after
pseudo class and position it just below the other:
.arrow{
width: 0;
height: 0;
border-radius: 50px;
display: inline-block;
position: relative;
}
.arrow:after{
content: "";
width: 0;
height: 0;
position: absolute;
}
.arrow-up{
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 50px solid #333;
}
.arrow-up:after{
top: 5px;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 50px solid #ccc;
right: -50px;
}
_x000D_
<div class="arrow arrow-up"> </div>
_x000D_
Now we just have to set the predominant border color of the second triangle to the same color of the background:
.arrow{
width: 0;
height: 0;
border-radius: 50px;
display: inline-block;
position: relative;
}
.arrow:after{
content: "";
width: 0;
height: 0;
position: absolute;
}
.arrow-up{
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 50px solid #333;
}
.arrow-up:after{
top: 5px;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 50px solid #fff;
right: -50px;
}
_x000D_
<div class="arrow arrow-up"> </div>
_x000D_
Fiddle with all the arrows:
http://jsfiddle.net/tomsarduy/r0zksgeu/
/^.*?\bcat\b.*?\bmat\b.*?$/m
Using the m
modifier (which ensures the beginning/end metacharacters match on line breaks rather than at the very beginning and end of the string):
^
matches the line beginning.*?
matches anything on the line before...\b
matches a word boundary the first occurrence of a word boundary (as @codaddict discussed)cat
and another word boundary; note that underscores are treated as "word" characters, so _cat_
would not match*;.*?
: any characters before...mat
, boundary.*?
: any remaining characters before...$
: the end of the line.It's important to use \b
to ensure the specified words aren't part of longer words, and it's important to use non-greedy wildcards (.*?
) versus greedy (.*
) because the latter would fail on strings like "There is a cat on top of the mat which is under the cat." (It would match the last occurrence of "cat" rather than the first.)
* If you want to be able to match _cat_
, you can use:
/^.*?(?:\b|_)cat(?:\b|_).*?(?:\b|_)mat(?:\b|_).*?$/m
which matches either underscores or word boundaries around the specified words. (?:)
indicates a non-capturing group, which can help with performance or avoid conflicted captures.
Edit: A question was raised in the comments about whether the solution would work for phrases rather than just words. The answer is, absolutely yes. The following would match "A line which includes both the first phrase and the second phrase":
/^.*?(?:\b|_)first phrase here(?:\b|_).*?(?:\b|_)second phrase here(?:\b|_).*?$/m
Edit 2: If order doesn't matter you can use:
/^.*?(?:\b|_)(first(?:\b|_).*?(?:\b|_)second|second(?:\b|_).*?(?:\b|_)first)(?:\b|_).*?$/m
And if performance is really an issue here, it's possible lookaround (if your regex engine supports it) might (but probably won't) perform better than the above, but I'll leave both the arguably more complex lookaround version and performance testing as an exercise to the questioner/reader.
Edited per @Alan Moore's comment. I didn't have a chance to test it, but I'll take your word for it.
You should be using indexes to help SQL server performance. Usually that implies that columns that are used to find rows in a table are indexed.
Clustered indexes makes SQL server order the rows on disk according to the index order. This implies that if you access data in the order of a clustered index, then the data will be present on disk in the correct order. However if the column(s) that have a clustered index is frequently changed, then the row(s) will move around on disk, causing overhead - which generally is not a good idea.
Having many indexes is not good either. They cost to maintain. So start out with the obvious ones, and then profile to see which ones you miss and would benefit from. You do not need them from start, they can be added later on.
Most column datatypes can be used when indexing, but it is better to have small columns indexed than large. Also it is common to create indexes on groups of columns (e.g. country + city + street).
Also you will not notice performance issues until you have quite a bit of data in your tables. And another thing to think about is that SQL server needs statistics to do its query optimizations the right way, so make sure that you do generate that.
If anyone is looking for the Android Studio (2.3.1) on Mac OSX (10.12.1) answer then here are the steps for it.
Tools Menu > Android > Android Device Monitor
Choose Your Device (at Left) > Click on File Explorer Tab (at Right)
Hope this helps.
Since you have a FULL backup, you can restore the backup to a different server as a database of the same name or to the same server with a different name.
Then you can just review the contents pre-update and write a SQL script to do the update.
This should do the trick:
#include <stdio.h>
NSString *readLineAsNSString(FILE *file)
{
char buffer[4096];
// tune this capacity to your liking -- larger buffer sizes will be faster, but
// use more memory
NSMutableString *result = [NSMutableString stringWithCapacity:256];
// Read up to 4095 non-newline characters, then read and discard the newline
int charsRead;
do
{
if(fscanf(file, "%4095[^\n]%n%*c", buffer, &charsRead) == 1)
[result appendFormat:@"%s", buffer];
else
break;
} while(charsRead == 4095);
return result;
}
Use as follows:
FILE *file = fopen("myfile", "r");
// check for NULL
while(!feof(file))
{
NSString *line = readLineAsNSString(file);
// do stuff with line; line is autoreleased, so you should NOT release it (unless you also retain it beforehand)
}
fclose(file);
This code reads non-newline characters from the file, up to 4095 at a time. If you have a line that is longer than 4095 characters, it keeps reading until it hits a newline or end-of-file.
Note: I have not tested this code. Please test it before using it.
This code will work on all android versions:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Automatic popping up keyboard on start Activity
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
or
//avoid automatically appear android keyboard when activity start
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
wget -O yourfilename.zip remote-storage.url/theirfilename.zip
will do the trick for you.
Note:
a) its a capital O.
b) wget -O filename url
will only work. Putting -O
last will not.
Actually, I cannot get selected date in aspx. Here is the way to set selected date in codes:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DateTime dt = DateTime.Now.AddDays(-1);
Calendar1.VisibleDate = dt;
Calendar1.SelectedDate = dt;
Calendar1.TodaysDate = dt;
...
}
}
In above example, I need to set the default selected date to yesterday. The key point is to set TodayDate. Otherwise, the selected calendar date is always today.
Parsing date and time
To create a LocalDateTime
object from a string you can use the static LocalDateTime.parse()
method. It takes a string and a DateTimeFormatter
as parameter. The DateTimeFormatter
is used to specify the date/time pattern.
String str = "1986-04-08 12:30";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
Formatting date and time
To create a formatted string out a LocalDateTime
object you can use the format()
method.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime dateTime = LocalDateTime.of(1986, Month.APRIL, 8, 12, 30);
String formattedDateTime = dateTime.format(formatter); // "1986-04-08 12:30"
Note that there are some commonly used date/time formats predefined as constants in DateTimeFormatter
. For example: Using DateTimeFormatter.ISO_DATE_TIME
to format the LocalDateTime
instance from above would result in the string "1986-04-08T12:30:00"
.
The parse()
and format()
methods are available for all date/time related objects (e.g. LocalDate
or ZonedDateTime
)
Use:
AND oh.tran_date BETWEEN TRUNC(SYSDATE - 1) AND TRUNC(SYSDATE) - 1/86400
Reference: TRUNC
Calling a function on the tran_date
means the optimizer won't be able to use an index (assuming one exists) associated with it. Some databases, such as Oracle, support function based indexes which allow for performing functions on the data to minimize impact in such situations, but IME DBAs won't allow these. And I agree - they aren't really necessary in this instance.
Try realpath
.
~ $ sudo apt-get install realpath # may already be installed
~ $ realpath .bashrc
/home/username/.bashrc
To avoid expanding symlinks, use realpath -s
.
The answer comes from "bash/fish command to print absolute path to a file".
You can use filter_var
filter_var(
$yourInteger,
FILTER_VALIDATE_INT,
array(
'options' => array(
'min_range' => $min,
'max_range' => $max
)
)
);
This will also allow you to specify whether you want to allow octal and hex notation of integers. Note that the function is type-safe. 5.5
is not an integer but a float and will not validate.
Detailed tutorial about filtering data with PHP:
int[] scores = { 100, 90, 90, 80, 75, 60 };
int[] alice = { 50, 65, 77, 90, 102 };
int[] scoreBoard = new int[scores.Length + alice.Length];
int j = 0;
for (int i=0;i<(scores.Length+alice.Length);i++) // to combine two arrays
{
if(i<scores.Length)
{
scoreBoard[i] = scores[i];
}
else
{
scoreBoard[i] = alice[j];
j = j + 1;
}
}
for (int l = 0; l < (scores.Length + alice.Length); l++)
{
Console.WriteLine(scoreBoard[l]);
}
Here is another fix:
My build system (Gradle) added a required native library (dll) to the Eclipse build path (Right Click on Project -> Properties -> Java Build Path -> Libraries). Telling the build system not to add the native dll library to the Eclipse classpath solved the problem.
For passing in command line parameters. For example args[0]
will give you the first command line parameter, if there is one.
I wrote this algorithm for similar kind of problem with DP, may it help
public class MinimumCoinProblem {
private static void calculateMinumCoins(int[] array_Coins, int sum) {
int[] array_best = new int[sum];
for (int i = 0; i < sum; i++) {
for (int j = 0; j < array_Coins.length; j++) {
if (array_Coins[j] <= i && (array_best[i] == 0 || (array_best[i - array_Coins[j]] + 1) <= array_best[i])) {
array_best[i] = array_best[i - array_Coins[j]] + 1;
}
}
}
System.err.println("The Value is" + array_best[14]);
}
public static void main(String[] args) {
int[] sequence1 = {11, 9,1, 3, 5,2 ,20};
int sum = 30;
calculateMinumCoins(sequence1, sum);
}
}
It's usually \t
in command-line interfaces, which will convert the char \t
into the whitespace tab character.
For example, hello\talex
-> hello--->alex
.
try
pip3 install --user --upgrade pandas
I ran into the same problem, and I'm not sure why, but it turned out to be that the script link generated by Scripts.Render did not have a .js extension. Because it also does not have a Type attribute the browser was just unable to use it (chrome and firefox).
To resolve this, I changed my bundle configuration to generate compiled files with a js extension, e.g.
var coreScripts = new ScriptBundle("~/bundles/coreAssets.js")
.Include("~/scripts/jquery.js");
var coreStyles = new StyleBundle("~/bundles/coreStyles.css")
.Include("~/css/bootstrap.css");
Notice in new StyleBundle(...
instead of saying ~/bundles/someBundle
, I am saying ~/bundlers/someBundle.js
or ~/bundles/someStyles.css
..
This causes the link generated in the src attribute to have .js or .css on it when optimizations are enabled, as such the browsers know based on the file extension what mime/type to use on the get request and everything works.
If I take off the extension, everything breaks. That's because @Scripts and @Styles doesn't render all the necessary attributes to understand a src to a file with no extension.
Following solution worked for me. When connecting to the db, specify that data should be truncated if they are too long (jdbcCompliantTruncation). My link looks like this:
jdbc:mysql://SERVER:PORT_NO/SCHEMA?sessionVariables=sql_mode='NO_ENGINE_SUBSTITUTION'&jdbcCompliantTruncation=false
If you increase the size of the strings, you may face the same problem in future if the string you are attempting to store into the DB is longer than the new size.
EDIT: STRICT_TRANS_TABLES has to be removed from sql_mode as well.
Here is an example that should give you some idea..
=IIF(First(Fields!Gender.Value,"vw_BrgyClearanceNew")="Female" and
(First(Fields!CivilStatus.Value,"vw_BrgyClearanceNew")="Married"),false,true)
I think you have to identify the datasource name or the table name where your data is coming from.
Use like this,
HTML:
<input type="text" disabled="disabled" class="inputDisabled" value="">
<div id="edit">edit</div>
JS:
$('#edit').click(function(){ // click to
$('.inputDisabled').attr('disabled',false); // removing disabled in this class
});
I'd do it like this jsFiddle example.
JavaScript:
function check(elem) {
document.getElementById('mySelect1').disabled = !elem.selectedIndex;
}
HTML:
<form>
<select id="mySelect" onChange="check(this);">
<option>No</option>
<option>Yes</option>
</select>
<select id="mySelect1" disabled="disabled" >
<option>Dep1</option>
<option>Dep2</option>
<option>Dep3</option>
<option>Dep4</option>
</select>
</form>
You can use .toString()
to join an array with a comma.
var array = ['a', 'b', 'c'];
array.toString(); // result: a,b,c
Or, set the separator with array.join('; '); // result: a; b; c
.
Add this to your <head>
:
<style type="text/css">
textarea { border: none; }
</style>
Or do it directly on the textarea:
<textarea style="border: none"></textarea>
imo there's a better answer for this using Snippets
Create a snippet with a definition like this:
"name_of_your_snippet": {
"scope": "javascript,html",
"prefix": "name_of_your_snippet",
"body": "<${0:b}>$TM_SELECTED_TEXT</${0:b}>"
}
Then bind it to a key in keybindings.json E.g. like this:
{
"key": "alt+w",
"command": "editor.action.insertSnippet",
"args": { "name": "name_of_your_snippet" }
}
I think this should give you exactly the same result as htmltagwrap but without having to install an extension.
It will insert tags around selected text, defaults to <b>
tag & selects the tag so typing lets you change it.
If you want to use a different default tag just change the b
in the body
property of the snippet.
None of these answers worked for me. I had to use the command line:
mysql -u root db_name < db_dump.sql
SET NAMES 'utf8';
SOURCE db_dump.sql;
Done!
If you use XHTML, for some reason, note that XHTML 1.0 C 4 says: “Use external scripts if your script uses < or & or ]]> or --.” That is, don’t embed script code inside a script
element but put it into a separate JavaScript file and refer to it with <script src="foo.js"></script>
.
Yes the culprit is definitely word-wrapping. When I tested your two programs, NetBeans IDE 8.2 gave me the following result.
Looking at your code closely you have used a line break at the end of first loop. But you didn't use any line break in second loop. So you are going to print a word with 1000 characters in the second loop. That causes a word-wrapping problem. If we use a non-word character " " after B, it takes only 5.35 seconds to compile the program. And If we use a line break in the second loop after passing 100 values or 50 values, it takes only 8.56 seconds and 7.05 seconds respectively.
Random r = new Random();
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
if(r.nextInt(4) == 0) {
System.out.print("O");
} else {
System.out.print("B");
}
if(j%100==0){ //Adding a line break in second loop
System.out.println();
}
}
System.out.println("");
}
Another advice is that to change settings of NetBeans IDE. First of all, go to NetBeans Tools and click Options. After that click Editor and go to Formatting tab. Then select Anywhere in Line Wrap Option. It will take almost 6.24% less time to compile the program.
Please try this simple function
var NanValue = function (entry) {
if(entry=="NaN") {
return 0.00;
} else {
return entry;
}
}
What I normally do, similar to answer one:
var response = await httpClient.GetAsync(completeURL); // http://192.168.0.1:915/api/Controller/Object
if (response.IsSuccessStatusCode == true)
{
string res = await response.Content.ReadAsStringAsync();
var content = Json.Deserialize<Model>(res);
// do whatever you need with the JSON which is in 'content'
// ex: int id = content.Id;
Navigate();
return true;
}
else
{
await JSRuntime.Current.InvokeAsync<string>("alert", "Warning, the credentials you have entered are incorrect.");
return false;
}
Where 'model' is your C# model class.
Here's the example from my code. So I will read a text from 1st line to 3rd line using readLine() and then store to array variable and print into textfield using for-loop :
QFile file("file.txt");
if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QTextStream in(&file);
QString line[3] = in.readLine();
for(int i=0; i<3; i++)
{
ui->textEdit->append(line[i]);
}
Set the list style and left padding to nothing.
ul {
list-style: none;
padding-left: 0;
}?
ul {_x000D_
list-style: none;_x000D_
padding-left: 0;_x000D_
}
_x000D_
<ul>_x000D_
<li>a</li>_x000D_
<li>b</li>_x000D_
<li>c</li>_x000D_
</ul>
_x000D_
To maintain the bullets you can replace the list-style: none
with list-style-position: inside
or the shorthand list-style: inside
:
ul {
list-style-position: inside;
padding-left: 0;
}
ul {_x000D_
list-style-position: inside;_x000D_
padding-left: 0;_x000D_
}
_x000D_
<ul>_x000D_
<li>a</li>_x000D_
<li>b</li>_x000D_
<li>c</li>_x000D_
</ul>
_x000D_
You may be able to do this with CSS3 using calculations, however it would most likely be safer to use JavaScript.
Here is an example: http://jsfiddle.net/8TrTU/
Using JS you can change the height of the text, then simply bind this same calculation to a resize event, during resize so it scales while the user is making adjustments, or however you are allowing resizing of your elements.
Out of curiosity, I found a box with a GNU version of sed
(v4.1.5) and tested the (uncached) performance of two approaches suggested so far, using an 11M line text file:
$ wc -l input
11771722 input
$ time head -1000 input > output; time tail -n +1000 input > input.tmp; time cp input.tmp input; time rm input.tmp
real 0m1.165s
user 0m0.030s
sys 0m1.130s
real 0m1.256s
user 0m0.062s
sys 0m1.162s
real 0m4.433s
user 0m0.033s
sys 0m1.282s
real 0m6.897s
user 0m0.000s
sys 0m0.159s
$ time head -1000 input > output && time sed -i '1,+999d' input
real 0m0.121s
user 0m0.000s
sys 0m0.121s
real 0m26.944s
user 0m0.227s
sys 0m26.624s
This is the Linux I was working with:
$ uname -a
Linux hostname 2.6.18-128.1.1.el5 #1 SMP Mon Jan 26 13:58:24 EST 2009 x86_64 x86_64 x86_64 GNU/Linux
For this test, at least, it looks like sed
is slower than the tail
approach (27 sec vs ~14 sec).
Use the Python list insert() method. Usage:
#Syntax
The syntax for the insert() method -
list.insert(index, obj)
#Parameters
#Return Value This method does not return any value, but it inserts the given element at the given index.
Example:
a = [1,2,4,5]
a.insert(2,3)
print(a)
Returns [1, 2, 3, 4, 5]
.hide{
visibility: hidden
}
<td class="hide"/>
Edit- Just for you
The difference between display and visibility is this.
"display": has many properties or values, but the ones you're focused on are "none" and "block". "none" is like a hide value, and "block" is like show. If you use the "none" value you will totally hide what ever html tag you have applied this css style. If you use "block" you will see the html tag and it's content. very simple.
"visibility": has many values, but we want to know more about the "hidden" and "visible" values. "hidden" will work in the same way as the "block" value for display, but this will hide tag and it's content, but it will not hide the phisical space of that tag. For example, if you have a couple of text lines, then and image (picture) and then a table with three columns and two rows with icons and text. Now if you apply the visibility css with the hidden value to the image, the image will disappear but the space the image was using will remaing in it's place, in other words, you will end with a big space (hole) between the text and the table. Now if you use the "visible" value your target tag and it's elements will be visible again.
This worked for me
.form-control {
box-shadow: none!important;}
To get the all related companies name, not based on particular Id.
SELECT
(SELECT GROUP_CONCAT(cmp.cmpny_name)
FROM company cmp
WHERE FIND_IN_SET(cmp.CompanyID, odr.attachedCompanyIDs)
) AS COMPANIES
FROM orders odr
It is a simple 3 Step Process :
1) Go to your private repo and click on settings
2) To the left of the screen click on Manage access
3) Then Click on Invite Collaborator
Use $n
(where n is a digit) to refer to captured subsequences in replaceFirst(...)
. I'm assuming you wanted to replace the first group with the literal string "number" and the second group with the value of the first group.
Pattern p = Pattern.compile("(\\d)(.*)(\\d)");
String input = "6 example input 4";
Matcher m = p.matcher(input);
if (m.find()) {
// replace first number with "number" and second number with the first
String output = m.replaceFirst("number $3$1"); // number 46
}
Consider (\D+)
for the second group instead of (.*)
. *
is a greedy matcher, and will at first consume the last digit. The matcher will then have to backtrack when it realizes the final (\d)
has nothing to match, before it can match to the final digit.
System.exit(0)
terminates the JVM. In simple examples like this it is difficult to percieve the difference. The parameter is passed back to the OS and is normally used to indicate abnormal termination (eg some kind of fatal error), so if you called java from a batch file or shell script you'd be able to get this value and get an idea if the application was successful.
It would make a quite an impact if you called System.exit(0)
on an application deployed to an application server (think about it before you try it).
Look at this example for clear understanding of how dynamic import works.
Dynamic Module Imports Example
To have Basic Understanding of importing and exporting Modules.
You say you have an index, the explain says otherwise. However, if you really do, this is how to continue:
If you have an index on the column, and MySQL decides not to use it, it may by because:
ANALYZE TABLE
helps.In the case of (2) or (3), you could coax MySQL into using the index by index hint sytax, but if you do, be sure run some tests to determine whether it actually improves performance to use the index as you hint it.
You can follow below steps to uninstall the app from the device via command prompt.
if it shows sucess your app is uninstalled successfully'
from rest_framework import status
from rest_framework.response import Response
class FileUpload(APIView):
def put(request):
try:
file = request.FILES['filename']
#now upload to s3 bucket or your media file
except Exception as e:
print e
return Response(status,
status.HTTP_500_INTERNAL_SERVER_ERROR)
return Response(status, status.HTTP_200_OK)
Make sure you use the root folder of the JDK. Don't add "\lib" to the end of the path, where tools.jar is physically located. It took me an hour to figure that one out. Also, this post will help show you where Ant is looking for tools.jar:
Why does ANT tell me that JAVA_HOME is wrong when it is not?
Sure, find where -Werror
is set and remove that flag. Then warnings will be only warnings.
do this
WHERE something + '%' in ('bla', 'foo', 'batz')
OR '%' + something + '%' in ('tra', 'la', 'la')
or
WHERE something + '%' in (select col from table where ....)
to get this working for a date error I had to delete the error first before calling $setValidity for the form to be marked valid.
delete currentmodal.form.$error.date;
currentmodal.form.$setValidity('myDate', true);
If you like the idea of Views, but are worried about performance you can get Oracle to create a cached table representing the view which oracle keeps up to date.
See materialized views
When you compare those two arrays, you're comparing the objects that represent the arrays, not the contents.
You'll have to use a function to compare the two. You could write your own that simply loops though one and compares it to the other after you check that the lengths are the same.
Ohk.. I got it running by typing /usr/bin/phpize
instead of only phpize
.
Just for the sake of it. People often do only need a 'view' on an array or list in reversed order instead of a completely do not need a reversed array when working with streams and collections but a 'reversed' view on the original array/collection. , it is best to create a toolkit that has a reverse view on a list / array.
So create your Iterator implementation that takes an array or list and provide the input.
/// Reverse Iterator
public class ReverseIterator<T> implements Iterator<T> {
private int index;
private final List<T> list;
public ReverseIterator(List<T> list) {
this.list = list;
this.index = list.size() - 1;
}
public boolean hasNext() {
return index >= 0 ? true : false;
}
public T next() {
if(index >= 0)
return list.get(index--);
else
throw new NoSuchElementException();
}
}
An implementation for the array situation is quite similar. Of cause an iterator can be source for a stream or a collection as well.
So not always it is best to create a new array just to provide a reverse view when all you want to do is iterating over the array / list or feed it into a stream or a new collection / array.
I cannot solve it with source ./myscript.sh
. It says the source not found error.
Failed also when using . ./myscript.sh
. It gives can't open myscript.sh.
So my option is put it in a text file to be called in the next script.
#!/bin/sh
echo "Perform Operation in su mode"
echo "ARCH=arm" >> environment.txt
echo "Export ARCH=arm Executed"
export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"
echo "Export path done"
export "CROSS_COMPILE='/home/linux/Practise/linux-devkit/bin/arm-arago-linux-gnueabi-' ## What's next to -?" >> environment.txt
echo "Export CROSS_COMPILE done"
# continue your compilation commands here
...
Tnen call it whenever is needed:
while read -r line; do
line=$(sed -e 's/[[:space:]]*$//' <<<${line})
var=`echo $line | cut -d '=' -f1`; test=$(echo $var)
if [ -z "$(test)" ];then eval export "$line";fi
done <environment.txt
Just returning response()->json($promotion)
won't solve the issue in this question. $promotion
is an Eloquent object, which Laravel will automatically json_encode for the response. The json encoding is failing because of the img
property, which is a PHP stream resource, and cannot be encoded.
Whatever you return from your controller, Laravel is going to attempt to convert to a string. When you return an object, the object's __toString()
magic method will be invoked to make the conversion.
Therefore, when you just return $promotion
from your controller action, Laravel is going to call __toString()
on it to convert it to a string to display.
On the Model
, __toString()
calls toJson()
, which returns the result of json_encode
. Therefore, json_encode
is returning false
, meaning it is running into an error.
Your dd
shows that your img
attribute is a stream resource
. json_encode
cannot encode a resource
, so this is probably causing the failure. You should add your img
attribute to the $hidden
property to remove it from the json_encode
.
class Promotion extends Model
{
protected $hidden = ['img'];
// rest of class
}
I had a similar situation trying to exec()
a backend command and also getting no tty present and no askpass program specified
in the web server error log. Original (bad) code:
$output = array();
$return_var = 0;
exec('sudo my_command', $output, $return_var);
A bash
wrapper solved this issue, such as:
$output = array();
$return_var = 0;
exec('sudo bash -c "my_command"', $output, $return_var);
Not sure if this will work in every case. Also, be sure to apply the appropriate quoting/escaping rules on my_command
portion.
In my case, I created a new project and when I ran it the first time, it gave me the following error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
So my solution was to go to the Package Manager Console inside the Visual Studio and run:Update-Package
Problem solved!!
I think that using the event tabPage1.Enter
is more convenient.
tabPage1.Enter += new System.EventHandler(tabPage1_Enter);
private void tabPage1_Enter(object sender, EventArgs e)
{
MessageBox.Show("you entered tabPage1");
}
This is better than having nested if-else statement when you have different logic for different tabs. And more suitable in case new tabs may be added in the future.
Note that this event fires if the form loads and tabPage1
is opened by default.
.toString()
is available, or just add ""
to the end of the int
var x = 3,
toString = x.toString(),
toConcat = x + "";
Angular is simply JavaScript at the core.
It depends on context. There a lot benefits that are appropriate to dynamic typed system as well as for strong typed. I'm of opinion that the flow of dynamic types language is faster. The dynamic languages are not constrained with class attributes and compiler thinking of what is going on in code. You have some kinda freedom. Furthermore, the dynamic language usually is more expressive and result in less code which is good. Despite of this, it's more error prone which is also questionable and depends more on unit test covering. It's easy prototype with dynamic lang but maintenance may become nightmare.
The main gain over static typed system is IDE support and surely static analyzer of code. You become more confident of code after every code change. The maintenance is peace of cake with such tools.
I had same problem with Spring Boot 2.1.1 and JUnit 4
just added those annotations:
@RunWith( SpringRunner.class )
@SpringBootTest
and all went well.
For Junit 5:
@ExtendWith(SpringExtension.class)
Try:
$(document).ready(function() {
$('#contact-form').validate({submitHandler: function(form) {
var data = $('#contact-form').serialize();
$.post(
'url_request',
{data: data},
function(response){
console.log(response);
}
);
}
});
});
If you want to retrieve the length (and possibly all other metadata) from your media file with ffmpeg by using a python script you could try this:
import subprocess
import json
input_file = "< path to your input file here >"
metadata = subprocess.check_output(f"ffprobe -i {input_file} -v quiet -print_format json -show_format -hide_banner".split(" "))
metadata = json.loads(metadata)
print(f"Length of file is: {float(metadata['format']['duration'])}")
print(metadata)
Output:
Length of file is: 7579.977143
{
"streams": [
{
"index": 0,
"codec_name": "mp3",
"codec_long_name": "MP3 (MPEG audio layer 3)",
"codec_type": "audio",
"codec_time_base": "1/44100",
"codec_tag_string": "[0][0][0][0]",
"codec_tag": "0x0000",
"sample_fmt": "fltp",
"sample_rate": "44100",
"channels": 2,
"channel_layout": "stereo",
"bits_per_sample": 0,
"r_frame_rate": "0/0",
"avg_frame_rate": "0/0",
"time_base": "1/14112000",
"start_pts": 353600,
"start_time": "0.025057",
"duration_ts": 106968637440,
"duration": "7579.977143",
"bit_rate": "320000",
...
...
It is quite simple to maintain order. I had the same problem with maintaining the order from DB layer to UI Layer.
Open JSONObject.java file. It internally uses HashMap which doesn't maintain the order.
Change it to LinkedHashMap:
//this.map = new HashMap();
this.map = new LinkedHashMap();
This worked for me. Let me know in the comments. I suggest the JSON library itself should have another JSONObject class which maintains order, like JSONOrderdObject.java. I am very poor in choosing the names.
My problem was that I tried to import a Django model before calling django.setup()
This worked for me:
import django
django.setup()
from myapp.models import MyModel
The above script is in the project root folder.
If you just have a link without a click event handler:
<a href="javascript:window.print();">Print Page</a>
easy if its pdf or img use
return (in_Array($file['content-type'], ['image/jpg', 'application/pdf']));
There is an important part of the conversation surrounding lexical and dynamic scoping that is missing: a plain explanation of the lifetime of the scoped variable - or when the variable can be accessed.
Dynamic scoping only very loosely corresponds to "global" scoping in the way that we traditionally think about it (the reason I bring up the comparison between the two is that it has already been mentioned - and I don't particularly like the linked article's explanation); it is probably best we don't make the comparison between global and dynamic - though supposedly, according to the linked article, "...[it] is useful as a substitute for globally scoped variables."
So, in plain English, what's the important distinction between the two scoping mechanisms?
Lexical scoping has been defined very well throughout the answers above: lexically scoped variables are available - or, accessible - at the local level of the function in which it was defined.
However - as it is not the focus of the OP - dynamic scoping has not received a great deal of attention and the attention it has received means it probably needs a bit more (that's not a criticism of other answers, but rather a "oh, that answer made we wish there was a bit more"). So, here's a little bit more:
Dynamic scoping means that a variable is accessible to the larger program during the lifetime of the function call - or, while the function is executing. Really, Wikipedia actually does a nice job with the explanation of the difference between the two. So as not to obfuscate it, here is the text that describes dynamic scoping:
...[I]n dynamic scoping (or dynamic scope), if a variable name's scope is a certain function, then its scope is the time-period during which the function is executing: while the function is running, the variable name exists, and is bound to its variable, but after the function returns, the variable name does not exist.
There is the command line parameter --spider
exactly for this. In this mode, wget does not download the files and its return value is zero if the resource was found and non-zero if it was not found. Try this (in your favorite shell):
wget -q --spider address
echo $?
Or if you want full output, leave the -q
off, so just wget --spider address
. -nv
shows some output, but not as much as the default.
Line continuations also can be achieved through clever use of syntax.
In the case of echo
:
# echo '-n' flag prevents trailing <CR>
echo -n "This is my one-line statement" ;
echo -n " that I would like to make."
This is my one-line statement that I would like to make.
In the case of vars:
outp="This is my one-line statement" ;
outp+=" that I would like to make." ;
echo -n "${outp}"
This is my one-line statement that I would like to make.
Another approach in the case of vars:
outp="This is my one-line statement" ;
outp="${outp} that I would like to make." ;
echo -n "${outp}"
This is my one-line statement that I would like to make.
Voila!
I have developed custom javascript to achieve this feature by just adding class
Example: <button type="button" class="ctrl-p">Custom Print</button>
Here Check it out Fiddle
-- or --
check out running example
https://stackoverflow.com/a/58010042/6631280
Note: on current logic, you need to press Ctrl + Enter
Just to state the obvious for anyone viewing this discussion.... if you give any of your folders 777 permissions, you are allowing ANYONE to read, write and execute any file in that directory.... what this means is you have given ANYONE (any hacker or malicious person in the entire world) permission to upload ANY file, virus or any other file, and THEN execute that file...
IF YOU ARE SETTING YOUR FOLDER PERMISSIONS TO 777 YOU HAVE OPENED YOUR SERVER TO ANYONE THAT CAN FIND THAT DIRECTORY. Clear enough??? :)
There are basically two ways to setup your ownership and permissions. Either you give yourself ownership or you make the webserver the owner of all files.
Webserver as owner (the way most people do it, and the Laravel doc's way):
assuming www-data (it could be something else) is your webserver user.
sudo chown -R www-data:www-data /path/to/your/laravel/root/directory
if you do that, the webserver owns all the files, and is also the group, and you will have some problems uploading files or working with files via FTP, because your FTP client will be logged in as you, not your webserver, so add your user to the webserver user group:
sudo usermod -a -G www-data ubuntu
Of course, this assumes your webserver is running as www-data (the Homestead default), and your user is ubuntu (it's vagrant if you are using Homestead).
Then you set all your directories to 755 and your files to 644... SET file permissions
sudo find /path/to/your/laravel/root/directory -type f -exec chmod 644 {} \;
SET directory permissions
sudo find /path/to/your/laravel/root/directory -type d -exec chmod 755 {} \;
Your user as owner
I prefer to own all the directories and files (it makes working with everything much easier), so, go to your laravel root directory:
cd /var/www/html/laravel >> assuming this is your current root directory
sudo chown -R $USER:www-data .
Then I give both myself and the webserver permissions:
sudo find . -type f -exec chmod 664 {} \; sudo find . -type d -exec chmod 775 {} \;
Then give the webserver the rights to read and write to storage and cache
Whichever way you set it up, then you need to give read and write permissions to the webserver for storage, cache and any other directories the webserver needs to upload or write too (depending on your situation), so run the commands from bashy above :
sudo chgrp -R www-data storage bootstrap/cache sudo chmod -R ug+rwx storage bootstrap/cache
Now, you're secure and your website works, AND you can work with the files fairly easily