We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.
Check your linker flags:
Target > Build Settings > Other Linker Flags
You should see -lApptentiveConnect
listed as a linker flag:
... -ObjC -lApptentiveConnect ...
You should also see our required Frameworks listed:
UIKit
-ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit
If you're creating a framework the whole idea is to make it portable. Tying a framework to the app delegate defeats the purpose of building a framework. What is it you need the app delegate for?
As @Ebin Joy said, If your gradle file get corrupted then there is one simple solution for that. Manually give the proxy details like shown in image. then you're good to go. This solution only works if you using any closed networks like office network etc.
If your application is hosted on IIS/IIS Express try the following:
c.SwaggerEndpoint("../swagger/v1/swagger.json", "MyAPI V1");
In my case I found once I rebuild the app it worked.
I had imported the HttpClientModule
as specified in the previous posts but I was still getting the error. I stopped the server, rebuilt the app (ng serve
) and it worked.
Enable Multidex through build.gradle
of your app module
multiDexEnabled true
Same as below -
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.xx.xxx"
minSdkVersion 15
targetSdkVersion 27
versionCode 1
versionName "1.0"
multiDexEnabled true //Add this
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
shrinkResources true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
Then follow below steps -
Build
menu -> press the Clean Project
button.Rebuild Project
button from the Build
menu.File -> Invalidate cashes / Restart
compile
is now deprecated so it's better to use implementation
or api
You shouldn't use ${varName}
when you're outside of strings, you should just use varName
. Inside strings you use it like this; echo "this is a string ${someVariable}";
. Infact you can place an general java expression inside of ${...}
; echo "this is a string ${func(arg1, arg2)}
.
Sometimes it also happens when the function need to be executed in main thread only, so you can fix it by assigning it to the main thread as follows :-
DispatchQueue.main.async{
your code here
}
You did not post the code generated by the compiler, so there' some guesswork here, but even without having seen it, one can say that this:
test rax, 1
jpe even
... has a 50% chance of mispredicting the branch, and that will come expensive.
The compiler almost certainly does both computations (which costs neglegibly more since the div/mod is quite long latency, so the multiply-add is "free") and follows up with a CMOV. Which, of course, has a zero percent chance of being mispredicted.
it just simple :import this directory
import {Component, Directive, Input, ViewChild} from '@angular/core';
For future googlers: You can also use copy-webpack-plugin and add this to webpack's production config:
plugins: [
new CopyWebpackPlugin({
patterns: [
// relative path is from src
{ from: './static/favicon.ico' }, // <- your path to favicon
]
})
]
It looks like latest RxJS requires typescript 1.8 so typescript 1.7 reports the above error.
I solved this issue by upgrading to the latest typescript version.
I'm probably a bit late to the party, but I wrote the junitcategorizer for my thesis project at TOPdesk. Earlier versions indeed used a company internal Parent POM. So your problems are caused by the Parent POM not being resolvable, since it is not available to the outside world.
You can either:
<parent>
block, but then have to configure the Surefire, Compiler and other plugins yourself<parent>
<groupId>com.topdesk</groupId>
<artifactId>open-source-parent</artifactId>
<version>1.2.0</version>
</parent>
Just add those below line in pom.xml file on the top of <modelversion>
tag:
<repositories>
<repository>
<id>central</id>
<name>Central Repository</name>
<url>http://repo.maven.apache.org/maven2</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
SWIFT 4 Update
@IBOutlet weak var tripDetails: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(GameViewController.tapFunction))
tripDetails.isUserInteractionEnabled = true
tripDetails.addGestureRecognizer(tap)
}
@objc func tapFunction(sender:UITapGestureRecognizer) {
print("tap working")
}
The justify-self
and justify-items
properties are not implemented in flexbox. This is due to the one-dimensional nature of flexbox, and that there may be multiple items along the axis, making it impossible to justify a single item. To align items along the main, inline axis in flexbox you use the justify-content
property.
Reference: Box alignment in CSS Grid Layout
This problem is caused by RecyclerView Data modified in different thread
Can confirm threading as one problem and since I ran into the issue and RxJava is becoming increasingly popular: make sure that you are using .observeOn(AndroidSchedulers.mainThread())
whenever you're calling notify[whatever changed]
code example from adapter:
myAuxDataStructure.getChangeObservable().observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<AuxDataStructure>() {
[...]
@Override
public void onNext(AuxDataStructure o) {
[notify here]
}
});
Just remove activation section, I don't know why -Pdev1 doesn't override default false activation. But if you omit this:
<activation>
<activeByDefault>false</activeByDefault>
</activation>
then your profile will be activated only after explicit declaration as -Pdev1
Try resetting your password for the email used. Had similar issue, and got it fixed only after changing password.
For me i was adding the whole playstore dependencies
compile 'com.google.android.gms:play-services:8.4.0'
But i needed google map only , so i made it more specific and the error was resolved.
compile 'com.google.android.gms:play-services-maps:8.4.0'
In my computer, I get this code works.It's a little different from Daimon's answer.
@SqlResultSetMapping(_x000D_
name="groupDetailsMapping",_x000D_
classes={_x000D_
@ConstructorResult(_x000D_
targetClass=GroupDetails.class,_x000D_
columns={_x000D_
@ColumnResult(name="GROUP_ID",type=Integer.class),_x000D_
@ColumnResult(name="USER_ID",type=Integer.class)_x000D_
}_x000D_
)_x000D_
}_x000D_
)_x000D_
_x000D_
@NamedNativeQuery(name="User.getGroupDetails", query="SELECT g.*, gm.* FROM group g LEFT JOIN group_members gm ON g.group_id = gm.group_id and gm.user_id = :userId WHERE g.group_id = :groupId", resultSetMapping="groupDetailsMapping")
_x000D_
If you're not using the storyboard. You can initialize your main view controller programmatically.
Swift 4
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let rootViewController = MainViewController()
let navigationController = UINavigationController(rootViewController: rootViewController)
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = navigationController
self.window?.makeKeyAndVisible()
return true
}
class MainViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .green
}
}
And also remove Main
from Deployment Info.
I encountered this bug when attempting to define a new OptionSetType
struct in Swift 2. When I corrected the type on the init()
parameter from Self.RawValue
to Int
the crash stopped occurring:
// bad:
// public init(rawValue: Self.RawValue) {
// self.rawValue = rawValue
// }
// good:
public init(rawValue: Int) {
self.rawValue = rawValue
}
I tried using all the above, nothing worked in my case.
I used the SumUp library which was causing this issue.
I fixed it by:
That still didn't fix the issue, I was still seeing errors all over the place hence coming to this thread,... however, after playing around with the settings the following fixed it:
I hope this helps for people using SumUP integration, it took the whole day to find out...
Cheers,
H
This usually appears when you want to use UIActivityViewController
in iPad.
Add below, before you present the controller to mark the arrow.
activityViewController.popoverPresentationController?.sourceRect = senderView.frame // senderView can be your button/view you tapped to call this VC
I assume you already have below, if not, add together:
activityViewController.popoverPresentationController?.sourceView = self.view
Use of main thread to present and dismiss view controller worked for me.
DispatchQueue.main.async { self.present(viewController, animated: true, completion: nil) }
Add this in your did load
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.0)
//adjust alpha according to your need 0 is transparent 1 is solid
Sometimes this error also appears when you have a var or a let that hasn't been intialized.
For example
class ViewController: UIViewController {
var x: Double
// or
var y: String
// or
let z: Int
}
Depending on what your variable is supposed to do you might either set that var type as an optional or initialize it with a value like the following
class ViewController: UIViewCOntroller {
// Set an initial value for the variable
var x: Double = 0
// or an optional String
var y: String?
// or
let z: Int = 2
}
I solved this by writing the explicit IP address defined in the Listener.ora file as the hostname.
So, instead of "localhost", I wrote "192.168.1.2" as the "Hostname" in the SQL Developer field.
In the below picture I highlighted the input boxes that I've modified:
Another code swift3
let myLabel = UILabel()
myLabel.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
myLabel.center = CGPoint(x: 0, y: 0)
myLabel.textAlignment = .center
myLabel.text = "myLabel!!!!!"
self.view.addSubview(myLabel)
One thing I mentioned in another thread that is worth pointing out -- if you are building different versions of your app for different densities, you should know about the "mipmap" resource directory. This is exactly like "drawable" resources, except it does not participate in density stripping when creating the different apk targets.
https://plus.google.com/105051985738280261832/posts/QTA9McYan1L
The short answer is "yes". A sample ldapsearch
command to query an Active Directory server is:
ldapsearch \
-x -h ldapserver.mydomain.com \
-D "[email protected]" \
-W \
-b "cn=users,dc=mydomain,dc=com" \
-s sub "(cn=*)" cn mail sn
This would connect to an AD server at hostname ldapserver.mydomain.com
as user [email protected]
, prompt for the password on the command line and show name and email details for users in the cn=users,dc=mydomain,dc=com
subtree.
See Managing LDAP from the Command Line on Linux for more samples. See LDAP Query Basics for Microsoft Exchange documentation for samples using LDAP queries with Active Directory.
An alternative method is to use a Gulp plugin created specifically for this problem. https://www.npmjs.com/package/gulp-ng-module-sort
It allows you to sort your scripts by adding in a .pipe(ngModuleSort())
as such:
var ngModuleSort = require('gulp-ng-module-sort');
var concat = require('gulp-concat');
gulp.task('angular-scripts', function() {
return gulp.src('./src/app/**/*.js')
.pipe(ngModuleSort())
.pipe(concat('angularAppScripts.js))
.pipe(gulp.dest('./dist/));
});
Assuming a directory convention of:
|——— src/
| |——— app/
| |——— module1/
| |——— sub-module1/
| |——— sub-module1.js
| |——— module1.js
| |——— module2/
| |——— sub-module2/
| |——— sub-module2.js
| |——— sub-module3/
| |——— sub-module3.js
| |——— module2.js
| |——— app.js
Hope this helps!
I face the same problem, and think that I do know why this happens.
The gmail account that I use is normally used from India, and the webserver that I use is located in The Netherlands.
Google notifies that there was a login attempt from am unusualy location and requires to login from that location via a web browser.
Furthermore I had to accept suspicious access to the gmail account via https://security.google.com/settings/security/activity
But in the end my problem is not yet solved, because I have to login to gmail from a location in The Netherlands.
I hope this will help you a little! (sorry, I do not read email replies on this email address)
If your are using gmail.
1-logon to your account
2- browse this link
3- Allow less secure apps: ON
Enjoy....
If you are using an SMTP server on the same box and your SMTP is bound to an IP address instead of "Any Assigned" it may fail because it is trying to use an IP address (like 127.0.0.1) that SMTP is not currently working on.
Here's my Swifty solution for any future onlookers.
1) Create a protocol to handle both login and logout functions:
protocol LoginFlowHandler {
func handleLogin(withWindow window: UIWindow?)
func handleLogout(withWindow window: UIWindow?)
}
2) Extend said protocol and provide the functionality here for logging out:
extension LoginFlowHandler {
func handleLogin(withWindow window: UIWindow?) {
if let _ = AppState.shared.currentUserId {
//User has logged in before, cache and continue
self.showMainApp(withWindow: window)
} else {
//No user information, show login flow
self.showLogin(withWindow: window)
}
}
func handleLogout(withWindow window: UIWindow?) {
AppState.shared.signOut()
showLogin(withWindow: window)
}
func showLogin(withWindow window: UIWindow?) {
window?.subviews.forEach { $0.removeFromSuperview() }
window?.rootViewController = nil
window?.rootViewController = R.storyboard.login.instantiateInitialViewController()
window?.makeKeyAndVisible()
}
func showMainApp(withWindow window: UIWindow?) {
window?.rootViewController = nil
window?.rootViewController = R.storyboard.mainTabBar.instantiateInitialViewController()
window?.makeKeyAndVisible()
}
}
3) Then I can conform my AppDelegate to the LoginFlowHandler protocol, and call handleLogin
on startup:
class AppDelegate: UIResponder, UIApplicationDelegate, LoginFlowHandler {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow.init(frame: UIScreen.main.bounds)
initialiseServices()
handleLogin(withWindow: window)
return true
}
}
From here, my protocol extension will handle the logic or determining if the user if logged in/out, and then change the windows rootViewController accordingly!
This might help you
In most cases, the system does not relaunch apps after they are force quit by the user. One exception is location apps, which in iOS 8 and later are relaunched after being force quit by the user. In other cases, though, the user must launch the app explicitly or reboot the device before the app can be launched automatically into the background by the system. When password protection is enabled on the device, the system does not launch an app in the background before the user first unlocks the device.
$mail->IsSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Username = "[email protected]";
$mail->Password = "**********";
$mail->Port = "465";
That is a working configuration.
try to replace what you have
Make sure that Access less secure app is allowed.
MailMessage mail = new MailMessage();
mail.From = new MailAddress("[email protected]");
mail.Sender = new MailAddress("[email protected]");
mail.To.Add("external@emailaddress");
mail.IsBodyHtml = true;
mail.Subject = "Email Sent";
mail.Body = "Body content from";
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "xx");
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.EnableSsl = true;
smtp.Timeout = 30000;
try
{
smtp.Send(mail);
}
catch (SmtpException e)
{
textBox1.Text= e.Message;
}
If it works on your localhost but not on your web host:
Some hosting sites block certain outbound SMTP ports. Commenting out the line $mail->IsSMTP();
as noted in the accepted answer may make it work, but it is simply disabling your SMTP configuration, and using the hosting site's email config.
If you are using GoDaddy, there is no way to send mail using a different SMTP. I was using SiteGround, and found that they were allowing SMTP access from ports 25 and 465 only, with an SSL encryption type, so I would look up documentation for your host and go from there.
In my case the hosting had a whitelist for remote connection to MySql. Try to add your IP to whitelist in hosting admin panel.
I've created a couple of map tutorials that will cover what you need
Animating the map describes howto create polylines based on a set of LatLngs. Using Google APIs on your map : Directions and Places describes howto use the Directions API and animate a marker along the path.
Take a look at these 2 tutorials and the Github project containing the sample app.
It contains some tips to make your code cleaner and more efficient:
In Swift 4.2 and Xcode 10.1
You can change your navigation bar colour from your AppDelegate directly to your entire project.
In didFinishLaunchingWithOptions launchOptions:
write below to lines of code
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().barTintColor = UIColor(red: 2/255, green: 96/255, blue: 130/255, alpha: 1.0)
Here
tintColor is for to set background images like back button & menu lines images etc. (See below left and right menu image)
barTintColor is for navigation bar background colour
If you want to set specific view controller navigation bar colour, write below code in viewDidLoad()
//Add navigation bar colour
navigationController?.navigationBar.barTintColor = UIColor(red: 2/255, green: 96/255, blue: 130/255, alpha: 1.0)
navigationController?.navigationBar.tintColor = UIColor.white
You are missing the event parameter on your function.
$(document).on("click",".appDetails", function (event) {
alert(event.target.id);
});
In Android Studio goto: File -> Project Structure... -> Notifications (last entry) -> check Google Cloud Messaging
Wait a few seconds and you're done :) import com.google.android.gms.gcm.GcmListenerService should be resolved properly
The default configuration of most SMTP servers is not to relay from an untrusted source to outside domains. For example, imagine that you contact the SMTP server for foo.com and ask it to send a message to [email protected]. Because the SMTP server doesn't really know who you are, it will refuse to relay the message. If the server did do that for you, it would be considered an open relay, which is how spammers often do their thing.
If you contact the foo.com mail server and ask it to send mail to [email protected], it might let you do it. It depends on if they trust that you're who you say you are. Often, the server will try to do a reverse DNS lookup, and refuse to send mail if the IP you're sending from doesn't match the IP address of the MX record in DNS. So if you say that you're the bar.com mail server but your IP address doesn't match the MX record for bar.com, then it will refuse to deliver the message.
You'll need to talk to the administrator of that SMTP server to get the authentication information so that it will allow relay for you. You'll need to present those credentials when you contact the SMTP server. Usually it's either a user name/password, or it can use Windows permissions. Depends on the server and how it's configured.
See Unable to send emails to external domain using SMTP for an example of how to send the credentials.
If you want to align the div
with pixel accurate, then use float. inline-block
seems to always requires you to chop off a few pixels (at least in IE)
To make sure it's a simulator issue, see if you can connect to the simulator with a brand new project without changing any code. Try the tab bar template.
If you think it's a simulator issue, press the iOS Simulator menu. Select "Reset Content and Settings...". Press "Reset."
I can't see your XIB and what @properties you have connected in Interface Builder, but it could also be that you're not loading your window, or that your window is not loading your view controller.
Avoid using Activity implements OnMarkerClickListener, use a local OnMarkerClickListener
// Not a good idea
class MapActivity extends Activity implements OnMarkerClickListener {
}
You will need a map to lookup the original data model linked to the marker
private Map<Marker, Map<String, Object>> markers = new HashMap<>();
You will need a data model
private Map<String, Object> dataModel = new HashMap<>();
Put some data in the data model
dataModel.put("title", "My Spot");
dataModel.put("snipet", "This is my spot!");
dataModel.put("latitude", 20.0f);
dataModel.put("longitude", 100.0f);
When creating a new marker using a data model add both to the maker map
Marker marker = googleMap.addMarker(markerOptions);
markers.put(marker, dataModel);
For on click marker event, use a local OnMarkerClickListener:
@Override
public void onMapReady(GoogleMap googleMap) {
// grab for laters
this.googleMap = googleMap;
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
Map dataModel = (Map)markers.get(marker);
String title = (String)dataModel.get("title");
markerOnClick(title);
return false;
}
});
mapView.onResume();
showMarkers();
ZoomAsync zoomAsync = new ZoomAsync();
zoomAsync.execute();
}
For displaying the info window retrieve the original data model from the marker map:
@Override
public void onMapReady(GoogleMap googleMap) {
this.googleMap = googleMap;
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
@Override
public void onInfoWindowClick(Marker marker) {
Map dataModel = (Map)markers.get(marker);
String title = (String)dataModel.get("title");
infoWindowOnClick(title);
}
});
It sounds like you might need to create and query linked database servers in SQL Server
At the moment you've created a query that's going between different databases using a 3 part name mydatabase.dbo.mytable
but you need to go up a level and use a 4 part name myserver.mydatabase.dbo.mytable
, see this post on four part naming for more info
edit
The four part naming for your existing query would be as shown below (which I suspect you may have already tried?), but this assumes you can "get to" the remote database with the four part name, you might need to edit your host file / register the server or otherwise identify where to find database.windows.net
.
INSERT INTO [DATABASE.WINDOWS.NET].[basecampdev].[dbo].[invoice]
([InvoiceNumber]
,[TotalAmount]
,[IsActive]
,[CreatedBy]
,[UpdatedBy]
,[CreatedDate]
,[UpdatedDate]
,[Remarks])
SELECT [InvoiceNumber]
,[TotalAmount]
,[IsActive]
,[CreatedBy]
,[UpdatedBy]
,[CreatedDate]
,[UpdatedDate]
,[Remarks] FROM [BC1-PC].[testdabse].[dbo].[invoice]
If you can't access the remote server then see if you can create a linked database server:
EXEC sp_addlinkedserver [database.windows.net];
GO
USE tempdb;
GO
CREATE SYNONYM MyInvoice FOR
[database.windows.net].basecampdev.dbo.invoice;
GO
Then you can just query against MyEmployee
without needing the full four part name
I don't get the true solution but I solve it after doing these things:
- Tick 'Copy projects into workspace' when importing google-play-services_lib
- Don't set the minSdkVersion below 13
- If you get error with theme, try changing your layout theme to any system theme
- Re-create your project from scratch or revert everything if you get it from somewhere
I give you the answer in both Objective C and Swift.Before that I want to say
If we use the
dequeueReusableCellWithIdentifier:forIndexPath:
,we must register a class or nib file using the registerNib:forCellReuseIdentifier: or registerClass:forCellReuseIdentifier: method before calling this method as Apple Documnetation Says
So we add registerNib:forCellReuseIdentifier: or registerClass:forCellReuseIdentifier:
Once we registered a class for the specified identifier and a new cell must be created, this method initializes the cell by calling its initWithStyle:reuseIdentifier: method. For nib-based cells, this method loads the cell object from the provided nib file. If an existing cell was available for reuse, this method calls the cell’s prepareForReuse method instead.
in viewDidLoad method we should register the cell
Objective C
OPTION 1:
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
OPTION 2:
[self.tableView registerNib:[UINib nibWithNibName:@"CustomCell" bundle:nil] forCellReuseIdentifier:@"cell"];
in above code nibWithNibName:@"CustomCell"
give your nib name instead of my nib name CustomCell
SWIFT
OPTION 1:
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
OPTION 2:
tableView.registerNib(UINib(nibName: "NameInput", bundle: nil), forCellReuseIdentifier: "Cell")
in above code nibName:"NameInput"
give your nib name
I spend a hour finding out what was wrong.. But Clean Project did the trick.
Build -> Clean All
The accepted solution is probably also working.. but this was enough for me.
Xcode 7
Select root node of your project -> In editor click on project name -> Select targets -> Identity -> Bundle Identifier
Try using this code:
ALTER TABLE `table name`
CHANGE COLUMN `column name` `column name` datatype NOT NULL,
ADD PRIMARY KEY (`column name`) ;
Swift 2.0 version of jungledev's answer
func getTopViewController() -> UIViewController {
var topViewController = UIApplication.sharedApplication().delegate!.window!!.rootViewController!
while (topViewController.presentedViewController != nil) {
topViewController = topViewController.presentedViewController!
}
return topViewController
}
I had this error too, my problem was in some part of code I didn't close file descriptor and in other part, I tried to open that file!!
use close(fd)
system call after you finished working on a file.
You should use the following code :
Class2 cls2 = new Class2();
cls2.UpdateEmployee();
In case you don't want to create a new instance to call the method, you can decalre the method as static
and then you can just call Class2.UpdateEmployee()
.
At least in the current versions of PHPMailers, there's a function clearReplyTos() to empty the reply-to array.
$mail->ClearReplyTos();
$mail->addReplyTo([email protected], 'EXAMPLE');
It probably is the # sign like tho others have mentioned because this appears to work just fine.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<select id="#ticket_category_clone">
<option value="hw">Hardware</option>
<option>fsdf</option>
<option>sfsd</option>
<option>sdfs</option>
</select>
<script type="text/javascript">
(function check() {
var e = document.getElementById("#ticket_category_clone");
var str = e.options[e.selectedIndex].text;
alert(str);
if (str === "Hardware") {
alert('Hi');
}
})();
</script>
</body>
Besides all above solutions, check if you have the "id
" or any custom defined parameter in the DELETE
method is matching the route config.
public void Delete(int id)
{
//some code here
}
If you hit with repeated 405 errors better reset the method signature to default as above and try.
The route config by default will look for id
in the URL. So the parameter name id
is important here unless you change the route config under the App_Start
folder.
You may change the data type of the id
though.
For example the method below should work just fine:
public void Delete(string id)
{
//some code here
}
Note: Also ensure that you pass the data over the url not the data method that will carry the payload as body content.
DELETE http://{url}/{action}/{id}
Example:
DELETE http://localhost/item/1
Hope it helps.
SIGABRT means in general that there is an uncaught exception. There should be more information on the console.
The following worked for me with tomcat 8.
Add these lines to apache-tomcat-8.0.9/conf/tomcat-users.xml
For Manager:
<role rolename="manager-gui"/>
<user username="admin" password="pass" roles="manager-gui"/>
For Host Manager:
<role rolename="admin-gui"/>
<user username="admin" password="pass" roles="admin-gui"/>
//Hope you find it useful, it contain too many things
string smtpAddress = "smtp.xyz.com";
int portNumber = 587;
bool enableSSL = true;
string m_userName = "[email protected]";
string m_UserpassWord = "56436578";
public void SendEmail(Customer _customers)
{
string emailID = [email protected];
string userName = DemoUser;
string emailFrom = "[email protected]";
string password = "qwerty";
string emailTo = emailID;
// Here you can put subject of the mail
string subject = "Registration";
// Body of the mail
string body = "<div style='border: medium solid grey; width: 500px; height: 266px;font-family: arial,sans-serif; font-size: 17px;'>";
body += "<h3 style='background-color: blueviolet; margin-top:0px;'>Aspen Reporting Tool</h3>";
body += "<br />";
body += "Dear " + userName + ",";
body += "<br />";
body += "<p>";
body += "Thank you for registering </p>";
body += "<p><a href='"+ sURL +"'>Click Here</a>To finalize the registration process</p>";
body += " <br />";
body += "Thanks,";
body += "<br />";
body += "<b>The Team</b>";
body += "</div>";
// this is done using using System.Net.Mail; & using System.Net;
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
// Can set to false, if you are sending pure text.
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.Credentials = new NetworkCredential(emailFrom, password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
}
}
This error means that length of index index
is more then 1000 bytes. MySQL and storage engines may have this restriction. I have got similar error on MySQL 5.5 - 'Specified key was too long; max key length is 3072 bytes' when ran this script:
CREATE TABLE IF NOT EXISTS test_table1 (
column1 varchar(500) NOT NULL,
column2 varchar(500) NOT NULL,
column3 varchar(500) NOT NULL,
column4 varchar(500) NOT NULL,
column5 varchar(500) NOT NULL,
column6 varchar(500) NOT NULL,
KEY `index` (column1, column2, column3, column4, column5, column6)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
UTF8 is multi-bytes, and key length is calculated in this way - 500 * 3 * 6 = 9000 bytes.
But note, next query works!
CREATE TABLE IF NOT EXISTS test_table1 (
column1 varchar(500) NOT NULL,
column2 varchar(500) NOT NULL,
column3 varchar(500) NOT NULL,
column4 varchar(500) NOT NULL,
column5 varchar(500) NOT NULL,
column6 varchar(500) NOT NULL,
KEY `index` (column1, column2, column3, column4, column5, column6)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
...because I used CHARSET=latin1, in this case key length is 500 * 6 = 3000 bytes.
Here is a way to get maximum values and names on any version of SQL.
Test Data:
CREATE TABLE EmpDetails(DeptID VARCHAR(10), EmpName VARCHAR(10), Salary DECIMAL(8,2))
INSERT INTO EmpDetails VALUES('Engg','Sam',1000)
INSERT INTO EmpDetails VALUES('Engg','Smith',2000)
INSERT INTO EmpDetails VALUES('HR','Denis',1500)
INSERT INTO EmpDetails VALUES('HR','Danny',3000)
INSERT INTO EmpDetails VALUES('IT','David',2000)
INSERT INTO EmpDetails VALUES('IT','John',3000)
Example:
SELECT ed.DeptID
,ed.EmpName
,ed.Salary
FROM (SELECT DeptID, MAX(Salary) MaxSal
FROM EmpDetails
GROUP BY DeptID)AS empmaxsal
INNER JOIN EmpDetails ed
ON empmaxsal.DeptID = ed.DeptID
AND empmaxsal.MaxSal = ed.Salary
Not the most elegant, but it works.
How to use an IF statement in the MySQL "select list":
select if (1>2, 2, 3); //returns 3
select if(1<2,'yes','no'); //returns yes
SELECT IF(STRCMP('test','test1'),'no','yes'); //returns no
How to use an IF statement in the MySQL where clause search condition list:
create table penguins (id int primary key auto_increment, name varchar(100))
insert into penguins (name) values ('rico')
insert into penguins (name) values ('kowalski')
insert into penguins (name) values ('skipper')
select * from penguins where 3 = id
-->3 skipper
select * from penguins where (if (true, 2, 3)) = id
-->2 kowalski
How to use an IF statement in the MySQL "having clause search conditions":
select * from penguins
where 1=1
having (if (true, 2, 3)) = id
-->1 rico
Use an IF statement with a column used in the select list to make a decision:
select (if (id = 2, -1, 1)) item
from penguins
where 1=1
--> 1
--> -1
--> 1
If statements embedded in SQL queries is a bad "code smell". Bad code has high "WTF's per minute" during code review. This is one of those things. If I see this in production with your name on it, I'm going to automatically not like you.
The T is just a literal to separate the date from the time, and the Z means "zero hour offset" also known as "Zulu time" (UTC). If your strings always have a "Z" you can use:
SimpleDateFormat format = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
Or using Joda Time, you can use ISODateTimeFormat.dateTime()
.
If you use XCode
5 you should do it in a different way.
UIViewController
in UIStoryboard
Identity Inspector
on the right top paneUse Storyboard ID
checkboxStoryboard ID
fieldThen write your code.
// Override point for customization after application launch.
if (<your implementation>) {
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main"
bundle: nil];
YourViewController *yourController = (YourViewController *)[mainStoryboard
instantiateViewControllerWithIdentifier:@"YourViewControllerID"];
self.window.rootViewController = yourController;
}
return YES;
You could possibly use Reflection to do this. As far as I understand it, you could enumerate the properties of your class and set the values. You would have to try this out and make sure you understand the order of the properties though. Refer to this MSDN Documentation for more information on this approach.
For a hint, you could possibly do something like:
Record record = new Record();
PropertyInfo[] properties = typeof(Record).GetProperties();
foreach (PropertyInfo property in properties)
{
property.SetValue(record, value);
}
Where value
is the value you're wanting to write in (so from your resultItems
array).
Instead of using:
self.present(viewControllerToPresent: UIViewController, animated: Bool, completion: (() -> Void)?)
you can use:
self.navigationController?.pushViewController(viewController: UIViewController, animated: Bool)
Not really to answer OP's question (it's resolved anyway), but to help people who may stumble into the similar issue.
Here is what we had:
#
# A fatal error has been detected by the Java Runtime Environment:
#
# SIGSEGV (0xb) at pc=0x0000000000000000, pid=11, tid=139910430250752
#
# JRE version: Java(TM) SE Runtime Environment (8.0_77-b03) (build 1.8.0_77-b03)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.77-b03 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# C 0x0000000000000000
#
# Core dump written. Default location: /builds/c5b22963/0/reporting/arsng2/core or core.11
#
The reason was defective RAM.
List<T>.Add
adds a single element. Instead, use List<T>.AddRange
to add multiple values.
Additionally, List<T>.AddRange
takes an IEnumerable<T>
, so you don't need to convert tripDetails
into a List<TripDetails>
, you can pass it directly, e.g.:
tripDetailsCollection.AddRange(tripDetails);
create or replace
TRIGGER triggername BEFORE INSERT ON
table FOR EACH ROW
BEGIN
/*
Write any select condition if you want to get the data from other tables
*/
:NEW.COLUMNA:= UPPER(COLUMNA);
--:NEW.COUMNa:= NULL;
END;
The above trigger will update the column value before inserting. For example if we give the value of COLUMNA as null it will update the column as null for each insert statement.
SELECT * FROM TABLE ORDER BY ID DESC LIMIT 1
Yes this is mysql, SQL Server:
SELECT TOP 1 * FROM Table ORDER BY ID DESC
This should work:
[tableView deselectRowAtIndexPath:indexpath1 animated:NO];
Just make sure materialTable and tableView are pointing to the same object.
Is materials connected to the tableView in Interface Builder?
Yes, you need OpenSSL to work correctly. My backup testing site worked, my live server didn't. Difference? Live server didn't have OpenSSL within PHP configuration.
Basically, the third parameter in loggedIn
should not be an integer, it should be an object of some kind, but we can't know for sure because you did not name the parameters in the method call. Provide the method signature so we can see for sure. Perhaps it takes an NSNumber
or something.
import base64
a = 'eW91ciB0ZXh0'
base64.b64decode(a)
A quick way to decode it without importing anything:
'eW91ciB0ZXh0'.decode('base64')
or more descriptive
>>> a = 'eW91ciB0ZXh0'
>>> a.decode('base64')
'your text'
Type it in one cell, copy that cell, select all the cells you want to fill, and paste.
Alternatively, type it in one cell, select the black square in the bottom-right of that cell, and drag down.
Your performance problems are more likely to be because of the number of joins you are doing and whether the columns you are joining on have indexes or not.
Worst case you could easily be doing 9 whole table scans for each join.
I am currently working on an open-source disassembler / decompiler called Assembly Analyzer. It generates source code for methods, displays assembly metadata and resources, and allows you to walk through dependencies.
The project is hosted on CodePlex => http://asmanalyzer.codeplex.com/
Swift 4 introduced the Codable protocol which does all the magic for these kinds of tasks. Just conform your custom struct/class to it:
struct Player: Codable {
let name: String
let life: Double
}
And for storing in the Defaults you can use the PropertyListEncoder/Decoder:
let player = Player(name: "Jim", life: 3.14)
UserDefaults.standard.set(try! PropertyListEncoder().encode(player), forKey: kPlayerDefaultsKey)
let storedObject: Data = UserDefaults.standard.object(forKey: kPlayerDefaultsKey) as! Data
let storedPlayer: Player = try! PropertyListDecoder().decode(Player.self, from: storedObject)
It will work like that for arrays and other container classes of such objects too:
try! PropertyListDecoder().decode([Player].self, from: storedArray)
Bump...
I just had the same error. I noticed that I was invoking super.doPost(request, response);
when overriding the doPost()
method as well as explicitly invoking the superclass constructor
public ScheduleServlet() {
super();
// TODO Auto-generated constructor stub
}
As soon as I commented out the super.doPost(request, response);
from within doPost()
statement it worked perfectly...
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//super.doPost(request, response);
// More code here...
}
Needless to say, I need to re-read on super()
best practices :p
The problem raised from using non-typed DBContext or DBSet if you using Interface and implement method of savechanges in a generic way
If this is your case I propose to strongly typed DBContex for example
MyDBContext.MyEntity.Add(mynewObject)
then .Savechanges
will work
This happened to me as well. For me, Postfix was located at the same server as the PHP script, and the error was happening when I would be using SMTP authentication and smtp.domain.com instead of localhost.
So when I commented out these lines:
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls";
and set the host to
$mail->Host = "localhost";
instead
$mail->Host = 'smtp.mydomainiuse.com'
and it worked :)
Just call css with one argument
$('#idDetails').css('display');
If I understand your question. Otherwise, you want cletus' answer.
This code is from Processing.org an open source Java based IDE. You can find it Processing.org. The Arduino IDE also uses this extension, although they run on a hardware board.
EDIT - And yes it is C syntax, used mostly for art or live media presentations.
How are you importing ClassA into your AppDelegate Class? Did you include the .h file in the main project? I had this problem for a while because I didn't copy the header file into the main project as well as the normal #include "ClassA.h."
Copying, or creating the .h solved it for me.
Turn On Access For Less Secure Apps and it will work for all no need to change password.
I found the problem, here's the script of the slow and fast versions of the stored procedure:
dbo.ViewOpener__RenamedForCruachan__Slow.PRC
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE dbo.ViewOpener_RenamedForCruachan_Slow
@SessionGUID uniqueidentifier
AS
SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
dbo.ViewOpener__RenamedForCruachan__Fast.PRC
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE dbo.ViewOpener_RenamedForCruachan_Fast
@SessionGUID uniqueidentifier
AS
SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
If you didn't spot the difference, I don't blame you. The difference is not in the stored procedure at all. The difference that turns a fast 0.5 cost query into one that does an eager spool of 6 million rows:
Slow: SET ANSI_NULLS OFF
Fast: SET ANSI_NULLS ON
This answer also could be made to make sense, since the view does have a join clause that says:
(table.column IS NOT NULL)
So there is some NULL
s involved.
The explanation is further proved by returning to Query Analizer, and running
SET ANSI_NULLS OFF
.
DECLARE @SessionGUID uniqueidentifier
SET @SessionGUID = 'BCBA333C-B6A1-4155-9833-C495F22EA908'
.
SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
And the query is slow.
So the problem isn't because the query is being run from a stored procedure. The problem is that Enterprise Manager's connection default option is ANSI_NULLS off
, rather than ANSI_NULLS on
, which is QA's default.
Microsoft acknowledges this fact in KB296769 (BUG: Cannot use SQL Enterprise Manager to create stored procedures containing linked server objects). The workaround is include the ANSI_NULLS
option in the stored procedure dialog:
Set ANSI_NULLS ON
Go
Create Proc spXXXX as
....
You can always find out the location of the tnsnames.ora file being used by running TNSPING to check connectivity (9i or later):
C:\>tnsping dev
TNS Ping Utility for 32-bit Windows: Version 10.2.0.1.0 - Production on 08-JAN-2009 12:48:38
Copyright (c) 1997, 2005, Oracle. All rights reserved.
Used parameter files:
C:\oracle\product\10.2.0\client_1\NETWORK\ADMIN\sqlnet.ora
Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = XXX)(PORT = 1521)) (CONNECT_DATA = (SERVICE_NAME = DEV)))
OK (30 msec)
C:\>
Sometimes, the problem is with the entry you made in tnsnames.ora, not that the system can't find it. That said, I agree that having a tns_admin environment variable set is a Good Thing, since it avoids the inevitable issues that arise with determining exactly which tnsnames file is being used in systems with multiple oracle homes.
There's also a simpler way. If the image is loaded as a resource in the XAML, and the code in question is the code-behind for that XAML content:
Uri iconUri = new Uri("pack://application:,,,/ImageNAme.ico", UriKind.RelativeOrAbsolute);
NotifyIcon.Icon = BitmapFrame.Create(iconUri);
Are you applying a RowFilter to your DefaultView later in the code? This could change the results returned.
I would also avoid using the string as the display member if you have a direct reference the the data column I would use the object properties:
mnuActionLanguage.ComboBox.DataSource = lTable.DefaultView;
mnuActionLanguage.ComboBox.DisplayMember = lName.ColumnName;
I have tried this with a blank form and standard combo, and seems to work for me.
I used the sdk.
eg:
using SevenZip.Compression.LZMA;
private static void CompressFileLZMA(string inFile, string outFile)
{
SevenZip.Compression.LZMA.Encoder coder = new SevenZip.Compression.LZMA.Encoder();
using (FileStream input = new FileStream(inFile, FileMode.Open))
{
using (FileStream output = new FileStream(outFile, FileMode.Create))
{
coder.Code(input, output, -1, -1, null);
output.Flush();
}
}
}
Here is a simple example:
ThreadTest.java
public class ThreadTest
{
public static void main(String [] args)
{
MyThread t1 = new MyThread(0, 3, 300);
MyThread t2 = new MyThread(1, 3, 300);
MyThread t3 = new MyThread(2, 3, 300);
t1.start();
t2.start();
t3.start();
}
}
MyThread.java
public class MyThread extends Thread
{
private int startIdx, nThreads, maxIdx;
public MyThread(int s, int n, int m)
{
this.startIdx = s;
this.nThreads = n;
this.maxIdx = m;
}
@Override
public void run()
{
for(int i = this.startIdx; i < this.maxIdx; i += this.nThreads)
{
System.out.println("[ID " + this.getId() + "] " + i);
}
}
}
And some output:
[ID 9] 1
[ID 10] 2
[ID 8] 0
[ID 10] 5
[ID 9] 4
[ID 10] 8
[ID 8] 3
[ID 10] 11
[ID 10] 14
[ID 10] 17
[ID 10] 20
[ID 10] 23
An explanation - Each MyThread
object tries to print numbers from 0 to 300, but they are only responsible for certain regions of that range. I chose to split it by indices, with each thread jumping ahead by the number of threads total. So t1
does index 0, 3, 6, 9, etc.
Now, without IO, trivial calculations like this can still look like threads are executing sequentially, which is why I just showed the first part of the output. On my computer, after this output thread with ID 10 finishes all at once, followed by 9, then 8. If you put in a wait or a yield, you can see it better:
MyThread.java
System.out.println("[ID " + this.getId() + "] " + i);
Thread.yield();
And the output:
[ID 8] 0
[ID 9] 1
[ID 10] 2
[ID 8] 3
[ID 9] 4
[ID 8] 6
[ID 10] 5
[ID 9] 7
Now you can see each thread executing, giving up control early, and the next executing.
For tracking changes to a folder where the folder was moved, I started using:
git rev-list --all --pretty=oneline -- "*/foo/subfoo/*"
This isn't perfect as it will grab other folders with the same name, but if it is unique, then it seems to work.
The difference is in the subsystem that each executable targets.
java.exe
targets the CONSOLE
subsystem.javaw.exe
targets the WINDOWS
subsystem.I use such alias in my .bashrc config
alias gpb='git push origin `git rev-parse --abbrev-ref HEAD`'
On the command $gpb
it takes the current branch name and pushes it to the origin.
Here are my other aliases:
alias gst='git status'
alias gbr='git branch'
alias gca='git commit -am'
alias gco='git checkout'
This is kind of hacky and probably not portable, only use it if you're looking for quick and dirty. If I just set the figure much bigger than the screen, it takes exactly the whole screen.
fig = figure(figsize=(80, 60))
In fact, in Ubuntu 16.04 with Qt4Agg, it maximizes the window (not full-screen) if it's bigger than the screen. (If you have two monitors, it just maximizes it on one of them).
If it is as your example of adding " World"
to the original string, then it can be:
#!/bin/bash
foo="Hello"
foo=$foo" World"
echo $foo
The output:
Hello World
First, you cannot have multiple elements with the same id. I know you said you can't control how the form is created, but...try to somehow remove all the ids from the radios, or make them unique.
To get the value of the selected radio button, select it by name with the :checked
filter.
var selectedVal = "";
var selected = $("input[type='radio'][name='s_2_1_6_0']:checked");
if (selected.length > 0) {
selectedVal = selected.val();
}
EDIT
So you have no control over the names. In that case I'd say put these radio buttons all inside a div, named, say, radioDiv
, then slightly modify your selector:
var selectedVal = "";
var selected = $("#radioDiv input[type='radio']:checked");
if (selected.length > 0) {
selectedVal = selected.val();
}
The output file needs to be opened in binary mode:
f = open('varstor.txt','w')
needs to be:
f = open('varstor.txt','wb')
I was able to achieve this by using set -x
in the main script (which makes the script print out every command that is executed) and writing a wrapper script which just shows the last line of output generated by set -x
.
This is the main script:
#!/bin/bash
set -x
echo some command here
echo last command
And this is the wrapper script:
#!/bin/sh
./test.sh 2>&1 | grep '^\+' | tail -n 1 | sed -e 's/^\+ //'
Running the wrapper script produces this as output:
echo last command
Simply type
MODE [width],[height]
Example:
MODE 14,1
That is the smallest size possible.
MODE 1000,1000
is the largest possible, although it probably won't even fit your screen. If you want to minimize it, type
start /min [yourbatchfile/cmd]
and of course, to maximaze,
start /max [yourbatchfile/cmd]
I am currently working on doing this from the same batch files so that you don't have to have two or start it with cmd. of course, there are shortcuts, but I'm gonna try to figure it out.
This is the problem
double a[] = null;
Since a
is null
, NullPointerException
will arise every time you use it until you initialize it. So this:
a[i] = var;
will fail.
A possible solution would be initialize it when declaring it:
double a[] = new double[PUT_A_LENGTH_HERE]; //seems like this constant should be 7
IMO more important than solving this exception, is the fact that you should learn to read the stacktrace and understand what it says, so you could detect the problems and solve it.
java.lang.NullPointerException
This exception means there's a variable with null
value being used. How to solve? Just make sure the variable is not null
before being used.
at twoten.TwoTenB.(TwoTenB.java:29)
This line has two parts:
<init>
method in class TwoTenB
declared in package twoten
. When you encounter an error message with SomeClassName.<init>
, means the error was thrown while creating a new instance of the class e.g. executing the constructor (in this case that seems to be the problem).a[i] = var;
.From this line, other lines will be similar to tell you where the error arose. So when reading this:
at javapractice.JavaPractice.main(JavaPractice.java:32)
It means that you were trying to instantiate a TwoTenB
object reference inside the main
method of your class JavaPractice
declared in javapractice
package.
Without doing a full revamp of the default routing (#/ViewName) environment, I was able to do a slight modification of Cody's tip and got it working great.
the controller
.controller('GeneralCtrl', ['$route', '$routeParams', '$location',
function($route, $routeParams, $location) {
...
this.goToView = function(viewName){
$location.url('/' + viewName);
}
}]
);
the view
...
<li ng-click="general.goToView('Home')">HOME</li>
...
What brought me to this solution was when I was attempting to integrate a Kendo Mobile UI widget into an angular environment I was losing the context of my controller and the behavior of the regular anchor tag was also being hijacked. I re-established my context from within the Kendo widget and needed to use a method to navigate...this worked.
Thanks for the previous posts!
mongodump: To dump all the records:
mongodump --db databasename
To limit the amount of data included in the database dump, you can specify --db and --collection as options to mongodump. For example:
mongodump --collection myCollection --db test
This operation creates a dump of the collection named myCollection from the database 'test' in a dump/ subdirectory of the current working directory. NOTE: mongodump overwrites output files if they exist in the backup data folder.
mongorestore: To restore all data to the original database:
1) mongorestore --verbose \path\dump
or restore to a new database:
2) mongorestore --db databasename --verbose \path\dump\<dumpfolder>
Note: Both requires mongod instances.
box-sizing: border-box;
width: 100%;
padding: 5px;
box-sizing: border box; makes it so that padding, margin and border are included in the width calculations.
Here is what works for me on Swift 3
let _ = (dict[key].map { $0 as? String } ?? "")
If you would like to populate another level deeper, here's what you need to do:
Airlines.findById(id)
.populate({
path: 'flights',
populate:[
{
path: 'planeType',
model: 'Plane'
},
{
path: 'destination',
model: 'Location',
populate: { // deeper
path: 'state',
model: 'State',
populate: { // even deeper
path: 'region',
model: 'Region'
}
}
}]
})
But I have declared that var in the top of the other files.
That's the problem. After all, this makes multiple declarations for the same name in the same (global) scope - which will throw an error with const
.
Instead, use var
, use only one declaration in your main file, or only assign to window.APP
exclusively.
Or use ES6 modules right away, and let your module bundler/loader deal with exposing them as expected.
That method can't return true
. That's the point of Long.MAX_VALUE
. It would be really confusing if its name were... false. Then it should be just called Long.SOME_FAIRLY_LARGE_VALUE
and have literally zero reasonable uses. Just use Android's isUserAGoat
, or you may roll your own function that always returns false
.
Note that a long
in memory takes a fixed number of bytes. From Oracle:
long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int.
As you may know from basic computer science or discrete math, there are 2^64 possible values for a long, since it is 64 bits. And as you know from discrete math or number theory or common sense, if there's only finitely many possibilities, one of them has to be the largest. That would be Long.MAX_VALUE
. So you are asking something similar to "is there an integer that's >0 and < 1?" Mathematically nonsensical.
If you actually need this for something for real then use BigInteger
class.
Create an initializer for it:
# config/initializers/time_formats.rb
Add something like this to it:
Time::DATE_FORMATS[:custom_datetime] = "%d.%m.%Y"
And then use it the following way:
post.updated_at.to_s(:custom_datetime)
?? Your have to restart rails server for this to work.
Check the documentation for more information: http://api.rubyonrails.org/v5.1/classes/DateTime.html#method-i-to_formatted_s
It's simple. Wrap the image and the "appear on hover" description in a div with the same dimensions of the image. Then, with some CSS, order the description to appear while hovering that div.
/* quick reset */_x000D_
* {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
border: 0;_x000D_
}_x000D_
_x000D_
/* relevant styles */_x000D_
.img__wrap {_x000D_
position: relative;_x000D_
height: 200px;_x000D_
width: 257px;_x000D_
}_x000D_
_x000D_
.img__description {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
background: rgba(29, 106, 154, 0.72);_x000D_
color: #fff;_x000D_
visibility: hidden;_x000D_
opacity: 0;_x000D_
_x000D_
/* transition effect. not necessary */_x000D_
transition: opacity .2s, visibility .2s;_x000D_
}_x000D_
_x000D_
.img__wrap:hover .img__description {_x000D_
visibility: visible;_x000D_
opacity: 1;_x000D_
}
_x000D_
<div class="img__wrap">_x000D_
<img class="img__img" src="http://placehold.it/257x200.jpg" />_x000D_
<p class="img__description">This image looks super neat.</p>_x000D_
</div>
_x000D_
A nice fiddle: https://jsfiddle.net/govdqd8y/
Don't forget that an input field must be visible first, thereafter you're able to focus it.
$("#elementid").show();
$("#elementid input[type=text]").focus();
document.querySelectorAll
(and its document.querySelector()
variant that returns the first found element) is much, much more powerful. You can easily:
document.querySelectorAll("*")
, effectively emulating non-standard document.all
property;document.querySelector("#your-id")
, effectively emulating document.getElementById()
function;document.querySelectorAll(".your-class")
, effectively emulating document.getElementsByClassName()
function;document.querySelectorAll("form")
instead of document.forms
, and document.querySelectorAll("a")
instead of document.links
;Unified querying API is the way to go. Even if document.all
would be in the standard, it's just inconvenient.
In order to see images, plots and anything displayed on windows on your remote machine you need to connect to it like this:
ssh -X user@hostname
That way you enable the access to the X server. The X server is a program in the X Window System that runs on local machines (i.e., the computers used directly by users) and handles all access to the graphics cards, display screens and input devices (typically a keyboard and mouse) on those computers.
More info here.
A struct (without a typedef) often needs to (or should) be with the keyword struct when used.
struct A; // forward declaration
void function( struct A *a ); // using the 'incomplete' type only as pointer
If you typedef your struct you can leave out the struct keyword.
typedef struct A A; // forward declaration *and* typedef
void function( A *a );
Note that it is legal to reuse the struct name
Try changing the forward declaration to this in your code:
typedef struct context context;
It might be more readable to do add a suffix to indicate struct name and type name:
typedef struct context_s context_t;
If you use the database information_schema, you can use this mysql code (the where part makes the query not show tables that have a null value for rows):
SELECT TABLE_NAME, TABLE_ROWS
FROM `TABLES`
WHERE `TABLE_ROWS` >=0
You can also use update_or_create just like get_or_create and here is the pattern I follow for update_or_create assuming a model Person with id (key), name, age, is_manager as attributes -
update_values = {"is_manager": False}
new_values = {"name": "Bob", "age": 25, "is_manager":True}
obj, created = Person.objects.update_or_create(identifier='id',
defaults=update_values)
if created:
obj.update(**new_values)
Just include #import "myProject-Swift.h" in .m or .h file
P.S You will not find "myProject-Swift.h" in file inspector it's hidden. But it is generated by app automatically.
Easiest way my friends, is to open the server explorer tab on visual studio 2019 (in my case), and then try to create the connection to the database. After creating a succesful connection just right click on it and go to propierties. There you will find a string connection field with the correct syntax!...This worked for me because I knew my server's name before hand....just couldn't figure out the correct syntax to run my ef scaffold...
(1) Your <script>
tag should be placed before the closing </body>
tag. Your JavaScript is trying to manipulate HTML elements that haven't been loaded into the DOM yet.
(2) Your assignment of HTML content looks jumbled.
(3) Be consistent with the case in your element ID, i.e. 'DIV2' vs 'Div2'
(4) User lower case for 'document' object (credit: ThatOtherPerson)
<body>
<div id="DIV1">
// Some content goes here.
</div>
<div id="DIV2">
</div>
<script type="text/javascript">
var MyDiv1 = document.getElementById('DIV1');
var MyDiv2 = document.getElementById('DIV2');
MyDiv2.innerHTML = MyDiv1.innerHTML;
</script>
</body>
Rails is deprecating the diff
method.
For a quick one-liner:
hash1.to_s == hash2.to_s
Look this:
List<Client> result = clients
.stream()
.filter(c ->
(users.stream().map(User::getName).collect(Collectors.toList())).contains(c.getName()))
.collect(Collectors.toList());
First off, it is perfectly feasible to use R successfully for years and not need to know the answer to this question. R handles the differences between the (usual) numerics and integers for you in the background.
> is.numeric(1)
[1] TRUE
> is.integer(1)
[1] FALSE
> is.numeric(1L)
[1] TRUE
> is.integer(1L)
[1] TRUE
(Putting capital 'L' after an integer forces it to be stored as an integer.)
As you can see "integer" is a subset of "numeric".
> .Machine$integer.max
[1] 2147483647
> .Machine$double.xmax
[1] 1.797693e+308
Integers only go to a little more than 2 billion, while the other numerics can be much bigger. They can be bigger because they are stored as double precision floating point numbers. This means that the number is stored in two pieces: the exponent (like 308 above, except in base 2 rather than base 10), and the "significand" (like 1.797693 above).
Note that 'is.integer' is not a test of whether you have a whole number, but a test of how the data are stored.
One thing to watch out for is that the colon operator, :
, will return integers if the start and end points are whole numbers. For example, 1:5
creates an integer
vector of numbers from 1 to 5. You don't need to append the letter L
.
> class(1:5)
[1] "integer"
Reference: https://www.quora.com/What-is-the-difference-between-numeric-and-integer-in-R
If you don't want execute assembly goal on package, you can use next command:
mvn package assembly:single
Here package is keyword.
The CASE
is just a "switch" to return a value - not to execute a whole code block.
You need to change your code to something like this:
SELECT
@selectoneCount = CASE @Temp
WHEN 1 THEN @selectoneCount + 1
WHEN 2 THEN @selectoneCount + 1
END
If @temp
is set to none of those values (1 or 2), then you'll get back a NULL
You can bind the mouseenter
and mouseleave
events and jQuery will emulate those where they are not native.
$("div.system_box").on('mouseenter', function(){
//enter
})
.on('mouseleave', function(){
//leave
});
note: do not use hover as that is deprecated
Open IIS manager, select Application Pools, select the application pool you are using, click on Advanced Settings in the right-hand menu. Under General, set "Enable 32-Bit Applications" to "True".
For version v2.2.2 and newer
In version v2.2.2 and up, name property no longer exists and it shouldn't be used to define the route. path should be used instead of name and no leading slash is needed on the path. In this case use path: '404'
instead of path: '/404'
:
{path: '404', component: NotFoundComponent},
{path: '**', redirectTo: '/404'}
For versions older than v2.2.2
you can use {path: '/*path', redirectTo: ['redirectPathName']}
:
{path: '/home/...', name: 'Home', component: HomeComponent}
{path: '/', redirectTo: ['Home']},
{path: '/user/...', name: 'User', component: UserComponent},
{path: '/404', name: 'NotFound', component: NotFoundComponent},
{path: '/*path', redirectTo: ['NotFound']}
if no path matches then redirect to NotFound
path
You can do this very easily with the [].filter
method:
var filterednames = names.filter(function(obj) {
return (obj.name === "Joe") && (obj.age < 30);
});
You will need to add a shim for browsers that don't support the [].filter
method: this MDN page gives such code.
- Can someone give a simple definition of what
Record
is?
A Record<K, T>
is an object type whose property keys are K
and whose property values are T
. That is, keyof Record<K, T>
is equivalent to K
, and Record<K, T>[K]
is (basically) equivalent to T
.
- Is
Record<K,T>
merely a way of saying "all properties on this object will have typeT
"? Probably not all objects, sinceK
has some purpose...
As you note, K
has a purpose... to limit the property keys to particular values. If you want to accept all possible string-valued keys, you could do something like Record<string, T>
, but the idiomatic way of doing that is to use an index signature like { [k: string]: T }
.
- Does the
K
generic forbid additional keys on the object that are notK
, or does it allow them and just indicate that their properties are not transformed toT
?
It doesn't exactly "forbid" additional keys: after all, a value is generally allowed to have properties not explicitly mentioned in its type... but it wouldn't recognize that such properties exist:
declare const x: Record<"a", string>;
x.b; // error, Property 'b' does not exist on type 'Record<"a", string>'
and it would treat them as excess properties which are sometimes rejected:
declare function acceptR(x: Record<"a", string>): void;
acceptR({a: "hey", b: "you"}); // error, Object literal may only specify known properties
and sometimes accepted:
const y = {a: "hey", b: "you"};
acceptR(y); // okay
With the given example:
type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>
Is it exactly the same as this?:
type ThreeStringProps = {prop1: string, prop2: string, prop3: string}
Yes!
Hope that helps. Good luck!
Here's another solution. This uses:
For the following input string:
"This is\, a value",Hello,4,-123,3.1415,'This is also\, possible',true
The code outputs:
[
"This is, a value",
"Hello",
4,
-123,
3.1415,
"This is also, possible",
true
]
Here's my implementation of parseCSVLine() in a runnable code snippet:
function parseCSVLine(text) {
return text.match( /\s*(\".*?\"|'.*?'|[^,]+)\s*(,|$)/g ).map( function (text) {
let m;
if (m = text.match(/^\s*\"(.*?)\"\s*,?$/)) return m[1]; // Double Quoted Text
if (m = text.match(/^\s*'(.*?)'\s*,?$/)) return m[1]; // Single Quoted Text
if (m = text.match(/^\s*(true|false)\s*,?$/)) return m[1] === "true"; // Boolean
if (m = text.match(/^\s*((?:\+|\-)?\d+)\s*,?$/)) return parseInt(m[1]); // Integer Number
if (m = text.match(/^\s*((?:\+|\-)?\d*\.\d*)\s*,?$/)) return parseFloat(m[1]); // Floating Number
if (m = text.match(/^\s*(.*?)\s*,?$/)) return m[1]; // Unquoted Text
return text;
} );
}
let data = `"This is\, a value",Hello,4,-123,3.1415,'This is also\, possible',true`;
let obj = parseCSVLine(data);
console.log( JSON.stringify( obj, undefined, 2 ) );
_x000D_
As suggested above I tried below one with fail.
store.proxy.reader.jsonData
But below one worked for me
store.proxy.reader.rawData
You could always do it recursively like so:
void freeList(struct node* currentNode)
{
if(currentNode->next) freeList(currentNode->next);
free(currentNode);
}
I'm the creator of Restangular.
You can take a look at this CRUD example to see how you can PUT/POST/GET elements without all that URL configuration and $resource configuration that you need to do. Besides it, you can then use nested resources without any configuration :).
Check out this plunkr example:
http://plnkr.co/edit/d6yDka?p=preview
You could also see the README and check the documentation here https://github.com/mgonto/restangular
If you need some feature that's not there, just create an issue. I usually add features asked within a week, as I also use this library for all my AngularJS projects :)
Hope it helps!
Here's the thing you should understand about tables... They're not a tree of nested independent elements. They're a single compound element. While the individual TDs behave more or less like CSS block elements, the intermediate stuff (anything between the TABLE and TD, including TRs and TBODYs) is indivisible and doesn't fall into either inline nor block. No random HTML elements are allowed in that other-dimensional space, and the size of such other-dimensional space isn't configurable at all through CSS. Only the HTML cellspacing
property can even get at it, and that property has no analog in CSS.
So, to solve your problem, I'd suggest either a DIV wrapper as another poster suggests, or if you absolutely must keep it contained in the table, you have this ugly junk:
<style>
.padded tr.first td { padding-top:10px; }
.padded tr.last td { padding-bottom:10px; }
.padded td.first { padding-left:10px; }
.padded td.last { padding-right:10px; }
</style>
<table class='padded'>
<tr class='first'>
<td class='first'>a</td><td>b</td><td class='last'>c</td>
</tr>
<tr>
<td class='first'>d</td><td>e</td><td class='last'>f</td>
</tr>
<tr class='last'>
<td class='first'>g</td><td>h</td><td class='last'>i</td>
</tr>
</table>
This is how you do if/else in Mustache (perfectly supported):
{{#repo}}
<b>{{name}}</b>
{{/repo}}
{{^repo}}
No repos :(
{{/repo}}
Or in your case:
{{#author}}
{{#avatar}}
<img src="{{avatar}}"/>
{{/avatar}}
{{^avatar}}
<img src="/images/default_avatar.png" height="75" width="75" />
{{/avatar}}
{{/author}}
Look for inverted sections in the docs: https://github.com/janl/mustache.js
I wrote a little 2,2kb library of saving image in localStorage JQueryImageCaching Usage:
<img data-src="path/to/image">
<script>
$('img').imageCaching();
</script>
Use the code below,
TableRow _tableRow =(TableRow)findViewById(R.id.tableRowMainBody);
tableRow.requestFocus();
that should work.
Here You Go:
HTML
<!DOCTYPE html>
<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
</style>
</head>
<body>
<input type='file' onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
</body>
</html>
Script:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
There are probably embedded tabs (CHAR(9)
) etc. as well. You can find out what other characters you need to replace (we have no idea what your goal is) with something like this:
DECLARE @var NVARCHAR(255), @i INT;
SET @i = 1;
SELECT @var = AccountType FROM dbo.Account
WHERE AccountNumber = 200
AND AccountType LIKE '%Daily%';
CREATE TABLE #x(i INT PRIMARY KEY, c NCHAR(1), a NCHAR(1));
WHILE @i <= LEN(@var)
BEGIN
INSERT #x
SELECT SUBSTRING(@var, @i, 1), ASCII(SUBSTRING(@var, @i, 1));
SET @i = @i + 1;
END
SELECT i,c,a FROM #x ORDER BY i;
You might also consider doing better cleansing of this data before it gets into your database. Cleaning it every time you need to search or display is not the best approach.
if we consider your real site configuration, than you need to run ReactJS in the head
<!-- Babel ECMAScript 6 injunction -->
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
and add attribute to your js file - type="text/babel" like
<script src="../js/r1HeadBabel.js" type="text/babel"></script>
then the below code example will work:
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
Since mysql_* are deprecated, so here is the solution using mysqli.
$mysqli = new mysqli('host', 'username', 'password', 'database');
if($mysqli->connect_errno>0)
{
die("Connection to MySQL-server failed!");
}
$resultArr = array();//to store results
//to execute query
$executingFetchQuery = $mysqli->query("SELECT `name` FROM customers WHERE 1");
if($executingFetchQuery)
{
while($arr = $executingFetchQuery->fetch_assoc())
{
$resultArr[] = $arr['name'];//storing values into an array
}
}
print_r($resultArr);//print the rows returned by query, containing specified columns
There is another way to do this using PDO
$db = new PDO('mysql:host=host_name;dbname=db_name', 'username', 'password'); //to establish a connection
//to fetch records
$fetchD = $db->prepare("SELECT `name` FROM customers WHERE 1");
$fetchD->execute();//executing the query
$resultArr = array();//to store results
while($row = $fetchD->fetch())
{
$resultArr[] = $row['name'];
}
print_r($resultArr);
Your problem might be here:
OR
(
SELECT m.ResourceNo FROM JobMember m
JOIN JobTask t ON t.JobTaskNo = m.JobTaskNo
WHERE t.TaskManagerNo = @UserResourceNo
OR
t.AlternateTaskManagerNo = @UserResourceNo
)
try changing to
OR r.ResourceNo IN
(
SELECT m.ResourceNo FROM JobMember m
JOIN JobTask t ON t.JobTaskNo = m.JobTaskNo
WHERE t.TaskManagerNo = @UserResourceNo
OR
t.AlternateTaskManagerNo = @UserResourceNo
)
Here are few pointers/suggestions for investigation
vote
method which creates a fresh HTTP connection.HttpClient
instance to post to the server. This way it wont create too many connections from the client side. HttpClient
needs to be shut and hence call httpclient.getConnectionManager().shutdown();
to release the resources used by the connections. If you're looking to verify whether an email address is valid, then VRFY will get you some of the way. I've found it's useful for validating intranet addresses (that is, email addresses for internal sites). However it's less useful for internet mail servers (see the caveats at the top of this page)
I have solved above problem Applying below steps
And after you made thses changes, do following changes in your web.config
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v12.0;AttachDbFilename=|DataDirectory|\aspnet-Real-Time-Commenting-20170927122714.mdf;Initial Catalog=aspnet-Real-Time-Commenting-20170927122714;Integrated Security=true" providerName="System.Data.SqlClient" />
Firstly, we just CAN'T make the variable final as its state may be changing during the run of the program and our decisions within the inner class override may depend on its current state.
Secondly, good object-oriented programming practice suggests using only variables/constants that are vital to the class definition as class members. This means that if the variable we are referencing within the anonymous inner class override is just a utility variable, then it should not be listed amongst the class members.
But – as of Java 8 – we have a third option, described here :
https://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html
Starting in Java SE 8, if you declare the local class in a method, it can access the method's parameters.
So now we can simply put the code containing the new inner class & its method override into a private method whose parameters include the variable we call from inside the override. This static method is then called after the btnInsert declaration statement :-
. . . .
. . . .
Statement statement = null;
. . . .
. . . .
Button btnInsert = new Button(shell, SWT.NONE);
addMouseListener(Button btnInsert, Statement statement); // Call new private method
. . .
. . .
. . .
private static void addMouseListener(Button btn, Statement st) // New private method giving access to statement
{
btn.addMouseListener(new MouseAdapter()
{
@Override
public void mouseDown(MouseEvent e)
{
String name = text.getText();
String from = text_1.getText();
String to = text_2.getText();
String price = text_3.getText();
String query = "INSERT INTO booking (name, fromst, tost,price) VALUES ('"+name+"', '"+from+"', '"+to+"', '"+price+"')";
try
{
st.executeUpdate(query);
}
catch (SQLException e1)
{
e1.printStackTrace(); // TODO Auto-generated catch block
}
}
});
return;
}
. . . .
. . . .
. . . .
for the new users on Mac os , find out .m2 folder and delete it, its on your /Users/.m2 directory.
you wont get to see .m2 folder in finder(File Explorer), for this user this command to Show Mac hidden files
$ defaults write com.apple.finder AppleShowAllFiles TRUE
after this press alt and click on finder-> relaunch, you can see /Users/.m2
to hide files again, simply use this $ defaults write com.apple.finder AppleShowAllFiles false
const
guarantees that a program does not change an object’s value. However, const
does not guarantee which type of initialization the object undergoes.
Consider:
const int mx = numeric_limits<int>::max(); // OK: runtime initialization
The function max()
merely returns a literal value. However, because the initializer is a function call, mx
undergoes runtime initialization. Therefore, you cannot use it as a constant expression:
int arr[mx]; // error: “constant expression required”
constexpr
is a new C++11 keyword that rids you of the need to create macros and hardcoded literals. It also guarantees, under certain conditions, that objects undergo static initialization. It controls the evaluation time of an expression. By enforcing compile-time evaluation of its expression, constexpr
lets you define true constant expressions that are crucial for time-critical applications, system programming, templates, and generally speaking, in any code that relies on compile-time constants.
A constant-expression function is a function declared constexpr
. Its body must be non-virtual and consist of a single return statement only, apart from typedefs and static asserts. Its arguments and return value must have literal types. It can be used with non-constant-expression arguments, but when that is done the result is not a constant expression.
A constant-expression function is meant to replace macros and hardcoded literals without sacrificing performance or type safety.
constexpr int max() { return INT_MAX; } // OK
constexpr long long_max() { return 2147483647; } // OK
constexpr bool get_val()
{
bool res = false;
return res;
} // error: body is not just a return statement
constexpr int square(int x)
{ return x * x; } // OK: compile-time evaluation only if x is a constant expression
const int res = square(5); // OK: compile-time evaluation of square(5)
int y = getval();
int n = square(y); // OK: runtime evaluation of square(y)
A constant-expression object is an object declared constexpr
. It must be initialized with a constant expression or an rvalue constructed by a constant-expression constructor with constant-expression arguments.
A constant-expression object behaves as if it was declared const
, except that it requires initialization before use and its initializer must be a constant expression. Consequently, a constant-expression object can always be used as part of another constant expression.
struct S
{
constexpr int two(); // constant-expression function
private:
static constexpr int sz; // constant-expression object
};
constexpr int S::sz = 256;
enum DataPacket
{
Small = S::two(), // error: S::two() called before it was defined
Big = 1024
};
constexpr int S::two() { return sz*2; }
constexpr S s;
int arr[s.two()]; // OK: s.two() called after its definition
A constant-expression constructor is a constructor declared constexpr
. It can have a member initialization list but its body must be empty, apart from typedefs and static asserts. Its arguments must have literal types.
A constant-expression constructor allows the compiler to initialize the object at compile-time, provided that the constructor’s arguments are all constant expressions.
struct complex
{
// constant-expression constructor
constexpr complex(double r, double i) : re(r), im(i) { } // OK: empty body
// constant-expression functions
constexpr double real() { return re; }
constexpr double imag() { return im; }
private:
double re;
double im;
};
constexpr complex COMP(0.0, 1.0); // creates a literal complex
double x = 1.0;
constexpr complex cx1(x, 0); // error: x is not a constant expression
const complex cx2(x, 1); // OK: runtime initialization
constexpr double xx = COMP.real(); // OK: compile-time initialization
constexpr double imaglval = COMP.imag(); // OK: compile-time initialization
complex cx3(2, 4.6); // OK: runtime initialization
Tips from the book Effective Modern C++ by Scott Meyers about constexpr
:
constexpr
objects are const and are initialized with values known during compilation;constexpr
functions produce compile-time results when called with arguments whose values are known during compilation;constexpr
objects and functions may be used in a wider range of contexts than non-constexpr
objects and functions;constexpr
is part of an object’s or function’s interface.Source: Using constexpr to Improve Security, Performance and Encapsulation in C++.
The best solution to your problem is to move your project folder to other directory with no non-ASCII characters and blank spaces.
For example ?:\Android\PROJECT-FOLDER
.
You can create the directory in C:\
using the name that you want.
On codeplex was released new XNA Extension for Visual Studio 2012/2013. You can download it from: https://msxna.codeplex.com/releases
I think this should do it.
let today = new Date();
let form_date=new Date('2019-10-23')
let difference=form_date>today ? form_date-today : today-form_date
let diff_days=Math.floor(difference/(1000*3600*24))
i have made a simple program, where you have 2 txt field you take input form the user and add them to make it simpler to understand please find the code below.
@IBOutlet weak var result: UILabel!
@IBOutlet weak var one: UITextField!
@IBOutlet weak var two: UITextField!
@IBAction func add(sender: AnyObject) {
let count = Int(one.text!)
let cal = Int(two.text!)
let sum = count! + cal!
result.text = "Sum is \(sum)"
}
hope this helps.
Static memory allocation. Memory allocated will be in stack.
int a[10];
Dynamic memory allocation. Memory allocated will be in heap.
int *a = malloc(sizeof(int) * 10);
and the latter should be freed since there is no Garbage Collector(GC) in C.
free(a);
There are various methods to get an input textbox value directly (without wrapping the input element inside a form element):
Method 1:
document.getElementById('textbox_id').value
to get the value of desired boxFor example,
document.getElementById("searchTxt").value;
Note: Method 2,3,4 and 6 returns a collection of elements, so use [whole_number] to get the desired occurrence. For the first element, use [0], for the second one use 1, and so on...
Method 2:
Use
document.getElementsByClassName('class_name')[whole_number].value
which returns a Live HTMLCollectionFor example,
document.getElementsByClassName("searchField")[0].value;
if this is the first textbox in your page.
Method 3:
Use
document.getElementsByTagName('tag_name')[whole_number].value
which also returns a live HTMLCollectionFor example,
document.getElementsByTagName("input")[0].value;
, if this is the first textbox in your page.
Method 4:
document.getElementsByName('name')[whole_number].value
which also >returns a live NodeListFor example,
document.getElementsByName("searchTxt")[0].value;
if this is the first textbox with name 'searchtext' in your page.
Method 5:
Use the powerful
document.querySelector('selector').value
which uses a CSS selector to select the elementFor example,
document.querySelector('#searchTxt').value;
selected by id
document.querySelector('.searchField').value;
selected by class
document.querySelector('input').value;
selected by tagname
document.querySelector('[name="searchTxt"]').value;
selected by name
Method 6:
document.querySelectorAll('selector')[whole_number].value
which also uses a CSS selector to select elements, but it returns all elements with that selector as a static Nodelist.For example,
document.querySelectorAll('#searchTxt')[0].value;
selected by id
document.querySelectorAll('.searchField')[0].value;
selected by class
document.querySelectorAll('input')[0].value;
selected by tagname
document.querySelectorAll('[name="searchTxt"]')[0].value;
selected by name
Support
Browser Method1 Method2 Method3 Method4 Method5/6
IE6 Y(Buggy) N Y Y(Buggy) N
IE7 Y(Buggy) N Y Y(Buggy) N
IE8 Y N Y Y(Buggy) Y
IE9 Y Y Y Y(Buggy) Y
IE10 Y Y Y Y Y
FF3.0 Y Y Y Y N IE=Internet Explorer
FF3.5/FF3.6 Y Y Y Y Y FF=Mozilla Firefox
FF4b1 Y Y Y Y Y GC=Google Chrome
GC4/GC5 Y Y Y Y Y Y=YES,N=NO
Safari4/Safari5 Y Y Y Y Y
Opera10.10/
Opera10.53/ Y Y Y Y(Buggy) Y
Opera10.60
Opera 12 Y Y Y Y Y
Useful links
Use Enum.Parse()
.
var content = (ContentEnum)Enum.Parse(typeof(ContentEnum), fileContentMessage);
It is possible.
When you use Return inside a procedure, the control is transferred to the calling program which calls the procedure. It is like an exit in loops.
It won't return any value.
For enabling Offline mode Android Studio Version Above 3.6, refer the following answer.
Test with [char]9, such as:
$Tab = [char]9
Write-Output "$Tab hello"
Output:
hello
Yes, it is possible.
try:
...
except FirstException:
handle_first_one()
except SecondException:
handle_second_one()
except (ThirdException, FourthException, FifthException) as e:
handle_either_of_3rd_4th_or_5th()
except Exception:
handle_all_other_exceptions()
See: http://docs.python.org/tutorial/errors.html
The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)
If you define operator<<
as a member function it will have a different decomposed syntax than if you used a non-member operator<<
. A non-member operator<<
is a binary operator, where a member operator<<
is a unary operator.
// Declarations
struct MyObj;
std::ostream& operator<<(std::ostream& os, const MyObj& myObj);
struct MyObj
{
// This is a member unary-operator, hence one argument
MyObj& operator<<(std::ostream& os) { os << *this; return *this; }
int value = 8;
};
// This is a non-member binary-operator, 2 arguments
std::ostream& operator<<(std::ostream& os, const MyObj& myObj)
{
return os << myObj.value;
}
So.... how do you really call them? Operators are odd in some ways, I'll challenge you to write the operator<<(...)
syntax in your head to make things make sense.
MyObj mo;
// Calling the unary operator
mo << std::cout;
// which decomposes to...
mo.operator<<(std::cout);
Or you could attempt to call the non-member binary operator:
MyObj mo;
// Calling the binary operator
std::cout << mo;
// which decomposes to...
operator<<(std::cout, mo);
You have no obligation to make these operators behave intuitively when you make them into member functions, you could define operator<<(int)
to left shift some member variable if you wanted to, understand that people may be a bit caught off guard, no matter how many comments you may write.
Almost lastly, there may be times where both decompositions for an operator call are valid, you may get into trouble here and we'll defer that conversation.
Lastly, note how odd it might be to write a unary member operator that is supposed to look like a binary operator (as you can make member operators virtual..... also attempting to not devolve and run down this path....)
struct MyObj
{
// Note that we now return the ostream
std::ostream& operator<<(std::ostream& os) { os << *this; return os; }
int value = 8;
};
This syntax will irritate many coders now....
MyObj mo;
mo << std::cout << "Words words words";
// this decomposes to...
mo.operator<<(std::cout) << "Words words words";
// ... or even further ...
operator<<(mo.operator<<(std::cout), "Words words words");
Note how the cout
is the second argument in the chain here.... odd right?
A way to use INSERT and WHERE is
INSERT INTO MYTABLE SELECT 953,'Hello',43 WHERE 0 in (SELECT count(*) FROM MYTABLE WHERE myID=953);
In this case ist like an exist-test. There is no exception if you run it two or more times...
Also see related printing forum topic: Printing from sublime
using redis-cli:
root@server:~# redis-cli
127.0.0.1:6379> CONFIG SET requirepass secret_password
OK
this will set password temporarily (until redis or server restart)
test password:
root@server:~# redis-cli
127.0.0.1:6379> AUTH secret_password
OK
Check out this site: http://osix.net/modules/article/?id=359
You can use backslash either way;
string str = "He said to me, \"Hello World\". How are you?";
It prints;
He said to me, "Hello World". How are you?
which is exactly same prints with;
string str = @"He said to me, ""Hello World"". How are you?";
Here is a DEMO
.
"
is still part of your string.
Check out Escape Sequences
and String literals
from MSDN.
You can use this function:
int arraySize(char array[])
{
int cont = 0;
for (int i = 0; array[i] != 0; i++)
cont++;
return cont;
}
After that you have to parse the results. Suppose results are in integers, then
int testint1 = Integer.parse(test1);
Similarly others should be parsed. Now the results should be checked for two higher marks in them, by using if statement After that take out the average.
Your code returns 0
if the execution of the commands passed is successful and non zero if it fails. The following program works on python2.7, haven checked 3 and versions above. Try this code.
>>> import commands
>>> ret = commands.getoutput("ps -p 2993 -o time --no-headers")
>>> print ret
After a few hours of messing around I eventually got something that works, partially answered in a similar issue here: How do I include a JavaScript file in another JavaScript file?
BUT there was an import that was screwing the rest of it up:
.vue
files<script>
var mylib = require('./mylib');
export default {
....
mylib
exports.myfunc = () => {....}
import
The actual issue in my case (which I didn't think was relevant!) was that mylib.js
was itself using other dependencies. The resulting error seems to have nothing to do with this, and there was no transpiling error from webpack
but anyway I had:
import models from './model/models'
import axios from 'axios'
This works so long as I'm not using mylib
in a .vue
component. However as soon as I use mylib
there, the error described in this issue arises.
I changed to:
let models = require('./model/models');
let axios = require('axios');
And all works as expected.
Need to make sure once switched into a frame, need to switch back to default content for accessing webelements in another frames. As Webdriver tend to find the new frame inside the current frame.
driver.switchTo().defaultContent()
it is because of using web address, You can not use http to write data. don't use : http:// or https:// in your location for upload files or save data or somting like that. instead of of using $_SERVER["HTTP_REFERER"] use $_SERVER["DOCUMENT_ROOT"]. for example :
wrong :
move_uploaded_file($_FILES["File"]["tmp_name"],$_SERVER["HTTP_REFERER"].'/uploads/images/1.jpg')
correct:
move_uploaded_file($_FILES["File"]["tmp_name"],$_SERVER["DOCUMENT_ROOT"].'/uploads/images/1.jpg')
On Mac OS X
Remove these directories:
~/Library/Application Support/AndroidStudioBeta
~/Library/Caches/AndroidStudioBeta
~/Library/Logs/AndroidStudioBeta
~/Library/Preferences/AndroidStudioBeta
if working in MS windows, you can use Anaconda navigator. click on the environment, in the drop-down box, it's "installed" by default. You can select "updatable" and start from there
In MySQL
select convert( if( listPrice REGEXP '^[0-9]+$', listPrice, '0' ), DECIMAL(15, 3) ) from MyProduct WHERE 1
It can be done using SQL Server Import and Export Wizard. But if you're familiar with SSIS and don't want to run the SQL Server Import and Export Wizard, create an SSIS package that uses the Excel Source and the SQL Server Destination in the data flow.
Try to add title
and alt
properties to your image.... Gmail and some others blocks images without some attributes.. and it is also a logic to include your email to be read as spam.
--ORACLE SQL EXAMPLE
SELECT
SYSDATE
,TO_DATE(SUBSTR(LAST_DAY(ADD_MONTHS(SYSDATE, -1)),1,10),'YYYY-MM-DD')
FROM DUAL
if(jQuery('#frmTest input[type=checkbox]:checked').length) { … }
Here's something a guy on Wordpress forum showed us. Add the following to your functions.php file. (remember to create a backup of your functions.php first)
add_filter( 'wp_image_editors', 'change_graphic_lib' );
function change_graphic_lib($array) {
return array( 'WP_Image_Editor_GD', 'WP_Image_Editor_Imagick' );
}
...it was that simple.
To convert this bytesarray directly to json, you could first convert the bytesarray to a string with decode(), utf-8 is standard. Change the quotation markers.. The last step is to remove the " from the dumped string, to change the json object from string to list.
dumps(s.decode()).replace("'", '"')[1:-1]
var logFile = File.ReadAllLines(LOG_PATH);
var logList = new List<string>(logFile);
Since logFile
is an array, you can pass it to the List<T>
constructor. This eliminates unnecessary overhead when iterating over the array, or using other IO classes.
Actual constructor implementation:
public List(IEnumerable<T> collection)
{
...
ICollection<T> c = collection as ICollection<T>;
if( c != null) {
int count = c.Count;
if (count == 0)
{
_items = _emptyArray;
}
else {
_items = new T[count];
c.CopyTo(_items, 0);
_size = count;
}
}
...
}
It is not quite clear what function you are talking about and if you need 2 separate branches or one. Assuming one:
Change your first line to
$slide = '';
if (isset($_GET["id"]))
{
$slide = $_GET["id"];
}
Anything that is not stored on an EBS volume that is mounted to the instance will be lost.
For example, if you mount your EBS volume at /mystuff
, then anything not in /mystuff
will be lost. If you don't mount an ebs volume and save stuff on it, then I believe everything will be lost.
You can create an AMI from your current machine state, which will contain everything in your ephemeral storage. Then, when you launch a new instance based on that AMI it will contain everything as it is now.
Update: to clarify based on comments by mattgmg1990 and glenn bech:
Note that there is a difference between "stop" and "terminate". If you "stop" an instance that is backed by EBS then the information on the root volume will still be in the same state when you "start" the machine again. According to the documentation, "By default, the root device volume and the other Amazon EBS volumes attached when you launch an Amazon EBS-backed instance are automatically deleted when the instance terminates" but you can modify that via configuration.
In our particular case, we use Stash as our remote Git repository. We tried all the previous answers and nothing was working. We ended up having to do the following:
git branch –D branch-name (delete from local)
git push origin :branch-name (delete from remote)
Then when users went to pull changes, they needed to do the following:
git fetch -p
You can't do that because you can not know the salt at a precise time. Below, a code who works in theory (not tested for the syntaxe)
<?php
$password1 = $_POST['password'];
$salt = 'hello_1m_@_SaLT';
$hashed = hash('sha256', $password1 . $salt);
?>
When you insert :
$qry="INSERT INTO member VALUES('$username', '$hashed')";
And for retrieving user :
$qry="SELECT * FROM member WHERE username='$username' AND password='$hashed'";
Here is an example of Jon Adams suggestion above in order to fix a div (toolbar) to the right hand side of your page element using jQuery. The idea is to find the distance from the right hand side of the viewport to the right hand side of the page element and to keep the right hand side of the toolbar there!
<div id="pageElement"></div>
<div id="toolbar"></div>
#toolbar {
position: fixed;
}
....
function placeOnRightHandEdgeOfElement(toolbar, pageElement) {
$(toolbar).css("right", $(window).scrollLeft() + $(window).width()
- $(pageElement).offset().left
- parseInt($(pageElement).css("borderLeftWidth"),10)
- $(pageElement).width() + "px");
}
$(document).ready(function() {
$(window).resize(function() {
placeOnRightHandEdgeOfElement("#toolbar", "#pageElement");
});
$(window).scroll(function () {
placeOnRightHandEdgeOfElement("#toolbar", "#pageElement");
});
$("#toolbar").resize();
});
When I needed to do this, I use
python -c "$(echo -e "import sys\nsys.stdout.write('Hello World!\\\n')")"
Note the triple backslash for the newline in the sys.stdout.write statement.
I have some experience at recovering from eclipse when it becomes unstartable for whatever reason, could these blog entries help you?
link (archived)
also search for "cannot start eclipse" (I am a new user, I can only post a single hyperlink, so I have to just ask that you search for the second :( sorry)
perhaps those allow you to recover your workspace as well, I hope it helps.
PostgreSql is very advanced when related to logging techniques
Logs are stored in Installationfolder/data/pg_log folder
. While log settings are placed in postgresql.conf
file.
Log format is usually set as stderr
. But CSV log format is recommended. In order to enable CSV format change in
log_destination = 'stderr,csvlog'
logging_collector = on
In order to log all queries, very usefull for new installations, set min. execution time for a query
log_min_duration_statement = 0
In order to view active Queries on your database, use
SELECT * FROM pg_stat_activity
To log specific queries set query type
log_statement = 'all' # none, ddl, mod, all
For more information on Logging queries see PostgreSql Log.
HttpContext.Response.AddHeader("content-disposition","attachment; filename=form.pdf");
if the filename is generating dynamically then how to define filename here, it is generating through guid here.
This should do the trick.
<activity ... android:launchMode="singleTop" />
When you create an intent to start the app use:
Intent intent= new Intent(context, YourActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
This is that should be needed.
To set image cource in imageview you can use any of the following ways. First confirm your image is present in which format.
If you have image in the form of bitmap then use
imageview.setImageBitmap(bm);
If you have image in the form of drawable then use
imageview.setImageDrawable(drawable);
If you have image in your resource example if image is present in drawable folder then use
imageview.setImageResource(R.drawable.image);
If you have path of image then use
imageview.setImageURI(Uri.parse("pathofimage"));
When uploading .mp4 file into Perl script, using CGI.pm I see it as video/mp when printing out Content-type
for the uploaded file.
I hope it will help someone.
I needed to do (the solution in the accepted answer):
git fetch origin
git reset --hard origin/master
Followed by:
git clean -f
To see what files will be removed (without actually removing them):
git clean -n -f
Here is a LIVE DEMO of atob()
and btoa()
JS built in functions:
<!DOCTYPE html>
<html>
<head>
<style>
textarea{
width:30%;
height:100px;
}
</style>
<script>
// encode string to base64
function encode()
{
var txt = document.getElementById("txt1").value;
var result = btoa(txt);
document.getElementById("txt2").value = result;
}
// decode base64 back to original string
function decode()
{
var txt = document.getElementById("txt3").value;
var result = atob(txt);
document.getElementById("txt4").value = result;
}
</script>
</head>
<body>
<div>
<textarea id="txt1">Some text to decode
</textarea>
</div>
<div>
<input type="button" id="btnencode" value="Encode" onClick="encode()"/>
</div>
<div>
<textarea id="txt2">
</textarea>
</div>
<br/>
<div>
<textarea id="txt3">U29tZSB0ZXh0IHRvIGRlY29kZQ==
</textarea>
</div>
<div>
<input type="button" id="btndecode" value="Decode" onClick="decode()"/>
</div>
<div>
<textarea id="txt4">
</textarea>
</div>
</body>
</html>
using System.IO;
string textToSplit;
if (textToSplit != null)
{
List<string> lines = new List<string>();
using (StringReader reader = new StringReader(textToSplit))
{
for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
{
lines.Add(line);
}
}
}
There is obviously another process listening on the port. You might find out that process by using the following command:
$ lsof -i :8000
or change your tornado app's port. tornado's error info not Explicitly on this.
Since IntelliJ 2016, the location is File | Settings | Build, Execution, Deployment | Compiler | Build process heap size.
You seem to be asking, "If I can rewrite a RIGHT OUTER JOIN
using LEFT OUTER JOIN
syntax then why have a RIGHT OUTER JOIN
syntax at all?" I think the answer to this question is, because the designers of the language didn't want to place such a restriction on users (and I think they would have been criticized if they did), which would force users to change the order of tables in the FROM
clause in some circumstances when merely changing the join type.
This answer is not the direct answer for the question. But it should help you figure out which solution fits best for your problem.
When analysing the problem you should activate the debug option -vv
Then rsync will output which files are included or excluded by which pattern:
building file list ...
[sender] hiding file FILE1 because of pattern FILE1*
[sender] showing file FILE2 because of pattern *
$Push_Pop = $ErrorActionPreference #Suppresses errors
$ErrorActionPreference = “SilentlyContinue” #Suppresses errors
#Script
#gc .\output\*.csv -ReadCount 5 | %{$_;throw "pipeline end!"} # head
#gc .\output\*.csv | %{$num=0;}{$num++;"$num $_"} # cat -n
gc .\output\*.csv | %{$num=0;}{$num++; if($num -gt 2 -and $num -lt 7){"$num $_"}} # sed
#End Script
$ErrorActionPreference = $Push_Pop #Suppresses errors
You don't get all the errors with the pushpop code BTW, your code only works with the "sed" option. All the rest ignores anything but gc and path.
gzip > stdin.gz
perhaps? Otherwise, you need to flesh out your question.
Here is an example that I used:
def volume(self):
return round(pi * self.radius ** 2 * self.height, 2)
def surface_area(self):
return round((2 * pi * self.radius * self.height) + (2 * pi * self.radius ** 2), 2)
log4j.logger.org.hibernate=INFO, hb
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE
log4j.logger.org.hibernate.hql.ast.AST=info
log4j.logger.org.hibernate.tool.hbm2ddl=warn
log4j.logger.org.hibernate.hql=debug
log4j.logger.org.hibernate.cache=info
log4j.logger.org.hibernate.jdbc=debug
log4j.appender.hb=org.apache.log4j.ConsoleAppender
log4j.appender.hb.layout=org.apache.log4j.PatternLayout
log4j.appender.hb.layout.ConversionPattern=HibernateLog --> %d{HH:mm:ss} %-5p %c - %m%n
log4j.appender.hb.Threshold=TRACE
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>
Some frameworks use persistence.xml
:
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.use_sql_comments" value="true"/>
The colorbar has to have its own axes. However, you can create an axes that overlaps with the previous one. Then use the cax
kwarg to tell fig.colorbar
to use the new axes.
For example:
import numpy as np
import matplotlib.pyplot as plt
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots()
cax = fig.add_axes([0.27, 0.8, 0.5, 0.05])
im = ax.imshow(data, cmap='gist_earth')
fig.colorbar(im, cax=cax, orientation='horizontal')
plt.show()
You want to use the atof() function.
use word boundaries \b,
The following (using four escapes) works in my environment: Mac, safari Version 10.0.3 (12602.4.8)
var myReg = new RegExp(‘\\\\b’+ variable + ‘\\\\b’, ‘g’)
Some notes:
IMO, I would recommend Hibernate.
There have been some comments / questions about what you should do if you need to use Hibernate-specific features. There are many ways to look at this, but my advice would be:
If you are not worried by the prospect of vendor tie-in, then make your choice between Hibernate, and other JPA and JDO implementations including the various vendor specific extensions in your decision making.
If you are worried by the prospect of vendor tie-in, and you can't use JPA without resorting to vendor specific extensions, then don't use JPA. (Ditto for JDO).
In reality, you will probably need to trade-off how much you are worried by vendor tie-in versus how much you need those vendor specific extensions.
And there are other factors too, like how well you / your staff know the respective technologies, how much the products will cost in licensing, and whose story you believe about what is going to happen in the future for JDO and JPA.
When you use a Range
object, you cannot simply use the following syntax:
Dim myRange as Range
myRange = Range("A1")
You must use the set
keyword to assign Range objects:
Function getData(currentWorksheet As Worksheet, dataStartRow As Integer, dataEndRow As Integer, DataStartCol As Integer, dataEndCol As Integer)
Dim dataTable As Range
Set dataTable = currentWorksheet.Range(currentWorksheet.Cells(dataStartRow, DataStartCol), currentWorksheet.Cells(dataEndRow, dataEndCol))
Set getData = dataTable
End Function
Sub main()
Dim test As Range
Set test = getData(ActiveSheet, 1, 3, 2, 5)
test.select
End Sub
Note that every time a range is declared I use the Set
keyword.
You can also allow your getData
function to return a Range
object instead of a Variant
although this is unrelated to the problem you are having.
Is this the expected behavior?
the json_encode()
only works with UTF-8 encoded data.
maybe you can get an answer to convert it here: cyrillic-characters-in-phps-json-encode
It's better to use an Iterator when you want to remove element from a list
because the source code of remove is
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null;
so ,if you remove an element from the list, the list will be restructure ,the other element's index will be changed, this can result something that you want to happened.
I once had this problem. I realized that while moving a class, I had overwritten the .mm
file with .h
file on the destination folder.
Fixing that issue fixed the error.
Foreign key and check constraints have the concept of being trusted or untrusted, as well as being enabled and disabled. See the MSDN page for ALTER TABLE
for full details.
WITH CHECK
is the default for adding new foreign key and check constraints, WITH NOCHECK
is the default for re-enabling disabled foreign key and check constraints. It's important to be aware of the difference.
Having said that, any apparently redundant statements generated by utilities are simply there for safety and/or ease of coding. Don't worry about them.
Here is the answer in Razor syntax
<table border="1" cellpadding="5">
<thead>
<tr>
@foreach (System.Data.DataColumn col in Model.Columns)
{
<th>@col.Caption</th>
}
</tr>
</thead>
<tbody>
@foreach(System.Data.DataRow row in Model.Rows)
{
<tr>
@foreach (var cell in row.ItemArray)
{
<td>@cell.ToString()</td>
}
</tr>
}
</tbody>
</table>
I know this question already have been answer but I have made some update to the GD function :
### COST FUNCTION
def cost(theta,X,y):
### Evaluate half MSE (Mean square error)
m = len(y)
error = np.dot(X,theta) - y
J = np.sum(error ** 2)/(2*m)
return J
cost(theta,X,y)
def GD(X,y,theta,alpha):
cost_histo = [0]
theta_histo = [0]
# an arbitrary gradient, to pass the initial while() check
delta = [np.repeat(1,len(X))]
# Initial theta
old_cost = cost(theta,X,y)
while (np.max(np.abs(delta)) > 1e-6):
error = np.dot(X,theta) - y
delta = np.dot(np.transpose(X),error)/len(y)
trial_theta = theta - alpha * delta
trial_cost = cost(trial_theta,X,y)
while (trial_cost >= old_cost):
trial_theta = (theta +trial_theta)/2
trial_cost = cost(trial_theta,X,y)
cost_histo = cost_histo + trial_cost
theta_histo = theta_histo + trial_theta
old_cost = trial_cost
theta = trial_theta
Intercept = theta[0]
Slope = theta[1]
return [Intercept,Slope]
res = GD(X,y,theta,alpha)
This function reduce the alpha over the iteration making the function too converge faster see Estimating linear regression with Gradient Descent (Steepest Descent) for an example in R. I apply the same logic but in Python.
If you prefer, you can set these options via the commmand line (instead of editing the config file) like so:
$ git config branch.master.remote origin
$ git config branch.master.merge refs/heads/master
Or, if you're like me, and want this to be the default across all of your projects, including those you might work on in the future, then add it as a global config setting:
$ git config --global branch.master.remote origin
$ git config --global branch.master.merge refs/heads/master
>>> x = "2342.34"
>>> float(x)
2342.3400000000001
There you go. Use float (which behaves like and has the same precision as a C,C++, or Java double).
sqlitejdbc code can be downloaded using git from https://github.com/crawshaw/sqlitejdbc.
# git clone https://github.com/crawshaw/sqlitejdbc.git sqlitejdbc
...
# cd sqlitejdbc
# make
Note: Makefile requires curl binary to download sqlite libraries/deps.
No need to find
. If you are just looking for a pattern within a specific directory, this should suffice:
grep -hn FOO /your/path/*.bar
Where -h
is the parameter to hide the filename, as from man grep
:
-h, --no-filename
Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search.
Note that you were using
-H, --with-filename
Print the file name for each match. This is the default when there is more than one file to search.
$a="some text =keep this,but not this"
$a.split('=')[1].split(',')[0]
returns
keep this
// wrap it in jQuery, now it's a collection
var $elements = $(someHTML);
// append to the DOM
$("#myDiv").append($elements);
// do stuff, using the initial reference
$elements.effects("highlight", {}, 2000);
You should see Sublime Column Selection:
Using the Mouse
Different mouse buttons are used on each platform:
OS X
- Left Mouse Button + ?
OR: Middle Mouse Button
Add to selection: ?
- Subtract from selection: ?+?
Windows
- Right Mouse Button + Shift
OR: Middle Mouse Button
Add to selection: Ctrl
- Subtract from selection: Alt
Linux
Right Mouse Button + Shift
Add to selection: Ctrl
- Subtract from selection: Alt
Using the Keyboard
OS X
- Ctrl + Shift + ?
- Ctrl + Shift + ?
Windows
- Ctrl + Alt + ?
- Ctrl + Alt + ?
Linux
- Ctrl + Alt + ?
- Ctrl + Alt + ?
The accepted answer is faulty, since the contents from the initial user folder are not moved using it. I am going to add another answer to correct it:
sudo usermod -d /newhome/username -m username
You don't need to create the folder with username and this will also move your files from the initial user folder to /newhome/username folder.
Just a notice for a sharing hosting server or added on domains =
For your settings to work you must have a different save session dir for added domain by using php_value session.save_path folderA/sessionsA
.
So create a folder to your root server, not into the public_html
and not to be publicity accessed from outside. For my cpanel/server worked fine the folder permissions 0700
. Give a try...
# Session timeout, 2628000 sec = 1 month, 604800 = 1 week, 57600 = 16 hours, 86400 = 1 day
ini_set('session.save_path', '/home/server/.folderA_sessionsA');
ini_set('session.gc_maxlifetime', 57600);
ini_set('session.cookie_lifetime', 57600);
# session.cache_expire is in minutes unlike the other settings above
ini_set('session.cache_expire', 960);
ini_set('session.name', 'MyDomainA');
before session_start();
or put this in your .htaccess
file.
php_value session.save_path /home/server/.folderA_sessionsA
php_value session.gc_maxlifetime 57600
php_value session.cookie_lifetime 57600
php_value session.cache_expire 57600
php_value session.name MyDomainA
After many researching and testing this worked fine for shared cpanel/php7 server. Many thanks to: NoiS
Instead of an ObservableCollection or TrulyObservableCollection, consider using a BindingList and calling the ResetBindings method.
For example:
private BindingList<TfsFile> _tfsFiles;
public BindingList<TfsFile> TfsFiles
{
get { return _tfsFiles; }
set
{
_tfsFiles = value;
NotifyPropertyChanged();
}
}
Given an event, such as a click your code would look like this:
foreach (var file in TfsFiles)
{
SelectedFile = file;
file.Name = "Different Text";
TfsFiles.ResetBindings();
}
My model looked like this:
namespace Models
{
public class TfsFile
{
public string ImagePath { get; set; }
public string FullPath { get; set; }
public string Name { get; set; }
public string Text { get; set; }
}
}
You don't need jQuery when it is so simple to do this using pure JavaScript. Here are two options:
Method 1 - Retrieve the exact value of the href
attribute:
Select the element and then use the .getAttribute()
method.
This method does not return the full URL, instead it retrieves the exact value of the href
attribute.
var anchor = document.querySelector('a'),_x000D_
url = anchor.getAttribute('href');_x000D_
_x000D_
alert(url);
_x000D_
<a href="/relative/path.html"></a>
_x000D_
Method 2 - Retrieve the full URL path:
Select the element and then simply access the href
property.
This method returns the full URL path.
In this case: http://stacksnippets.net/relative/path.html
.
var anchor = document.querySelector('a'),_x000D_
url = anchor.href;_x000D_
_x000D_
alert(url);
_x000D_
<a href="/relative/path.html"></a>
_x000D_
As your title implies, you want to get the href
value on click. Simply select an element, add a click event listener and then return the href
value using either of the aforementioned methods.
var anchor = document.querySelector('a'),_x000D_
button = document.getElementById('getURL'),_x000D_
url = anchor.href;_x000D_
_x000D_
button.addEventListener('click', function (e) {_x000D_
alert(url);_x000D_
});
_x000D_
<button id="getURL">Click me!</button>_x000D_
<a href="/relative/path.html"></a>
_x000D_
If you are using hand inputted data, you can enter your data as mm:ss,0
or mm:ss.0
depending on your language/region selection instead of 00:mm:ss
.
You need to specify your cell format as [m]:ss
if you like to see all minutes seconds format instead of hours minutes seconds format.
For people looking for getting text that is both centered and justified, the following should work:
<div class="center-justified">...lots and lots of text...</div>
With the following CSS rule (adjust the width
property as needed):
.center-justified {
text-align: justify;
margin: 0 auto;
width: 30em;
}
Here's the live demo.
text-align: justify;
makes sure the text fills the full width of the div
it is enclosed in.margin: 0 auto;
is actually a shorthand for four rules:
margin-top
and margin-bottom
rules.
The whole thing therefore means margin-top: 0; margin-bottom: 0
, i.e. no margins above or below the div
.margin-left
and margin-right
rules.
So this rule results in margin-left: auto; margin-right: auto
.
This is the clever bit: it tells the browser to take whatever space is available on the sides and distribute it evenly on left and right.
The result is centered text.width: 30em;
, which limits the width of the div
.
Only when the width is restricted is there some whitespace left over for margin: auto
to distribute.
Without this rule the div
would take up all available horizontal space, and you'd lose the centering effect.For UTF-16, the character needs four bytes (two code units) if it starts with 0xD800 or greater; such a character is called a "surrogate pair." More specifically, a surrogate pair has the form:
[0xD800 - 0xDBFF] [0xDC00 - 0xDFF]
where [...] indicates a two-byte code unit with the given range. Anything <= 0xD7FF is one code unit (two bytes). Anything >= 0xE000 is invalid (except BOM markers, arguably).
See http://unicodebook.readthedocs.io/unicode_encodings.html, section 7.5.
Create an empty activity and add two lines in onCreate
.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// full screen activity
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
}
...
}
Also you can add #include<vector>
in the header. When two of the above solutions don't work.
301 redirects are cached indefinitely (at least by some browsers).
This means, if you set up a 301, visit that page, you not only get redirected, but that redirection gets cached.
When you visit that page again, your Browser* doesn't even bother to request that URL, it just goes to the cached redirection target.
The only way to undo a 301 for a visitor with that redirection in Cache, is re-redirecting back to the original URL**. In that case, the Browser will notice the loop, and finally really request the entered URL.
Obviously, that's not an option if you decided to 301 to facebook or any other resource you're not fully under control.
Unfortunately, many Hosting Providers offer a feature in their Admin Interface simply called "Redirection", which does a 301 redirect. If you're using this to temporarily redirect your domain to facebook as a coming soon page, you're basically screwed.
*at least Chrome and Firefox, according to How long do browsers cache HTTP 301s?. Just tried it with Chrome 45. Edit: Safari 7.0.6 on Mac also caches, a browser restart didn't help (Link says that on Safari 5 on Windows it does help.)
**I tried javascript window.location = ''
, because it would be the solution which could be applied in most cases - it doesn't work. It results in an undetected infinite Loop. However, php header('Location: new.url')
does break the loop
Bottom Line: only use 301s if you're absolutely sure you're never going to use that URL again. Usually never on the root dir (example.com/)
Using an enhanced for would be even nicer:
int sum = 0;
for (int d : data) sum += d;
Another thing that will probably give you a big surprise is the wrong result that you will obtain from
double average = sum / data.length;
Reason: on the right-hand side you have integer division and Java will not automatically promote it to floating-point division. It will calculate the integer quotient of sum/data.length
and only then promote that integer to a double
. A solution would be
double average = 1.0d * sum / data.length;
This will force the dividend into a double
, which will automatically propagate to the divisor.
Guava has a method Ints.asList()
for creating a List<Integer>
backed by an int[]
array. You can use this with Collections.sort to apply the Comparator to the underlying array.
List<Integer> integersList = Ints.asList(arr);
Collections.sort(integersList, Collections.reverseOrder());
Note that the latter is a live list backed by the actual array, so it should be pretty efficient.
The return type of Html.RenderAction
is void
that means it directly renders the responses in View where the return type of Html.Action
is MvcHtmlString
You can catch its render view in controller and modify it by using following method
protected string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action");
ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
This will return the Html string of the View.
This is also applicable to Html.Partial
and Html.RenderPartial
To increase the phpMyAdmin
Session Timeout, open config.inc.php
in the root phpMyAdmin
directory and add this setting (anywhere).
$cfg['LoginCookieValidity'] = <your_new_timeout>;
Where <your_new_timeout>
is some number larger than 1800.
Note:
Always keep on mind that a short cookie lifetime is all well and good for the development server. So do not do this on your production server.
>>> value=42
>>> print "Value is %s"%('"'+str(value)+'"')
Value is "42"
NOTE this answer is now incorrect. I may get back to it at a later time.
As others have pointed out, you can't set the height of a table unless you set its display to block
, but then you get a scrolling header. So what you're looking for is to set the height
and display:block
on the tbody
alone:
<table style="border: 1px solid red">
<thead>
<tr>
<td>Header stays put, no scrolling</td>
</tr>
</thead>
<tbody style="display: block; border: 1px solid green; height: 30px; overflow-y: scroll">
<tr>
<td>cell 1/1</td>
<td>cell 1/2</td>
</tr>
<tr>
<td>cell 2/1</td>
<td>cell 2/2</td>
</tr>
<tr>
<td>cell 3/1</td>
<td>cell 3/2</td>
</tr>
</tbody>
</table>
Here's the fiddle.
You need to do it directly on a server. But a better way is using PHP. I have heard that PHP has a special code that can send e-mail directly without opening the mail client.
imports
are used to import supporting modules like FormsModule, RouterModule, CommonModule, or any other custom-made feature module.
declarations
are used to declare components, directives, pipes that belong to the current module. Everyone inside declarations knows each other. For example, if we have a component, say UsernameComponent, which displays a list of the usernames and we also have a pipe, say toupperPipe, which transforms a string to an uppercase letter string. Now If we want to show usernames in uppercase letters in our UsernameComponent then we can use the toupperPipe which we had created before but the question is how UsernameComponent knows that the toupperPipe exists and how it can access and use that. Here come the declarations, we can declare UsernameComponent and toupperPipe.
Providers
are used for injecting the services required by components, directives, pipes in the module.
we can do it with a single line of code.
user1 = pd.read_csv('dataset/1.csv', names=['TIME', 'X', 'Y', 'Z'], header=None)
You should use monit, a standard unix tool that can monitor different things on the system and react accordingly.
From the docs: http://mmonit.com/monit/documentation/monit.html#pid_testing
check process checkqueue.py with pidfile /var/run/checkqueue.pid if changed pid then exec "checkqueue_restart.sh"
You can also configure monit to email you when it does do a restart.
how remote is that url ? is it from the same domain ? the code looks okay
try this
$.ajaxSetup({async:false});
$.get(remote_url, function(data) { remote = data; });
// or
remote = $.get(remote_url).responseText;
$('.IsBestAnswer').removeClass('IsBestAnswer').addClass('bestanswer');
Your code has two problems:
.IsBestAnswe
does not match what you thoughtaddClass()
, not addclass()
.Also, I'm not sure whether you want to replace the class or add it. The above will replace, but remove the .removeClass('IsBestAnswer')
part to add only:
$('.IsBestAnswer').addClass('bestanswer');
You should decide whether to use camelCase or all-lowercase in your CSS classes too (e.g. bestAnswer
vs. bestanswer
).
HTML
? ✕
? ✓
? ✖
? ✔
? ✗
? ✘
× ×
×
CSS
If you want to use the above characters from CSS (like i.e: in an :before
or :after
pseudo) simply use the escaped \
Unicode HEX value, like for example:
[class^="ico-"], [class*=" ico-"]{
font: normal 1em/1 Arial, sans-serif;
display: inline-block;
}
.ico-times:before{ content: "\2716"; }
.ico-check:before{ content: "\2714"; }
_x000D_
<i class="ico-times" role="img" aria-label="Cancel"></i>
<i class="ico-check" role="img" aria-label="Accept"></i>
_x000D_
✕
HTML'\2715'
CSS like i.e: .clear:before { content: '\2715'; }
'\u2715'
JavaScript stringI use this: if you declare var x = 0; before the functions declarations, the variable works for all the code files, but the variable will be declare every time that you edit a cell in the spreadsheet
This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.
In standard SQL one would write:
SELECT t0.foo, t1.bar
FROM FIRST_TABLE t0
RIGHT OUTER JOIN SECOND_TABLE t1;
Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :
Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]
All the answers here are great but, just to illustrate where this comes from, for questions like this it's good to go to the source: the Java Language Specification.
Section 15:23, Conditional-And operator (&&), says:
The && operator is like & (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true. [...] At run time, the left-hand operand expression is evaluated first [...] if the resulting value is false, the value of the conditional-and expression is false and the right-hand operand expression is not evaluated. If the value of the left-hand operand is true, then the right-hand expression is evaluated [...] the resulting value becomes the value of the conditional-and expression. Thus, && computes the same result as & on boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.
And similarly, Section 15:24, Conditional-Or operator (||), says:
The || operator is like | (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is false. [...] At run time, the left-hand operand expression is evaluated first; [...] if the resulting value is true, the value of the conditional-or expression is true and the right-hand operand expression is not evaluated. If the value of the left-hand operand is false, then the right-hand expression is evaluated; [...] the resulting value becomes the value of the conditional-or expression. Thus, || computes the same result as | on boolean or Boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.
A little repetitive, maybe, but the best confirmation of exactly how they work. Similarly the conditional operator (?:) only evaluates the appropriate 'half' (left half if the value is true, right half if it's false), allowing the use of expressions like:
int x = (y == null) ? 0 : y.getFoo();
without a NullPointerException.
As many others have pointed out here, increasing the timeout settings for NGINX can solve your issue.
However, increasing your timeout settings might not be as straightforward as many of these answers suggest. I myself faced this issue and tried to change my timeout settings in the /etc/nginx/nginx.conf file, as almost everyone in these threads suggest. This did not help me a single bit; there was no apparent change in NGINX' timeout settings. Now, many hours later, I finally managed to fix this problem.
The solution lies in this forum thread, and what it says is that you should put your timeout settings in /etc/nginx/conf.d/timeout.conf (and if this file doesn't exist, you should create it). I used the same settings as suggested in the thread:
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;
Just tried this rule, and it worked with GoDaddy hosting since they've already have the Microsoft URL Rewriting module installed for every IIS 7 account.
<rewrite>
<rules>
<rule name="enquiry" stopProcessing="true">
<match url="^enquiry$" />
<action type="Rewrite" url="/Enquiry.aspx" />
</rule>
</rules>
</rewrite>
you can try :
$("#MediaPlayer").ready(function(){
$("html, body").delay(2000).animate({
scrollTop: $('#MediaPlayer').offset().top
}, 2000);
});
Oct. 2008:
I would recommend to cache it in a static variable:
public static final class OsUtils
{
private static String OS = null;
public static String getOsName()
{
if(OS == null) { OS = System.getProperty("os.name"); }
return OS;
}
public static boolean isWindows()
{
return getOsName().startsWith("Windows");
}
public static boolean isUnix() // and so on
}
That way, every time you ask for the Os, you do not fetch the property more than once in the lifetime of your application.
February 2016: 7+ years later:
There is a bug with Windows 10 (which did not exist at the time of the original answer).
See "Java's “os.name” for Windows 10?"
You want your if
check to be:
{% if not loop.last %}
,
{% endif %}
Note that you can also shorten the code by using If Expression:
{{ ", " if not loop.last else "" }}
Unless your app is using some special encryption you can simply add Boolean a key to your Info.plist
with name ITSAppUsesNonExemptEncryption
and value NO
.
If your app is using custom encryption then you will need to provide extra legal documents and go through a review of your encryption before being able to select builds.
If you continue with selecting that version for testing, it will ask for the compliance information manually. Choosing "No" presents you with the plist recommendation above.
This is change has been announced in the 2015 WWDC, but I guess it has been enforced only very recently. See this and this for a transcript of the WWDC session related to the export compliance, just to a text search for "export".
There are other similar questions on SO, see:
Better late than never! Here is how we can do it(for learning purpose only)-
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class SoftDrink {
String name;
String color;
int volume;
SoftDrink (String name, String color, int volume) {
this.name = name;
this.color = color;
this.volume = volume;
}
}
public class ListItemComparision {
public static void main (String...arg) {
List<SoftDrink> softDrinkList = new ArrayList<SoftDrink>() ;
softDrinkList .add(new SoftDrink("Faygo", "ColorOne", 4));
softDrinkList .add(new SoftDrink("Fanta", "ColorTwo", 3));
softDrinkList .add(new SoftDrink("Frooti", "ColorThree", 2));
softDrinkList .add(new SoftDrink("Freshie", "ColorFour", 1));
Collections.sort(softDrinkList, new Comparator() {
@Override
public int compare(Object softDrinkOne, Object softDrinkTwo) {
//use instanceof to verify the references are indeed of the type in question
return ((SoftDrink)softDrinkOne).name
.compareTo(((SoftDrink)softDrinkTwo).name);
}
});
for (SoftDrink sd : softDrinkList) {
System.out.println(sd.name + " - " + sd.color + " - " + sd.volume);
}
Collections.sort(softDrinkList, new Comparator() {
@Override
public int compare(Object softDrinkOne, Object softDrinkTwo) {
//comparision for primitive int uses compareTo of the wrapper Integer
return(new Integer(((SoftDrink)softDrinkOne).volume))
.compareTo(((SoftDrink)softDrinkTwo).volume);
}
});
for (SoftDrink sd : softDrinkList) {
System.out.println(sd.volume + " - " + sd.color + " - " + sd.name);
}
}
}
You should really read Wikipedia for in-depth understanding. In short, Cloud computing means you develop/run your software remotely on remote platform. This can be either using remote virtual infrastructure (amazon EC2), remote platform (google app engine), or remote application (force.com or gmail.com).
Grid computing means using many physical hardwares to do computations (in the broad sense) as if it was a single hardware. This means that you can run your application on several distinct machines at the same time.
not very accurate but enough to get you started.
Depending on the hibernate flush mode that you are using (AUTO
is the default) save
may or may not write your changes to the DB straight away. When you call saveAndFlush
you are enforcing the synchronization of your model state with the DB.
If you use flush mode AUTO and you are using your application to first save and then select the data again, you will not see a difference in bahvior between save()
and saveAndFlush()
because the select triggers a flush first. See the documention.
Go to this link
Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download
Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.
From a Stack Overflow reference
It did not work with value="" if the browser already saves the value so you should add.
For an input tag there's the attribute autocomplete you can set:
<input type="text" autocomplete="off" />
You can use autocomplete for a form too.
You could also just create a Group Policy Preference and have it create the reg key for you. (no scripting involved)
I had the same problem on my virtual server with Parallels Plesk Panel 10.4.4. The solution was (thanks to Zappa for the idea) setting error_reporting value to 32767 instead of E_ALL. In Plesk: Home > Subscriptions > (Select domain) > Customize > PHP Settings > error_reporting - Enter custom value - 32767
hostname
and uname
will give you the name of the host. Then use nslookup
to translate that to an IP address.
For a three dimensional array you could try:
for c in array.transpose(1, 0, 2):
do_stuff(c)
See the docs on how array.transpose
works. Basically you are specifying which dimension to shift. In this case we are shifting the second dimension (e.g. columns) to the first dimension.
I came across this post today as I was trying to gather the time difference between fields located in separate tables joined together on a key field. This is the working code for such an endeavor. (tested in sql 2010) Bare in mind that my original query co-joined 6 tables on a common keyfield, in the code below I have removed the other tables as to not cause any confusion for the reader.
The purpose of the query is to calculate the difference between the variables CreatedUTC & BackupUTC, where difference is expressed in days and the field is called 'DaysActive.'
declare @CreatedUTC datetime
declare @BackupUtc datetime
SELECT TOP 500
table02.Column_CreatedUTC AS DeviceCreated,
CAST(DATEDIFF(day, table02.Column_CreatedUTC, table03.Column_EndDateUTC) AS nvarchar(5))+ ' Days' As DaysActive,
table03.Column_EndDateUTC AS LastCompleteBackup
FROM
Operations.table01 AS table01
LEFT OUTER JOIN
dbo.table02 AS table02
ON
table02.Column_KeyField = table01.Column_KeyField
LEFT OUTER JOIN
dbo.table03 AS table03
ON
table01.Column_KeyField = table03.Column_KeyField
Where table03.Column_EndDateUTC > dateadd(hour, -24, getutcdate()) --Gathers records with an end date in the last 24 hours
AND table02.[Column_CreatedUTC] = COALESCE(@CreatedUTC, table02.[Column_CreatedUTC])
AND table03.[Column_EndDateUTC] = COALESCE(@BackupUTC, table03.[Column_EndDateUTC])
GROUP BY table03.Column_EndDateUTC, table02.Column_CreatedUTC
ORDER BY table02.Column_CreatedUTC ASC, DaysActive, table03.Column_EndDateUTC DESC
The Output will be as follows:
[DeviceCreated]..[DaysActive]..[LastCompleteBackup]
---------------------------------------------------------
[2/13/12 16:04]..[463 Days]....[5/21/13 12:14]
[2/12/13 22:37]..[97 Days].....[5/20/13 22:10]
Python has a built in any() function for exactly this purpose.
drop the index and the foreign_key in the same query like below
ALTER TABLE `your_table_name` DROP FOREIGN KEY `your_index`;
ALTER TABLE `your_table_name` DROP COLUMN `your_foreign_key_id`;
Use execute_script
, here's a python example:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://stackoverflow.com/questions/7794087/running-javascript-in-selenium-using-python")
driver.execute_script("document.getElementsByClassName('comment-user')[0].click()")
I think the only difference is the amount of syntactical sugar on each query. BETWEEN is just a slick way of saying exactly the same as the second query.
There might be some RDBMS specific difference that I'm not aware of, but I don't really think so.
what about this?
top -c -p <PID>
In Font Awesome 5, you can create custom icons with your own SVG data. Here's a demo GitHub repo that you can play with. And here's a CodePen that shows how something similar might be done in <script>
blocks.
In either case, it simply involves using library.add()
to add an object like this:
export const faSomeObjectName = {
// Use a prefix like 'fac' that doesn't conflict with a prefix in the standard Font Awesome styles
// (So avoid fab, fal, fas, far, fa)
prefix: string,
iconName: string, // Any name you like
icon: [
number, // width
number, // height
string[], // ligatures
string, // unicode (if relevant)
string // svg path data
]
}
Note that the element labelled by the comment "svg path data" in the code sample is what will be assigned as the value of the d
attribute on a <path>
element that is a child of the <svg>
. Like this (leaving out some details for clarity):
<svg>
<path d=SVG_PATH_DATA></path>
</svg>
(Adapted from my similar answer here: https://stackoverflow.com/a/50338775/4642871)
I faced this issue when I was tring to link a locally created repo with a blank repo on github.
Initially I was trying git remote set-url
but I had to do git remote add
instead.
git remote add origin https://github.com/VijayNew/NewExample.git
First of all, you are trying to access non-static member var
outside the class which is not allowed in C++.
Mark's answer is correct.
Anything that is part of Outer should have access to all of Outer's members, public or private.
So you can do two things, either declare var
as static
or use a reference of an instance of the outer class to access 'var' (because a friend class or function also needs reference to access private data).
Static var
Change var
to static
If you don't want var
to be associated with the instances of the class.
#include <iostream>
class Outer {
private:
static const char* const MYCONST;
static int var;
public:
class Inner {
public:
Inner() {
Outer::var = 1;
}
void func() ;
};
};
int Outer::var = 0;
void Outer::Inner::func() {
std::cout << "var: "<< Outer::var;
}
int main() {
Outer outer;
Outer::Inner inner;
inner.func();
}
Output- var: 1
Non-static var
An object's reference is must access any non-static member variables.
#include <iostream>
class Outer {
private:
static const char* const MYCONST;
int var;
public:
class Inner {
public:
Inner(Outer &outer) {
outer.var = 1;
}
void func(const Outer &outer) ;
};
};
void Outer::Inner::func(const Outer &outer) {
std::cout << "var: "<< outer.var;
}
int main() {
Outer outer;
Outer::Inner inner(outer);
inner.func(outer);
}
Output- var: 1
Edit - External links are links to my Blog.
This is my proposed solution:
void showProgressDialog()
method can be added to the fragment-activity listener interface for this purpose.This issue for me was caused by a database mapping error.
I attempted to use a select() call on a datasource with errors in the code behind. My controls were within an update panel and the actual cause was hidden.
Usually, if you can temporarily remove the update panel, asp.net will return a more useful error message.
with open(csv_filename) as file:
data = file.read()
with open(xl_file_name, 'w') as file:
file.write(data)
You can turn CSV to excel like above with inbuilt packages. CSV can be handled with an inbuilt package of dictreader and dictwriter which will work the same way as python dictionary works. which makes it a ton easy I am currently unaware of any inbuilt packages for excel but I had come across openpyxl. It was also pretty straight forward and simple You can see the code snippet below hope this helps
import openpyxl
book = openpyxl.load_workbook(filename)
sheet = book.active
result =sheet['AP2']
print(result.value)
Year(Date)
Year()
: Returns the year portion of the date argument.
Date
: Current date only.
Explanation of both of these functions from here.
If you are on Mac OS X just use Simulator. I don't know if it is available by default but it looks like it is a part of the Xcode suite.
Anyway it is free and really useful, it allows you to simulate many popular Apple devices:
Setting a reference to the Microsoft Access 12.0 Object Library allows us to test if a table exists using DCount.
Public Function ifTableExists(tblName As String) As Boolean
If DCount("[Name]", "MSysObjects", "[Name] = '" & tblName & "'") = 1 Then
ifTableExists = True
End If
End Function
First, you'll need to add session_start()
at the top of any page that you wish to use SESSION
variables on.
Also, you should check to make sure the variable is set first before using it:
if(isset($_SESSION['SESS_fname'])){
echo $_SESSION['SESS_fname'];
}
Or, simply:
echo (isset($_SESSION['SESS_fname']) ? $_SESSION['SESS_fname'] : "Visitor");
Direct link to the .Net-3.5-Full-Setup
http://download.microsoft.com/download/6/0/f/60fc5854-3cb8-4892-b6db-bd4f42510f28/dotnetfx35.exe
Direct link to the .Net-3.5-SP1-Full-Setup
http://download.microsoft.com/download/2/0/e/20e90413-712f-438c-988e-fdaa79a8ac3d/dotnetfx35.exe
Thanks to Dzmitry Lahoda!
If you use .net 4.0 you can use a sorter way:
String.Join<string>(String.Empty, los);
onNewIntent()
is meant as entry point for singleTop activities which already run somewhere else in the stack and therefore can't call onCreate()
. From activities lifecycle point of view it's therefore needed to call onPause()
before onNewIntent()
. I suggest you to rewrite your activity to not use these listeners inside of onNewIntent()
. For example most of the time my onNewIntent()
methods simply looks like this:
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// getIntent() should always return the most recent
setIntent(intent);
}
With all setup logic happening in onResume()
by utilizing getIntent()
.
When you add floating point numbers together, there's often a little bit of error. Would a range(0.0, 2.2, 1.1)
return [0.0, 1.1]
or [0.0, 1.1, 2.199999999]
? There's no way to be certain without rigorous analysis.
The code you posted is an OK work-around if you really need this. Just be aware of the possible shortcomings.
Should be:
curl --cert certificate_file.pem:password https://www.example.com/some_protected_page
You may want to explore the notion of namespaces. In Python, the module is the natural place for global data:
Each module has its own private symbol table, which is used as the global symbol table by all functions defined in the module. Thus, the author of a module can use global variables in the module without worrying about accidental clashes with a user’s global variables. On the other hand, if you know what you are doing you can touch a module’s global variables with the same notation used to refer to its functions,
modname.itemname
.
A specific use of global-in-a-module is described here - How do I share global variables across modules?, and for completeness the contents are shared here:
The canonical way to share information across modules within a single program is to create a special configuration module (often called config or cfg). Just import the configuration module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere. For example:
File: config.py
x = 0 # Default value of the 'x' configuration setting
File: mod.py
import config
config.x = 1
File: main.py
import config
import mod
print config.x
As mentioned several times here
-webkit-appearance:none;
also removes the arrows, which is not what you want in most cases.
An easy workaround I found is to simply use select2 instead of select. You can re-style a select2 element as well, and most importantly, select2 looks the same on Windows, Android, iOS and Mac.
If you're interested in the reasons for these rules, it's because the time it takes the earth to make exactly one orbit around the sun is a long imprecise decimal value. It's not exactly 365.25. It's slightly less than 365.25, so every 100 years, one leap day must be eliminated (365.25 - 0.01 = 365.24). But that's not exactly correct either. The value is slightly larger than 365.24. So only 3 out of 4 times will the 100 year rule apply (or in other words, add back in 1 day every 400 years; 365.25 - 0.01 + 0.0025 = 365.2425).