In my case, this error happened with a new project.
none of the proposed solutions here worked, so I simply reinstalled all the packages and started working correctly.
Using $resource
in AngularJS you can do:
task.service.js
$ngTask.factory("$taskService", [
"$resource",
function ($resource) {
var taskModelUrl = 'api/task/';
return {
rest: {
taskUpload: $resource(taskModelUrl, {
id: '@id'
}, {
save: {
method: "POST",
isArray: false,
headers: {"Content-Type": undefined},
transformRequest: angular.identity
}
})
}
};
}
]);
And then use it in a module:
task.module.js
$ngModelTask.controller("taskController", [
"$scope",
"$taskService",
function (
$scope,
$taskService,
) {
$scope.saveTask = function (name, file) {
var newTask,
payload = new FormData();
payload.append("name", name);
payload.append("file", file);
newTask = $taskService.rest.taskUpload.save(payload);
// check if exists
}
}
Dmitry's answer works fine. I just made a simple example using the same technique.
jsfiddle: http://jsfiddle.net/o895a8n8/5/
<button onclick="call()">Call Controller's method from outside</button>
<div id="container" ng-app="" ng-controller="testController">
</div>
.
function call() {
var scope = angular.element(document.getElementById('container')).scope();
scope.$apply(function(){
scope.msg = scope.msg + ' I am the newly addded message from the outside of the controller.';
})
alert(scope.returnHello());
}
function testController($scope) {
$scope.msg = "Hello from a controller method.";
$scope.returnHello = function() {
return $scope.msg ;
}
}
Somewhere the code--either your code or a jQuery plugin--is calling $.browser
to get the current browser type.
However, early has year the $.browser
function was deprecated. Since then some bugs have been filed against it but because it is deprecated, the jQuery team has decided not to fix them. I've decided not to rely on the function at all.
I don't see any references to $.browser
in your code, so the problem probably lies in one of your plugins. To find it, look at the source code for each plugin that you've referenced with a <script>
tag.
As for how to fix it: well, it depends on the context. E.g., maybe there's an updated version of the problematic plugin. Or perhaps you can use another plugin that does something similar but doesn't depend on $.browser
.
Thanks to the previous commenters I found all the following worked for me:
Either adding an onclick stub to the element
onclick="void(0);"
or user a cursor pointer style
style="cursor:pointer;"
or as in my existing code my jquery code needed tap added
$(document).on('click tap','.ciAddLike',function(event)
{
alert('like added!'); // stopped working in ios safari until tap added
});
I am adding a cross-reference back to the Apple Docs for those interested. See Apple Docs:Making Events Clickable
(I'm not sure exactly when my hybrid app stopped processing clicks but I seem to remember they worked iOS 7 and earlier.)
Is your repository at "upstream" a bare repository? I got the same error, but when I change to bare they no longer happen.
A slight generalization to Peter's answer -- you can specify a range over the original array's shape if you want to go beyond three dimensional arrays.
e.g. to flatten all but the last two dimensions:
arr = numpy.zeros((3, 4, 5, 6))
new_arr = arr.reshape(-1, *arr.shape[-2:])
new_arr.shape
# (12, 5, 6)
EDIT: A slight generalization to my earlier answer -- you can, of course, also specify a range at the beginning of the of the reshape too:
arr = numpy.zeros((3, 4, 5, 6, 7, 8))
new_arr = arr.reshape(*arr.shape[:2], -1, *arr.shape[-2:])
new_arr.shape
# (3, 4, 30, 7, 8)
This is a little bit to old but: Solutions like is obsolete. Let the server handle the cache or not cache (in the response). The only way to guarantee no caching (thinking about new versions in production) is to change the js or css file with a version number. I do this with webpack.
Check whether the BIN
folder is uploaded completely or missing in the files.
You have to specify the name of the custom view and its related model in Controller Action method.
public ActionResult About()
{
return View("NameOfViewYouWantToReturn",Model);
}
df.dropna(subset=['columnName1', 'columnName2'])
If you do
.headers ON
you will get the desired result.
it works for me after changing MaxPermSize=512M to MaxPermSize=256M
matches
method performs matching of full line, i.e. it is equivalent to find()
with '^abc$'. So, just use Pattern.compile("[a-zA-Z]").matcher(str).find()
instead. Then fix your regex. As @user unknown mentioned your regex actually matches only one character. You probably should say [a-zA-Z]+
In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic
about following the C++ standard), you can do:
int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++
If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:
int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!
Or, better yet, use a standard container:
int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>
If you still want a proper array, you can use a constant, not a variable, when creating it:
const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)
Similarly, if you want to get the size from a function in C++11, you can use a constexpr
:
constexpr int n()
{
return 10;
}
double a[n()]; // n() is a compile time constant expression
As of the current JRE implementation, Function.identity()
will always return the same instance while each occurrence of identifier -> identifier
will not only create its own instance but even have a distinct implementation class. For more details, see here.
The reason is that the compiler generates a synthetic method holding the trivial body of that lambda expression (in the case of x->x
, equivalent to return identifier;
) and tell the runtime to create an implementation of the functional interface calling this method. So the runtime sees only different target methods and the current implementation does not analyze the methods to find out whether certain methods are equivalent.
So using Function.identity()
instead of x -> x
might save some memory but that shouldn’t drive your decision if you really think that x -> x
is more readable than Function.identity()
.
You may also consider that when compiling with debug information enabled, the synthetic method will have a line debug attribute pointing to the source code line(s) holding the lambda expression, therefore you have a chance of finding the source of a particular Function
instance while debugging. In contrast, when encountering the instance returned by Function.identity()
during debugging an operation, you won’t know who has called that method and passed the instance to the operation.
I assume you want to pass the Order ID in. So:
CREATE PROCEDURE [dbo].[Procedure_Name]
(
@OrderID INT
) AS
BEGIN
Declare @OrderItemID AS INT
DECLARE @AppointmentID AS INT
DECLARE @PurchaseOrderID AS INT
DECLARE @PurchaseOrderItemID AS INT
DECLARE @SalesOrderID AS INT
DECLARE @SalesOrderItemID AS INT
SET @OrderItemID = (SELECT OrderItemID FROM [OrderItem] WHERE OrderID = @OrderID)
SET @AppointmentID = (SELECT AppoinmentID FROM [Appointment] WHERE OrderID = @OrderID)
SET @PurchaseOrderID = (SELECT PurchaseOrderID FROM [PurchaseOrder] WHERE OrderID = @OrderID)
END
in your setChilds, you might want to try looping thru the list and doing something like
child.parent = this;
you also should set up the cascade on the parent to the appropriate values.
Swift 5
@IBOutlet weak var paswd: UITextField! {
didSet{
paswd.setLeftView(image: UIImage.init(named: "password")!)
paswd.tintColor = .darkGray
paswd.isSecureTextEntry = true
}
}
I have created extension
extension UITextField {
func setLeftView(image: UIImage) {
let iconView = UIImageView(frame: CGRect(x: 10, y: 10, width: 25, height: 25)) // set your Own size
iconView.image = image
let iconContainerView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 35, height: 45))
iconContainerView.addSubview(iconView)
leftView = iconContainerView
leftViewMode = .always
self.tintColor = .lightGray
}
}
Result
You might changed your drive-letter: once u had installed eclipse on D:\, after windows reinstall the drive-letter is now E:\ (for example).
look into eclipse.ini in your eclipse folder, there are some lines where the drive-letter is still D:\
Change return false;
to return true;
in longClickListener
You long click the button, if it returns true then it does the work. If it returns false then it does it's work and also calls the short click and then the onClick also works.
numpy.ndarray
can contain any type of element, e.g. int
, float
, string
etc. Check the type an do a conversion if neccessary.
because:
so guessing it's IME is always wrong - don't guess be sure !!!
@kevin-du is best solution wright now as its query IMM for IME height - but as it said the method is hidden API so using it could be dangerous in the way of getting wrong "false negative results" - by wrong dev usage.
Since following 2 reasons, you should run my solution in CMD:
Login username & password is sometimes necessary to query a remote SQL Server instance
sqlcmd -U [your_User] -P[your_password] -S [your_remote_Server] -d [your_databasename] -i "query.txt" -o "output.csv" -s"," -w 700
If you want pull requests, there are the open source projects of RhodeCode and GitLab and the paid Stash
Spring security is a filter based framework, it plants a WALL(HttpFireWall) before your application in terms of proxy filters or spring managed beans. Your request has to pass through multiple filters to reach your API.
WebAsyncManagerIntegrationFilter
Provides integration between the SecurityContext and Spring Web's WebAsyncManager.
SecurityContextPersistenceFilter
This filter will only execute once per request, Populates the SecurityContextHolder with information obtained from the configured SecurityContextRepository prior to the request and stores it back in the repository once the request has completed and clearing the context holder.
Request is checked for existing session. If new request, SecurityContext will be created else if request has session then existing security-context will be obtained from respository.
HeaderWriterFilter
Filter implementation to add headers to the current response.
LogoutFilter
If request url is /logout
(for default configuration) or if request url mathces RequestMatcher
configured in LogoutConfigurer
then
LogoutConfigurer
/
or logout success url configured or invokes logoutSuccessHandler configured.UsernamePasswordAuthenticationFilter
HTTP POST
) default /login
or matches .loginProcessingUrl()
configured in FormLoginConfigurer
then UsernamePasswordAuthenticationFilter
attempts authentication.usernameParameter(String)
, passwordParameter(String)
..loginPage()
overrides defaults Authentication
object(UsernamePasswordAuthenticationToken
or any implementation of Authentication
in case of your custom auth filter) is created. authenticationManager.authenticate(authToken)
will be invokedAuthenticationProvider
authenticate method tries all auth providers and checks any of the auth provider supports
authToken/authentication object, supporting auth provider will be used for authenticating. and returns Authentication object in case of successful authentication else throws AuthenticationException
.authenticationSuccessHandler
will be invoked which redirects to the target url configured(default is /
)SecurityContextHolderAwareRequestFilter
, if you are using it to install a Spring Security aware HttpServletRequestWrapper into your servlet container
AnonymousAuthenticationFilter
Detects if there is no Authentication object in the SecurityContextHolder, if no authentication object found, creates Authentication
object (AnonymousAuthenticationToken
) with granted authority ROLE_ANONYMOUS
. Here AnonymousAuthenticationToken
facilitates identifying un-authenticated users subsequent requests.
DEBUG - /app/admin/app-config at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
DEBUG - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@aeef7b36: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
ExceptionTranslationFilter
, to catch any Spring Security exceptions so that either an HTTP error response can be returned or an appropriate AuthenticationEntryPoint can be launched
FilterSecurityInterceptor
There will be FilterSecurityInterceptor
which comes almost last in the filter chain which gets Authentication object from SecurityContext
and gets granted authorities list(roles granted) and it will make a decision whether to allow this request to reach the requested resource or not, decision is made by matching with the allowed AntMatchers
configured in HttpSecurityConfiguration
.
Consider the exceptions 401-UnAuthorized and 403-Forbidden. These decisions will be done at the last in the filter chain
Note: User Request flows not only in above mentioned filters, but there are others filters too not shown here.(ConcurrentSessionFilter
,RequestCacheAwareFilter
,SessionManagementFilter
...)
It will be different when you use your custom auth filter instead of UsernamePasswordAuthenticationFilter
.
It will be different if you configure JWT auth filter and omit .formLogin() i.e, UsernamePasswordAuthenticationFilter
it will become entirely different case.
From Documentation ordering of filters is given as
- ChannelProcessingFilter
- ConcurrentSessionFilter
- SecurityContextPersistenceFilter
- LogoutFilter
- X509AuthenticationFilter
- AbstractPreAuthenticatedProcessingFilter
- CasAuthenticationFilter
- UsernamePasswordAuthenticationFilter
- ConcurrentSessionFilter
- OpenIDAuthenticationFilter
- DefaultLoginPageGeneratingFilter
- DefaultLogoutPageGeneratingFilter
- ConcurrentSessionFilter
- DigestAuthenticationFilter
- BearerTokenAuthenticationFilter
- BasicAuthenticationFilter
- RequestCacheAwareFilter
- SecurityContextHolderAwareRequestFilter
- JaasApiIntegrationFilter
- RememberMeAuthenticationFilter
- AnonymousAuthenticationFilter
- SessionManagementFilter
- ExceptionTranslationFilter
- FilterSecurityInterceptor
- SwitchUserFilter
You can also refer
most common way to authenticate a modern web app?
difference between authentication and authorization in context of Spring Security?
For the sake of an alternative answer for those searching for a lightweight way to just find a user's home dir...
Rather than messing with su
hacks, or bothering with the overhead of launching another bash
shell just to find the $HOME
environment variable...
There is a command specifically for this: getent
getent passwd someuser | cut -f6 -d:
getent
can do a lot more... just see the man page. The passwd
nsswitch database will return the user's entry in /etc/passwd
format. Just split it on the colon :
to parse out the fields.
It should be installed on most Linux systems (or any system that uses GNU Lib C (RHEL: glibc-common
, Deb: libc-bin
)
The JAX-WS way for basic authentication is
Service s = new Service();
Port port = s.getPort();
BindingProvider prov = (BindingProvider)port;
prov.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "myusername");
prov.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "mypassword");
port.call();
# SOCKS5 proxy for HTTP/HTTPS
proxiesDict = {
'http' : "socks5://1.2.3.4:1080",
'https' : "socks5://1.2.3.4:1080"
}
# SOCKS4 proxy for HTTP/HTTPS
proxiesDict = {
'http' : "socks4://1.2.3.4:1080",
'https' : "socks4://1.2.3.4:1080"
}
# HTTP proxy for HTTP/HTTPS
proxiesDict = {
'http' : "1.2.3.4:1080",
'https' : "1.2.3.4:1080"
}
Using @vivek's hint I develop an utils class based on Swift 3, hope you appreciate!
import Foundation
import UIKit
public enum PreferenceType: String {
case about = "General&path=About"
case accessibility = "General&path=ACCESSIBILITY"
case airplaneMode = "AIRPLANE_MODE"
case autolock = "General&path=AUTOLOCK"
case cellularUsage = "General&path=USAGE/CELLULAR_USAGE"
case brightness = "Brightness"
case bluetooth = "Bluetooth"
case dateAndTime = "General&path=DATE_AND_TIME"
case facetime = "FACETIME"
case general = "General"
case keyboard = "General&path=Keyboard"
case castle = "CASTLE"
case storageAndBackup = "CASTLE&path=STORAGE_AND_BACKUP"
case international = "General&path=INTERNATIONAL"
case locationServices = "LOCATION_SERVICES"
case accountSettings = "ACCOUNT_SETTINGS"
case music = "MUSIC"
case equalizer = "MUSIC&path=EQ"
case volumeLimit = "MUSIC&path=VolumeLimit"
case network = "General&path=Network"
case nikePlusIPod = "NIKE_PLUS_IPOD"
case notes = "NOTES"
case notificationsId = "NOTIFICATIONS_ID"
case phone = "Phone"
case photos = "Photos"
case managedConfigurationList = "General&path=ManagedConfigurationList"
case reset = "General&path=Reset"
case ringtone = "Sounds&path=Ringtone"
case safari = "Safari"
case assistant = "General&path=Assistant"
case sounds = "Sounds"
case softwareUpdateLink = "General&path=SOFTWARE_UPDATE_LINK"
case store = "STORE"
case twitter = "TWITTER"
case facebook = "FACEBOOK"
case usage = "General&path=USAGE"
case video = "VIDEO"
case vpn = "General&path=Network/VPN"
case wallpaper = "Wallpaper"
case wifi = "WIFI"
case tethering = "INTERNET_TETHERING"
case blocked = "Phone&path=Blocked"
case doNotDisturb = "DO_NOT_DISTURB"
}
enum PreferenceExplorerError: Error {
case notFound(String)
}
open class PreferencesExplorer {
// MARK: - Class properties -
static private let preferencePath = "App-Prefs:root"
// MARK: - Class methods -
static func open(_ preferenceType: PreferenceType) throws {
let appPath = "\(PreferencesExplorer.preferencePath)=\(preferenceType.rawValue)"
if let url = URL(string: appPath) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
} else {
throw PreferenceExplorerError.notFound(appPath)
}
}
}
This is very helpful since that API's will change for sure and you can refactor once and very fast!
Do this:
"android:style/Theme.Holo.Light.DarkActionBar"
You missed the android
keyword before style. This denotes that it is an inbuilt style for Android.
Here you go:
public static byte[] ConvertToByteArray(string str, Encoding encoding)
{
return encoding.GetBytes(str);
}
public static String ToBinary(Byte[] data)
{
return string.Join(" ", data.Select(byt => Convert.ToString(byt, 2).PadLeft(8, '0')));
}
// Use any sort of encoding you like.
var binaryString = ToBinary(ConvertToByteArray("Welcome, World!", Encoding.ASCII));
You can get fans using new facebook search: https://www.facebook.com/search/321770180859/likers?ref=about
Since the methods used in other answers seems quite complicated for such easy task, here is a new answer:
Instead of a ListedColormap
, which produces a discrete colormap, you may use a LinearSegmentedColormap
. This can easily be created from a list using the from_list
method.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors
x,y,c = zip(*np.random.rand(30,3)*4-2)
norm=plt.Normalize(-2,2)
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", ["red","violet","blue"])
plt.scatter(x,y,c=c, cmap=cmap, norm=norm)
plt.colorbar()
plt.show()
More generally, if you have a list of values (e.g. [-2., -1, 2]
) and corresponding colors, (e.g. ["red","violet","blue"]
), such that the n
th value should correspond to the n
th color, you can normalize the values and supply them as tuples to the from_list
method.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors
x,y,c = zip(*np.random.rand(30,3)*4-2)
cvals = [-2., -1, 2]
colors = ["red","violet","blue"]
norm=plt.Normalize(min(cvals),max(cvals))
tuples = list(zip(map(norm,cvals), colors))
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", tuples)
plt.scatter(x,y,c=c, cmap=cmap, norm=norm)
plt.colorbar()
plt.show()
You're probably looking for the Convert.ChangeType
method. For example:
Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude");
propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType), null);
JupyterLab supports cell collapsing. Clicking on the blue cell bar on the left will fold the cell.
There are more aspects to this.
You can achieve TLS (some keep saying SSL) with a certificate, self-signed or not.
To have a green bar for a self-signed certificate, you also need to become the Certificate Authority (CA). This aspect is missing in most resources I found on my journey to achieve the green bar in my local development setup. Becoming a CA is as easy as creating a certificate.
This resource covers the creation of both the CA certificate and a Server certificate and resulted my setup in showing a green bar on localhost Chrome, Firefox and Edge: https://ram.k0a1a.net/self-signed_https_cert_after_chrome_58
Please note: in Chrome you need to add the CA Certificate to your trusted authorities.
Here's how I would do it. I'll leave range checking on the int month
up to you.
import java.text.DateFormatSymbols;
public String formatMonth(int month, Locale locale) {
DateFormatSymbols symbols = new DateFormatSymbols(locale);
String[] monthNames = symbols.getMonths();
return monthNames[month - 1];
}
The stl contains a bunch of methods that should be used dependent to the problem.
std::find
std::find_if
std::count
std::find
std::binary_search
std::equal_range
std::lower_bound
std::upper_bound
Now it contains on your data what algorithm to use. This Artikel contains a perfect table to help choosing the right algorithm.
In the special case where min max should be determined and you are using std::vector or ???* array
std::min_element
std::max_element
can be used.
I solved this problem by adding C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\System.Runtime.Serialization.dll in the reference
You can change the buffer size of cmd by clicking the icon at top left corner -->properties --> layout --> screen buffer size.
you can even change it with cmd command
mode con:cols=100 lines=60
Upto lines = 58 the height of the cmd window changes ..
After lines value of 58 the buffer size of the cmd changes...
Look up ?strftime
:
%A
Full weekday name in the current locale
df$day = strftime(df$date,'%A')
This question comes up as one of the top 3 hits for the Google search for "how to suppress -Wunused-result in c++", so I'm adding this answer here since I figured it out and want to help the next person.
-Wunused
(or one of its sub-errors) or -Wunused -Werror
only, the solution is to cast to void
:For -Wunused
or one of its sub-errors only1, you can just cast it to void
to disable the warning. This should work for any compiler and any IDE for both C and C++.
1Note 1: see gcc documentation here, for example, for a list of these warnings: https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html, then search for the phrase "All the above -Wunused options combined" and look there for the main -Wunused
warning and above it for its sub-warnings. The sub-warnings that -Wunused
contains include:
-Wunused-but-set-parameter
-Wunused-but-set-variable
-Wunused-function
-Wunused-label
-Wunused-local-typedefs
-Wunused-parameter
-Wno-unused-result
-Wunused-variable
-Wunused-const-variable
-Wunused-const-variable=n
-Wunused-value
-Wunused
= contains all of the above -Wunused
options combinedExample of casting to void
to suppress this warning:
// some "unused" variable you want to keep around
int some_var = 7;
// turn off `-Wunused` compiler warning for this one variable
// by casting it to void
(void)some_var; // <===== SOLUTION! ======
For C++, this also works on functions which return a variable marked with [[nodiscard]]
:
C++ attribute: nodiscard (since C++17)
If a function declared nodiscard or a function returning an enumeration or class declared nodiscard by value is called from a discarded-value expression other than a cast to void, the compiler is encouraged to issue a warning.
(Source: https://en.cppreference.com/w/cpp/language/attributes/nodiscard)
So, the solution is to cast the function call to void
, as this is actually casting the value returned by the function (which is marked with the [[nodiscard]]
attribute) to void
.
Example:
// Some class or struct marked with the C++ `[[nodiscard]]` attribute
class [[nodiscard]] MyNodiscardClass
{
public:
// fill in class details here
private:
// fill in class details here
};
// Some function which returns a variable previously marked with
// with the C++ `[[nodiscard]]` attribute
MyNodiscardClass MyFunc()
{
MyNodiscardClass myNodiscardClass;
return myNodiscardClass;
}
int main(int argc, char *argv[])
{
// THE COMPILER WILL COMPLAIN ABOUT THIS FUNCTION CALL
// IF YOU HAVE `-Wunused` turned on, since you are
// discarding a "nodiscard" return type by calling this
// function and not using its returned value!
MyFunc();
// This is ok, however, as casing the returned value to
// `void` suppresses this `-Wunused` warning!
(void)MyFunc(); // <===== SOLUTION! ======
}
Lastly, you can also use the C++17 [[maybe_unused]]
attribute: https://en.cppreference.com/w/cpp/language/attributes/maybe_unused.
Additional: when you save df to .csv format, the datetime (year in this specific case) is saved as object, so you need to convert it into integer (year in this specific case) when you do the merge. That is why when you upload both df from csv files, you can do the merge easily, while above error will show up if one df is uploaded from csv files and the other is from an existing df. This is somewhat annoying, but have an easy solution if kept in mind.
use Extension
import java.text.NumberFormat
val Int.commaString: String
get() = NumberFormat.getInstance().format(this)
val String.commaString: String
get() = NumberFormat.getNumberInstance().format(this.toDouble())
val Long.commaString: String
get() = NumberFormat.getInstance().format(this)
val Double.commaString: String
get() = NumberFormat.getInstance().format(this)
result
1234.commaString => 1,234
"1234.456".commaString => 1,234.456
1234567890123456789.commaString => 1,234,567,890,123,456,789
1234.456.commaString => 1,234.456
Run the below in the command prompt:
Start -> Run -> Type cmd
and enter the command below in the resulting black box:
wmic os get osarchitecture
I found this resource that details the various methods: How to embed TIFF files in HTML documents
As mentioned, it will very much depend on browser support for the format. Viewing that page in Chrome on Windows didn't display any of the images.
It would also be helpful if you posted the code you've tried already.
It is possible using Apex Recovery Tool,i have successfully recovered my table rows which i accidentally deleted
if you download the trial version it will recover only 10th row
check here http://www.apexsql.com/sql_tools_log.aspx
Both approaches call a constructor, they just call different ones. This code:
var albumData = new Album
{
Name = "Albumius",
Artist = "Artistus",
Year = 2013
};
is syntactic shorthand for this equivalent code:
var albumData = new Album();
albumData.Name = "Albumius";
albumData.Artist = "Artistus";
albumData.Year = 2013;
The two are almost identical after compilation (close enough for nearly all intents and purposes). So if the parameterless constructor wasn't public:
public Album() { }
then you wouldn't be able to use the object initializer at all anyway. So the main question isn't which to use when initializing the object, but which constructor(s) the object exposes in the first place. If the object exposes two constructors (like the one in your example), then one can assume that both ways are equally valid for constructing an object.
Sometimes objects don't expose parameterless constructors because they require certain values for construction. Though in cases like that you can still use the initializer syntax for other values. For example, suppose you have these constructors on your object:
private Album() { }
public Album(string name)
{
this.Name = name;
}
Since the parameterless constructor is private, you can't use that. But you can use the other one and still make use of the initializer syntax:
var albumData = new Album("Albumius")
{
Artist = "Artistus",
Year = 2013
};
The post-compilation result would then be identical to:
var albumData = new Album("Albumius");
albumData.Artist = "Artistus";
albumData.Year = 2013;
Use ternary operator:
echo (($test == '') ? $redText : '');
echo $test == '' ? $redText : ''; //removed parenthesis
But in this case you can't use shorter reversed version because it will return bool(true)
in first condition.
echo (($test != '') ?: $redText); //this will not work properly for this case
Install this plugin for jquery and use it
http://plugins.jquery.com/project/jqueryenabledisable
It allows you to disable/enable pretty much any field in the page.
If you want to open a page on some condition write a java script function and call it from href. If the condition satisfied you open page otherwise just do nothing.
code looks like this:
<a href="javascript: openPage()" >Click here</a>
and function:
function openPage()
{
if(some conditon)
opener.document.location = "http://www.google.com";
}
}
You can also put the link in a div and set the display property of the Style attribute to none. this will hide the div. For eg.,
<div id="divid" style="display:none">
<a href="Hiding Link" />
</div>
This will hide the link. Use a button or an image to make this div visible now by calling this function in onclick as:
<a href="Visible Link" onclick="showDiv()">
and write the js code as:
function showDiv(){
document.getElememtById("divid").style.display="block";
}
You can also put an id tag to the html tag, so it would be
<a id="myATag" href="whatever"></a>
And get this id on your javascript by using
document.getElementById("myATag").value="#";
One of this must work for sure haha
var url = "http://www.example.com";
window.open(url, '_blank');
As of C++11, you have two major additional options. First, you can use insert()
with list initialization syntax:
function.insert({0, 42});
This is functionally equivalent to
function.insert(std::map<int, int>::value_type(0, 42));
but much more concise and readable. As other answers have noted, this has several advantages over the other forms:
operator[]
approach requires the mapped type to be assignable, which isn't always the case.operator[]
approach can overwrite existing elements, and gives you no way to tell whether this has happened.insert
that you list involve an implicit type conversion, which may slow your code down.The major drawback is that this form used to require the key and value to be copyable, so it wouldn't work with e.g. a map with unique_ptr
values. That has been fixed in the standard, but the fix may not have reached your standard library implementation yet.
Second, you can use the emplace()
method:
function.emplace(0, 42);
This is more concise than any of the forms of insert()
, works fine with move-only types like unique_ptr
, and theoretically may be slightly more efficient (although a decent compiler should optimize away the difference). The only major drawback is that it may surprise your readers a little, since emplace
methods aren't usually used that way.
try this
if($('input:radio:checked').length > 0){
// go on with script
}else{
// NOTHING IS CHECKED
}
find path -type f | xargs -L1 command
is all you need.
From the 1.1.x
documentation, you can enable debug mode by exporting an environment variable to your shell prompt:
export FLASK_APP=/daemon/api/views.py # path to app
export FLASK_DEBUG=1
python -m flask run --host=0.0.0.0
You can merge interface with namespace using the same name:
interface myInterface { }
namespace myInterface {
Name:string;
}
But this interface is only useful to know that its have property Name
. You can not implement it.
Currently the working soloution is android:fillColor="#FFFFFF"
Nothing worked for me except hard coding in the vector
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:fillColor="#FFFFFF"
android:viewportHeight="24.0">
<path
android:fillColor="#FFFFFF"
android:pathData="M15.5,14h-0.79l-0.28,-0.27C15.41,12.59 16,11.11 16,9.5 16,5.91 13.09,3 9.5,3S3,5.91 3,9.5 5.91,16 9.5,16c1.61,0 3.09,-0.59 4.23,-1.57l0.27,0.28v0.79l5,4.99L20.49,19l-4.99,-5zm-6,0C7.01,14 5,11.99 5,9.5S7.01,5 9.5,5 14,7.01 14,9.5 11.99,14 9.5,14z"/>
However, fillcolor and tint might work soon. Please see this discussion for more information:
https://code.google.com/p/android/issues/detail?id=186431
Also the colors mighr stick in the cache so deleting app for all users might help.
You are experiencing this issue for two reasons.
When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)
User.java
@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="iduser")
private Long idUser;
@Column(name="user_name")
private String userName;
@OneToOne()
@JoinColumn(name="idarea")
private Area area;
public Long getIdUser() {
return idUser;
}
public void setIdUser(Long idUser) {
this.idUser = idUser;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Area getArea() {
return area;
}
public void setArea(Area area) {
this.area = area;
}
}
Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:
@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")
While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.
Area.java
@Entity
@Table(name = "area")
public class Area {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="idarea")
private Long idArea;
@Column(name="area_name")
private String areaName;
@OneToOne(fetch=FetchType.LAZY, mappedBy="area")
private User user;
public Long getIdArea() {
return idArea;
}
public void setIdArea(Long idArea) {
this.idArea = idArea;
}
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
You can use default_scope to implement a default sort order http://api.rubyonrails.org/classes/ActiveRecord/Scoping/Default/ClassMethods.html
For the follow-up question, you can get a number between 36^5 and 36^6 and convert it in base 36
UPDATED:
using this code
http://javaconfessions.com/2008/09/convert-between-base-10-and-base-62-in_28.html
It's written
BaseConverterUtil.toBase36(60466176+r.nextInt(2116316160))
but in your use case, it can be optimized by using a StringBuilder
and having the number in the reverse order ie 71 should be converted in Z1 instead of 1Z
EDITED:
You can easily convert the string data type to numerical data type.
Don't forget to change collectionName & FieldName. for ex : CollectionNmae : Users & FieldName : Contactno.
Try this query..
db.collectionName.find().forEach( function (x) {
x.FieldName = parseInt(x.FieldName);
db.collectionName.save(x);
});
/^[\w-_.]*$/
What is means By:
^ Start of string
[......] Match characters inside
\w Any word character so 0-9 a-z A-Z
-_. Matched by charecter - and _ and .
Zero or more of pattern or unlimited $ End of string If you want to limit the amount of characters:
/^[\w-_.]{0,5}$/
{0,5} Means 0-5 Numbers & characters
I tried the usual "gg=G" command, which is what I use to fix the indentation of code files. However, it didn't seem to work right on HTML files. It simply removed all the formatting.
If vim's autoformat/indent gg=G
seems to be "broken" (such as left indenting every line), most likely the indent plugin is not enabled/loaded. It should really give an error message instead of just doing bad indenting, otherwise users just think the autoformat/indenting feature is awful, when it actually is pretty good.
To check if the indent plugin is enabled/loaded, run :scriptnames
. See if .../indent/html.vim
is in the list. If not, then that means the plugin is not loaded. In that case, add this line to ~/.vimrc
:
filetype plugin indent on
Now if you open the file and run :scriptnames
, you should see .../indent/html.vim
. Then run gg=G
, which should do the correct autoformat/indent now. (Although it won't add newlines, so if all the html code is on a single line, it won't be indented).
Note: if you are running :filetype plugin indent on
on the vim command line instead of ~/.vimrc
, you must re-open the file :e
.
Also, you don't need to worry about autoindent
and smartindent
settings, they are not relevant for this.
At the end of the day, you simply cannot do this in MS SQL. I recently created tables on the go (application startup) using a stored Procedure that reads from a lookup table. When I created a view that combined these with another table I had manually created earlier one (same schema, with data), It failed - simply because I was using ''Select * UNION Select * ' for the view. At the same time, if I use only those created through the stored procedure, I am successful.
In conclusion: If there is any application which depends on the order of column it is really not good programming and will for sure create problems in the future. Columns should 'feel' free to be anywhere and be used for any data process (INSERT, UPDATE, SELECT).
Xcode 9.2, Swift 4, this works for me.
<key>App Transport Security Settings</key>
<dict>
<key>Allow Arbitrary Loads</key>
<true/>
</dict>
Try these simple steps:
ObjectMapper mapper = new ObjectMapper();
String newJsonData = mapper.writeValueAsString(cartList);
return newJsonData;
ObjectMapper() is com.fasterxml.jackson.databind.ObjectMapper.ObjectMapper();
For array type Please try this one.
List<MyStok> myDeserializedObjList = (List<MyStok>)Newtonsoft.Json.JsonConvert.DeserializeObject(sc), typeof(List<MyStok>));
I make another solution for dropdown. Hope this is helpfull Just add this js script
<script type="text/javascript"> jQuery("document").ready(function() {
jQuery("ul.dropdown-menu > .dropdown.parent").click(function(e) {
e.preventDefault();
e.stopPropagation();
if (jQuery(this).hasClass('open2'))
jQuery(this).removeClass('open2');
else {
jQuery(this).addClass('open2');
}
});
}); < /script>
<style type="text/css">.open2{display:block; position:relative;}</style>
request.getSession(true)
and request.getSession()
both do the same thing, but if we use
request.getSession(false)
it will return null
if session object not created yet.
Updating the accepted answer (can't comment yet). As of 1/12/16 using the demo jsfiddle in chrome, switch-immediate is the fastest solution.
Results: Time resolution: 1.33
25ms "if-immediate" 150878146
29ms "if-indirect" 150878146
24ms "switch-immediate" 150878146
128ms "switch-range" 150878146
45ms "switch-range2" 150878146
47ms "switch-indirect-array" 150878146
43ms "array-linear-switch" 150878146
72ms "array-binary-switch" 150878146
Finished
1.04 ( 25ms) if-immediate
1.21 ( 29ms) if-indirect
1.00 ( 24ms) switch-immediate
5.33 ( 128ms) switch-range
1.88 ( 45ms) switch-range2
1.96 ( 47ms) switch-indirect-array
1.79 ( 43ms) array-linear-switch
3.00 ( 72ms) array-binary-switch
If you have a colleague working with you:
1) ask him to rename the file causing problems and commit
2) you update
(now you see the file with invalid checksum with different name)
3) rename it back to its original name
4) commit
(and ask you colleague to update
to get back the file name in its initial state)
This solved the problem for me.
Changing code page to 1252 is working for me. The problem for me is the symbol double doller § is converting to another symbol by DOS on Windows Server 2008.
I have used CHCP 1252 and a cap before it in my BCP statement ^§.
Here is a generic solution for this problem.
public <T> List<T> difference(List<T> first, List<T> second) {
List<T> toReturn = new ArrayList<>(first);
toReturn.removeAll(second);
return toReturn;
}
This should work too:
logging.Formatter(fmt='%(asctime)s.%(msecs)03d',datefmt='%Y-%m-%d,%H:%M:%S')
I have this same requirement - we want to put logs in a specific root directory that should exist within the environment.
public static readonly string DefaultLogFilePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
If I want to combine this with a sub-directory, I should be able to use Path.Combine( ... )
.
The GetFolderPath
method has an overload for special folder options which allows you to control whether the specified path be created or simply verified.
Use the Maven debug option, ie mvn -X
:
Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...
In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml
.
I had a similar issue and just fixed it by creating an image with the same aspect ratio as my video (16:9). My width is set to 100% on the video tag and now the image (320 x 180) fits perfectly. Hope that helps!
You could use THROW
(available in SQL Server 2012+):
THROW 50000, 'Your custom error message', 1
THROW <error_number>, <message>, <state>
I use maven for my java builds which has a plugin called the maven assembly plugin.
It does what your asking, but like some of the other suggestions describe - essentially exploding all the dependent jars and recombining them into a single jar
You can use the csv module found in the python standard library to manipulate CSV files.
example:
import csv
with open('some.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
print row
You should install Application Development part of IIS on your server as you may see in this picture:
You can find the answer to your question on the following page:
https://stackoverflow.com/a/17633941/2359161
Here is the JSFiddle that was given:
Note the scrolling section at the end of the CSS, specifically:
/*_x000D_
*Styling_x000D_
*/_x000D_
_x000D_
html,body {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
position: relative; _x000D_
}_x000D_
body {_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
header {_x000D_
background: #fff; _x000D_
position: fixed; _x000D_
left: 0; top: 0; _x000D_
width:100%;_x000D_
height: 3.5rem;_x000D_
z-index: 10; _x000D_
}_x000D_
_x000D_
nav {_x000D_
width: 100%;_x000D_
padding-top: 0.5rem;_x000D_
}_x000D_
_x000D_
nav ul {_x000D_
list-style: none;_x000D_
width: inherit; _x000D_
margin: 0; _x000D_
}_x000D_
_x000D_
_x000D_
ul li:nth-child( 3n + 1), #main .panel:nth-child( 3n + 1) {_x000D_
background: rgb( 0, 180, 255 );_x000D_
}_x000D_
_x000D_
ul li:nth-child( 3n + 2), #main .panel:nth-child( 3n + 2) {_x000D_
background: rgb( 255, 65, 180 );_x000D_
}_x000D_
_x000D_
ul li:nth-child( 3n + 3), #main .panel:nth-child( 3n + 3) {_x000D_
background: rgb( 0, 255, 180 );_x000D_
}_x000D_
_x000D_
ul li {_x000D_
display: inline-block; _x000D_
margin: 0 8px;_x000D_
margin: 0 0.5rem;_x000D_
padding: 5px 8px;_x000D_
padding: 0.3rem 0.5rem;_x000D_
border-radius: 2px; _x000D_
line-height: 1.5;_x000D_
}_x000D_
_x000D_
ul li a {_x000D_
color: #fff;_x000D_
text-decoration: none;_x000D_
}_x000D_
_x000D_
.panel {_x000D_
width: 100%;_x000D_
height: 500px;_x000D_
z-index:0; _x000D_
-webkit-transform: translateZ( 0 );_x000D_
transform: translateZ( 0 );_x000D_
-webkit-transition: -webkit-transform 0.6s ease-in-out;_x000D_
transition: transform 0.6s ease-in-out;_x000D_
-webkit-backface-visibility: hidden;_x000D_
backface-visibility: hidden;_x000D_
_x000D_
}_x000D_
_x000D_
.panel h1 {_x000D_
font-family: sans-serif;_x000D_
font-size: 64px;_x000D_
font-size: 4rem;_x000D_
color: #fff;_x000D_
position:relative;_x000D_
line-height: 200px;_x000D_
top: 33%;_x000D_
text-align: center;_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
/*_x000D_
*Scrolling_x000D_
*/_x000D_
_x000D_
a[ id= "servicios" ]:target ~ #main article.panel {_x000D_
-webkit-transform: translateY( 0px);_x000D_
transform: translateY( 0px );_x000D_
}_x000D_
_x000D_
a[ id= "galeria" ]:target ~ #main article.panel {_x000D_
-webkit-transform: translateY( -500px );_x000D_
transform: translateY( -500px );_x000D_
}_x000D_
a[ id= "contacto" ]:target ~ #main article.panel {_x000D_
-webkit-transform: translateY( -1000px );_x000D_
transform: translateY( -1000px );_x000D_
}
_x000D_
<a id="servicios"></a>_x000D_
<a id="galeria"></a>_x000D_
<a id="contacto"></a>_x000D_
<header class="nav">_x000D_
<nav>_x000D_
<ul>_x000D_
<li><a href="#servicios"> Servicios </a> </li>_x000D_
<li><a href="#galeria"> Galeria </a> </li>_x000D_
<li><a href="#contacto">Contacta nos </a> </li>_x000D_
</ul>_x000D_
</nav>_x000D_
</header>_x000D_
_x000D_
<section id="main">_x000D_
<article class="panel" id="servicios">_x000D_
<h1> Nuestros Servicios</h1>_x000D_
</article>_x000D_
_x000D_
<article class="panel" id="galeria">_x000D_
<h1> Mustra de nuestro trabajos</h1>_x000D_
</article>_x000D_
_x000D_
<article class="panel" id="contacto">_x000D_
<h1> Pongamonos en contacto</h1>_x000D_
</article>_x000D_
</section>
_x000D_
The user543 answer is perfect
<activity
android:name="first Activity Name"
android:theme="@android:style/Theme.Translucent.NoTitleBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
But:
You'r LAUNCHER Activity must extands Activity, not AppCompatActivity as it came by default!
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
Where referenceNode
is the node you want to put newNode
after. If referenceNode
is the last child within its parent element, that's fine, because referenceNode.nextSibling
will be null
and insertBefore
handles that case by adding to the end of the list.
So:
function insertAfter(newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
You can test it using the following snippet:
function insertAfter(referenceNode, newNode) {_x000D_
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);_x000D_
}_x000D_
_x000D_
var el = document.createElement("span");_x000D_
el.innerHTML = "test";_x000D_
var div = document.getElementById("foo");_x000D_
insertAfter(div, el);
_x000D_
<div id="foo">Hello</div>
_x000D_
1) add the below jquery:
$thumbnail.on('click', function(e){
e.preventDefault();
src = src+'&autoplay=1'; // src: the original URL for embedding
$videoContainer.empty().append( $iframe.clone().attr({'src': src}) ); // $iframe: the original iframe for embedding
}
);
note: in the first src (shown) add the original youtube link.
2) edit the iframe tag as:
<iframe width="1280" height="720" src="https://www.youtube.com/embed/nfQHF87vY0s?autoplay=1" frameborder="0" allowfullscreen></iframe>
note: copy paste the youtube video id after the embed/ in the iframe src.
For Bootstrap 4
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="input-group">_x000D_
<input type="text" class="form-control" placeholder="Start"/>_x000D_
<div class="input-group-prepend">_x000D_
<span class="input-group-text" id="">-</span>_x000D_
</div>_x000D_
<input type="text" class="form-control" placeholder="End"/>_x000D_
</div>
_x000D_
I remote into the computer using Enter-PSsession pcName then I type Get-PSDrive
That will list all drives and space used and remaining. If you need to see all the info formated, pipe it to FL like this: Get-PSdrive | FL *
If you're okay with the formatting as it appears when you call the DataFrame in your coding environment, then the absolute easiest way is to just use print screen and crop the image using basic image editing software.
Here's how it turned out for me using Jupyter Notebook, and Pinta Image Editor (Ubuntu freeware).
Give selected
attribute to all options like this
$('#countries option').attr('selected', 'selected');
Usage:
$('#select_all').click( function() {
$('#countries option').attr('selected', 'selected');
});
In case you are using 1.6+, better option would be to use .prop()
instead of .attr()
$('#select_all').click( function() {
$('#countries option').prop('selected', true);
});
I dont think adding dual functions inside the toggle function works for a registered click event (Unless I'm missing something)
For example:
$('.btnName').click(function() {
top.$('#panel').toggle(function() {
$(this).animate({
// style change
}, 500);
},
function() {
$(this).animate({
// style change back
}, 500);
});
I got the same error in this case:
var result = Db.SystemLog
.Where(log =>
eventTypeValues.Contains(log.EventType)
&& (
search.Contains(log.Id.ToString())
|| log.Message.Contains(search)
|| log.PayLoad.Contains(search)
|| log.Timestamp.ToString(CultureInfo.CurrentUICulture).Contains(search)
)
)
.OrderByDescending(log => log.Id)
.Select(r => r);
After spending way too much time debugging, I figured out that error appeared in the logic expression.
The first line search.Contains(log.Id.ToString())
does work fine, but the last line that deals with a DateTime object made it fail miserably:
|| log.Timestamp.ToString(CultureInfo.CurrentUICulture).Contains(search)
Remove the problematic line and problem solved.
I do not fully understand why, but it seems as ToString() is a LINQ expression for strings, but not for Entities. LINQ for Entities deals with database queries like SQL, and SQL has no notion of ToString(). As such, we can not throw ToString() into a .Where() clause.
But how then does the first line work? Instead of ToString(), SQL have CAST
and CONVERT
, so my best guess so far is that linq for entities uses that in some simple cases. DateTime objects are not always found to be so simple...
Use grep or grepl to find observations with white spaces and sub to get rid of them.
names<-c("Ganga Din\t", "Shyam Lal", "Bulbul ")
grep("[[:space:]]+$", names)
[1] 1 3
grepl("[[:space:]]+$", names)
[1] TRUE FALSE TRUE
sub("[[:space:]]+$", "", names)
[1] "Ganga Din" "Shyam Lal" "Bulbul"
"Commercial use" in cases like this is actually just a shorthand to indicate that the product is dual-licensed under both an open source and a traditional paid-for commercial license.
Any "true" open source license will not discriminate against commercial use. (See clause 6 of the Open Source Definition.) However, open source licenses like the GPL contain clauses that are incompatible with most companies' approach to commercial software (since the GPL requires that you make your source code available if you incorporate GPL'ed code into your product).
Duel-licensing is a way to accommodate this and also provides a revenue stream for the company providing the software. For users that don't mind the restrictions of the GPL and don't need support, the product is available under an open source license. For users for whom the GPL's restrictions would be incompatible with their business model, and for users that do need support, a commercial license is available.
You gave the specific example of the Screwturn wiki, which is dual-licensed under the GPL and a commercial license. Under the terms of the GPL (i.e., without getting a "commercial" license), you can do the following:
In other words, there's a lot that you can do without getting a commercial license. This is especially true for web-based software, since people can use web-based software without it being distributed to them. Screwturn's web site even acknowledges this: they state that the commercial license is for "either integrating it in a commercial application, or using it in an enterprise environment where free software is not allowed," not for any use related to commerce.
All of the preceding is merely my understanding and is not intended to be legal advice. Consult your lawyer to be certain.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("form").submit(function(e){
e.preventDefault();
var name = $("#name").val();
var amount =$("#number").val();
var gst=(amount)*(0.18);
gst=Math.round(gst);
var total=parseInt(amount)+parseInt(gst);
$(".myTable tbody").append("<tr><td></td><td>"+name+"</td><td>"+amount+"</td><td>"+gst+"</td><td>"+total+"</td></tr>");
$("#name").val('');
$("#number").val('');
$(".myTable").find("tbody").find("tr").each(function(i){
$(this).closest('tr').find('td:first-child').text(i+1);
});
$("#formdata").on('submit', '.myTable', function () {
var sum = 0;
$(".myTable tbody tr").each(function () {
var getvalue = $(this).val();
if ($.isNumeric(getvalue))
{
sum += parseFloat(getvalue);
}
});
$(".total").text(sum);
});
});
});
</script>
<style>
#formdata{
float:left;
width:400px;
}
</style>
</head>
<body>
<form id="formdata">
<span>Product Name</span>
<input type="text" id="name">
<br>
<span>Product Amount</span>
<input type="text" id="number">
<br>
<br>
<center><button type="submit" class="adddata">Add</button></center>
</form>
<br>
<br>
<table class="myTable" border="1px" width="300px">
<thead><th>s.no</th><th>Name</th><th>Amount</th><th>Gst</th><th>NetTotal</th></thead>
<tbody></tbody>
<tfoot>
<tr>
<td></td>
<td></td>
<td></td>
<td class="total"></td>
<td class="total"></td>
</tr>
</tfoot>
</table>
</body>
You could use the rename() function :
rename('foo/test.php', 'bar/test.php');
This however will move the file not copy
The NumberFormat class will only parse the string until it reaches a non-parseable character:
((Number)NumberFormat.getInstance().parse("123e")).intValue()
will hence return 123.
In SQL server you would use TOP together with ROW_NUMBER()
Select Table Column Name where you want to get default value of Current date
ALTER TABLE
[dbo].[Table_Name]
ADD CONSTRAINT [Constraint_Name]
DEFAULT (getdate()) FOR [Column_Name]
Alter Table Query
Alter TABLE [dbo].[Table_Name](
[PDate] [datetime] Default GetDate())
I find that when i choose option of Project->Properties->Linker->System->SubSystem->Console(/subsystem:console), and then make sure include the function : int _tmain(int argc,_TCHAR* argv[]){return 0} all of the compiling ,linking and running will be ok;
With the Python library pandas
, you can easily create column names and infer data types from a csv file.
from sqlalchemy import create_engine
import pandas as pd
engine = create_engine('postgresql://user:pass@localhost/db_name')
df = pd.read_csv('/path/to/csv_file')
df.to_sql('pandas_db', engine)
The if_exists
parameter can be set to replace or append to an existing table, e.g. df.to_sql('pandas_db', engine, if_exists='replace')
. This works for additional input file types as well, docs here and here.
You can use
DispatchQueue.main.asyncAfter(deadline: .now() + .microseconds(100)) {
// Code
}
Another variation you can try is(expanding @mnel's answer) if you have many temp'x'.
here "n" could be the number of temp variables present
rm(list = c(paste("temp",c(1:n),sep="")))
try converting the date first.
$date = "2012-08-06";
mysql_query("INSERT INTO data_table (title, date_of_event)
VALUES('" . $_POST['post_title'] . "',
'" . $date . "')")
or die(mysql_error());
I think the best option in Terms of performance (or in any terms) is to Distinct using the The IEqualityComparer interface.
Although implementing each time a new comparer for each class is cumbersome and produces boilerplate code.
So here is an extension method which produces a new IEqualityComparer on the fly for any class using reflection.
Usage:
var filtered = taskList.DistinctBy(t => t.TaskExternalId).ToArray();
Extension Method Code
public static class LinqExtensions
{
public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> items, Func<T, TKey> property)
{
GeneralPropertyComparer<T, TKey> comparer = new GeneralPropertyComparer<T,TKey>(property);
return items.Distinct(comparer);
}
}
public class GeneralPropertyComparer<T,TKey> : IEqualityComparer<T>
{
private Func<T, TKey> expr { get; set; }
public GeneralPropertyComparer (Func<T, TKey> expr)
{
this.expr = expr;
}
public bool Equals(T left, T right)
{
var leftProp = expr.Invoke(left);
var rightProp = expr.Invoke(right);
if (leftProp == null && rightProp == null)
return true;
else if (leftProp == null ^ rightProp == null)
return false;
else
return leftProp.Equals(rightProp);
}
public int GetHashCode(T obj)
{
var prop = expr.Invoke(obj);
return (prop==null)? 0:prop.GetHashCode();
}
}
No need to do that mess.
use python-lambda
https://github.com/nficano/python-lambda
with single command pylambda deploy
it will automatically deploy your function
public boolean compareMap(Map<String, String> map1, Map<String, String> map2) {
if (map1 == null || map2 == null)
return false;
for (String ch1 : map1.keySet()) {
if (!map1.get(ch1).equalsIgnoreCase(map2.get(ch1)))
return false;
}
for (String ch2 : map2.keySet()) {
if (!map2.get(ch2).equalsIgnoreCase(map1.get(ch2)))
return false;
}
return true;
}
For anyone who wants to pass in arbitrary strings which are exact matches (And not worry about escaping regex special characters), git log takes a --fixed-strings option
git log --fixed-strings --grep "$SEARCH_TERM"
For SharePoint 2016
%COMMONPROGRAMFILES%\Microsoft Shared\Web Server Extensions\15\Logs
For SharePoint 2013
%COMMONPROGRAMFILES%\Microsoft Shared\Web Server Extensions\15\Logs
For SharePoint 2010
%COMMONPROGRAMFILES%\Microsoft Shared\Web Server Extensions\14\Logs
For SharePoint 2007
%COMMONPROGRAMFILES%\Microsoft Shared\Web Server Extensions\12\Logs
Note: The sharePoint Trace log path can be changed by opening Central Administration > Monitoring > Reporting > Configure Diagnostic Logs
For more details check SHAREPOINT ULS VIEWER
I simply use this jQuery trick:
$("a:focus").attr('data-id');
It gets the focused a
element and gets the data-id
attribute from it.
If you install it directly with the community installer on windows 2008 server, it will reside on c:\ProgamData\MySql\MysqlServerVersion\my.ini
true
and false
are not meant to be strings in this context.
You want the literal true
and false
Boolean
values.
startButton.disabled = true;
startButton.disabled = false;
The reason it sort of works (disables the element) is because a non empty string is truthy. So assigning 'false'
to the disabled
property has the same effect of setting it to true
.
Whether encrypted be the same when plain text is encrypted with the same key depends of algorithm and protocol. In cryptography there is initialization vector IV: http://en.wikipedia.org/wiki/Initialization_vector that used with various ciphers makes that the same plain text encrypted with the same key gives various cipher texts.
I advice you to read more about cryptography on Wikipedia, Bruce Schneier http://www.schneier.com/books.html and "Beginning Cryptography with Java" by David Hook. The last book is full of examples of usage of http://www.bouncycastle.org library.
If you are interested in cryptography the there is CrypTool: http://www.cryptool.org/ CrypTool is a free, open-source e-learning application, used worldwide in the implementation and analysis of cryptographic algorithms.
As others have written, you can cast null to everything. Normally, you wouldn't need that, you can write:
String nullString = null;
without putting the cast there.
But there are occasions where such casts make sense:
a) if you want to make sure that a specific method is called, like:
void foo(String bar) { ... }
void foo(Object bar) { ... }
then it would make a difference if you type
foo((String) null) vs. foo(null)
b) if you intend to use your IDE to generate code; for example I am typically writing unit tests like:
@Test(expected=NullPointerException.class)
public testCtorWithNullWhatever() {
new MyClassUnderTest((Whatever) null);
}
I am doing TDD; this means that the class "MyClassUnderTest" probably doesn't exist yet. By writing down that code, I can then use my IDE to first generate the new class; and to then generate a constructor accepting a "Whatever" argument "out of the box" - the IDE can figure from my test that the constructor should take exactly one argument of type Whatever.
Use the pandas.DataFrame.round() method like this:
df = df.round({'value1': 0})
Any columns not included will be left as is.
The following constructor, JLabel(String, int)
, allow you to specify the horizontal alignment of the label.
JLabel label = new JLabel("The Label", SwingConstants.CENTER);
You use a self join when a table references data in itself.
E.g., an Employee
table may have a SupervisorID
column that points to the employee that is the boss of the current employee.
To query the data and get information for both people in one row, you could self join like this:
select e1.EmployeeID,
e1.FirstName,
e1.LastName,
e1.SupervisorID,
e2.FirstName as SupervisorFirstName,
e2.LastName as SupervisorLastName
from Employee e1
left outer join Employee e2 on e1.SupervisorID = e2.EmployeeID
As stated above, it happens due to the conflict of $ variable.
I resolved this issue by reserving a secondary variable for jQuery with no conflict.
var $j = jQuery.noConflict();
and then use it anywhere
$j( "div" ).hide();
more details can be found here
Bash supports arithmetic expansion with $(( expression ))
. For example:
$ echo $(( 5 * 5 ))
25
A number of utilities provide arithmetic, including bc and expr.
$ echo '5 * 5' | /usr/bin/bc
25
$ /usr/bin/expr 5 \* 5
25
In React 16.8+, using functional components, you would do
import React from 'react';
import { Button, Linking } from 'react-native';
const ExternalLinkBtn = (props) => {
return <Button
title={props.title}
onPress={() => {
Linking.openURL(props.url)
.catch(err => {
console.error("Failed opening page because: ", err)
alert('Failed to open page')
})}}
/>
}
export default function exampleUse() {
return (
<View>
<ExternalLinkBtn title="Example Link" url="https://example.com" />
</View>
)
}
To get it to recognize the raw file, make sure you create it, and add it as a raw resource file. Then go to build.gradle file and add this block of code.
sourceSets {
main {
assets.srcDirs = ['/res/raw']
}
}
You can use <progress>
element in HTML5. See this page for source code and live demo. http://purpledesign.in/blog/super-cool-loading-bar-html5/
here is the progress element...
<progress id="progressbar" value="20" max="100"></progress>
this will have the loading value starting from 20. Of course only the element wont suffice. You need to move it as the script loads. For that we need JQuery. Here is a simple JQuery script that starts the progress from 0 to 100 and does something in defined time slot.
<script>
$(document).ready(function() {
if(!Modernizr.meter){
alert('Sorry your brower does not support HTML5 progress bar');
} else {
var progressbar = $('#progressbar'),
max = progressbar.attr('max'),
time = (1000/max)*10,
value = progressbar.val();
var loading = function() {
value += 1;
addValue = progressbar.val(value);
$('.progress-value').html(value + '%');
if (value == max) {
clearInterval(animate);
//Do Something
}
if (value == 16) {
//Do something
}
if (value == 38) {
//Do something
}
if (value == 55) {
//Do something
}
if (value == 72) {
//Do something
}
if (value == 1) {
//Do something
}
if (value == 86) {
//Do something
}
};
var animate = setInterval(function() {
loading();
}, time);
};
});
</script>
Add this to your HTML file.
<div class="demo-wrapper html5-progress-bar">
<div class="progress-bar-wrapper">
<progress id="progressbar" value="0" max="100"></progress>
<span class="progress-value">0%</span>
</div>
</div>
Hope this will give you a start.
You can do that using the SimpleDateFormat
class.
SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dates=formatter.format(mydate);
//mydate is your date object
You can pass a config object to axios like:
axios({
method: 'post',
url: '....',
params: {'HTTP_CONTENT_LANGUAGE': self.language},
headers: {'header1': value}
})
To do this, I had to come up with an intermediate data structure:
class KeyDataPoint {
String key;
DateTime timestamp;
Number data;
// obvious constructor and getters
}
With this in place, the approach is to "flatten" each MultiDataPoint into a list of (timestamp, key, data) triples and stream together all such triples from the list of MultiDataPoint.
Then, we apply a groupingBy
operation on the string key in order to gather the data for each key together. Note that a simple groupingBy
would result in a map from each string key to a list of the corresponding KeyDataPoint triples. We don't want the triples; we want DataPoint instances, which are (timestamp, data) pairs. To do this we apply a "downstream" collector of the groupingBy
which is a mapping
operation that constructs a new DataPoint by getting the right values from the KeyDataPoint triple. The downstream collector of the mapping
operation is simply toList
which collects the DataPoint objects of the same group into a list.
Now we have a Map<String, List<DataPoint>>
and we want to convert it to a collection of DataSet objects. We simply stream out the map entries and construct DataSet objects, collect them into a list, and return it.
The code ends up looking like this:
Collection<DataSet> convertMultiDataPointToDataSet(List<MultiDataPoint> multiDataPoints) {
return multiDataPoints.stream()
.flatMap(mdp -> mdp.getData().entrySet().stream()
.map(e -> new KeyDataPoint(e.getKey(), mdp.getTimestamp(), e.getValue())))
.collect(groupingBy(KeyDataPoint::getKey,
mapping(kdp -> new DataPoint(kdp.getTimestamp(), kdp.getData()), toList())))
.entrySet().stream()
.map(e -> new DataSet(e.getKey(), e.getValue()))
.collect(toList());
}
I took some liberties with constructors and getters, but I think they should be obvious.
Consider this example:
public class StringSplit {
public static void main(String args[]) throws Exception{
String testString = "Real|How|To|||";
System.out.println
(java.util.Arrays.toString(testString.split("\\|")));
// output : [Real, How, To]
}
}
The result does not include the empty strings between the "|" separator. To keep the empty strings :
public class StringSplit {
public static void main(String args[]) throws Exception{
String testString = "Real|How|To|||";
System.out.println
(java.util.Arrays.toString(testString.split("\\|", -1)));
// output : [Real, How, To, , , ]
}
}
For more details go to this website: http://www.rgagnon.com/javadetails/java-0438.html
When you want to add a javascript object to the form data, you can use the following code
var data = {name1: 'value1', name2: 'value2'};
var postData = $('#my-form').serializeArray();
for (var key in data) {
if (data.hasOwnProperty(key)) {
postData.push({name:key, value:data[key]});
}
}
$.post(url, postData, function(){});
Or if you add the method serializeObject(), you can do the following
var data = {name1: 'value1', name2: 'value2'};
var postData = $('#my-form').serializeObject();
$.extend(postData, data);
$.post(url, postData, function(){});
Here are the instructions for Windows users on connecting to a RPi by using just an Ethernet cable and a DHCP server. There is no need for a cross over cable, as the RPi can handle it. I have a blog post that documents this with pictures here which may be easier to follow.
Downloads
Download the DHCP Server for Windows (download link is here). Unzip the zip file and open the dhcpwiz application, which will configure the DHCP server.
DHCP Server Configuration
Hit next on the first screen.
On the second screen, look for a "Local Area Connection" row and verify its IP address is 0.0.0.0
and its status is enabled
. Connect the Ethernet cable from the RPi to your laptop, and turn on the Pi. Hit refresh on this screen until the IP address changes to 169.254.*.*
. If it is anything else then you should alter your network settings for the Local Area Connection (make sure it is not a static IP/DNS). Click on this Local Area Connection row and hit next.
Check HTTP (Web Server)
. This makes it much more easy to locate the RPi's IP address. Hit Next.
Take the defaults and hit Next until you get to the Writing the INI file
screen. Check Overwrite existing file
and hit the Write INI file
button. Then hit Next.
On the final screen, check Run DHCP server immediately
and hit `Finish.
DHCP Server and Obtaining the IP Address of your Raspberry PI
This launches the actual DHCP server, using the configuration you just created in the previous wizard. Click the Continue as tray app
button, and the DHCP server will be minimized to your system tray.
Anywhere from 1 second to 5 minutes from now you will see an alert on the system tray with your laptop and your RPi's new IP address. This alert is really quick and you will probably miss it. Normally your RPi's IP is 169.254.0.2
, but it could be *.01
or even something else. It is easier to access the DHCP server's web UI at http://localhost/dhcpstatus.xml. This will list the hostname as "raspberrypi" with its IP address.
Now you can putty or remote desktop into your RPi, and configure its wireless settings or whatever you want to do.
Trouble shooting
This can be somewhat finicky. I've had my connection appear to drop and have been unable to SSH back in using the IP address. Normally, I can restart the Pi and get the IP address again. Sometimes I have to restart both the RPi and the DHCP server. Sometimes I have to do this multiple times. At one point when I wasn't getting a connection for 15 minutes, I copied all of the files in the dhcpsrv2.5.1 folder to a new folder and tried again; it immediately worked.
In my case I solved this problem using this following CheckBox attribute in the XML:
*
android:paddingLeft="@dimen/activity_horizontal_margin"
*
In merge-sort, the general algorithm is:
At the top level, merging the 2 sorted sub-arrays involves dealing with N elements.
One level below that, each iteration of step 3 involves dealing with N/2 elements, but you have to repeat this process twice. So you're still dealing with 2 * N/2 == N elements.
One level below that, you're merging 4 * N/4 == N elements, and so on. Every depth in the recursive stack involves merging the same number of elements, across all calls for that depth.
Consider the quick-sort algorithm instead:
At the top level, you're dealing with an array of size N. You then pick one pivot point, put it in its correct position, and can then ignore it completely for the rest of the algorithm.
One level below that, you're dealing with 2 sub-arrays that have a combined size of N-1 (ie, subtract the earlier pivot point). You pick a pivot point for each sub-array, which comes up to 2 additional pivot points.
One level below that, you're dealing with 4 sub-arrays with combined size N-3, for the same reasons as above.
Then N-7... Then N-15... Then N-32...
The depth of your recursive stack remains approximately the same (logN). With merge-sort, you're always dealing with a N-element merge, across each level of the recursive stack. With quick-sort though, the number of elements that you're dealing with diminishes as you go down the stack. For example, if you look at the depth midway through the recursive stack, the number of elements you're dealing with is N - 2^((logN)/2)) == N - sqrt(N).
Disclaimer: On merge-sort, because you divide the array into 2 exactly equal chunks each time, the recursive depth is exactly logN. On quick-sort, because your pivot point is unlikely to be exactly in the middle of the array, the depth of your recursive stack may be slightly greater than logN. I haven't done the math to see how big a role this factor and the factor described above, actually play in the algorithm's complexity.
C does not have its own String data type like Java.
Only we can declare String datatype in C using character array or character pointer For example :
char message[10];
or
char *message;
But you need to declare at least:
char message[14];
to copy "Hello, world!" into message variable.
You can bypass https using below commands:
npm config set strict-ssl false
or set the registry URL from https or http like below:
npm config set registry="http://registry.npmjs.org/"
However, Personally I believe bypassing https is not the real solution, but we can use it as a workaround.
I had to restart my queue worker using php artisan queue:restart
after running php artisan key:generate
to get jobs working.
I think it should be the case. To erase the character, you should use replace(".", "")
instead.
Simple way to differentiate UTF-8 and UTF-16 is to identify commonalities between them.
Other than sharing same unicode number for given character, each one is their own format.
UTF-8 try to represent, every unicode number given to character with one byte(If it is ASCII), else 2 two bytes, else 4 bytes and so on...
UTF-16 try to represent, every unicode number given to character with two byte to start with. If two bytes are not sufficient, then uses 4 bytes. IF that is also not sufficient, then uses 6 bytes.
Theoretically, UTF-16 is more space efficient, but in practical UTF-8 is more space efficient as most of the characters(98% of data) for processing are ASCII and UTF-8 try to represent them with single byte and UTF-16 try to represent them with 2 bytes.
Also, UTF-8 is superset of ASCII encoding. So every app that expects ASCII data would also accepted by UTF-8 processor. This is not true for UTF-16. UTF-16 could not understand ASCII, and this is big hurdle for UTF-16 adoption.
Another point to note is, all UNICODE as of now could be fit in 4 bytes of UTF-8 maximum(Considering all languages of world). This is same as UTF-16 and no real saving in space compared to UTF-8 ( https://stackoverflow.com/a/8505038/3343801 )
So, people use UTF-8 where ever possible.
None of the answers here quite hit the nail on the head.
How to store a datetime in MySQL with timezone info
Use two columns: DATETIME
, and a VARCHAR
to hold the time zone information, which may be in several forms:
A timezone or location such as America/New_York
is the highest data fidelity.
A timezone abbreviation such as PST
is the next highest fidelity.
A time offset such as -2:00
is the smallest amount of data in this regard.
Some key points:
TIMESTAMP
because it's limited to the year 2038, and MySQL relates it to the server timezone, which is probably undesired.INT
field, because there are half-hour and quarter-hour offsets.If it's important for your use case to have MySQL compare or sort these dates chronologically, DATETIME
has a problem:
'2009-11-10 11:00:00 -0500'
is before '2009-11-10 10:00:00 -0700'
in terms of "instant in time", but they would sort the other way when inserted into a DATETIME
.
You can do your own conversion to UTC. In the above example, you would then have '2009-11-10 16:00:00'
and '2009-11-10 17:00:00'
respectively, which would sort correctly. When retrieving the data, you would then use the timezone info to revert it to its original form.
One recommendation which I quite like is to have three columns:
local_time DATETIME
utc_time DATETIME
time_zone VARCHAR(X)
where X is appropriate for what kind of data you're storing there. (I would choose 64 characters for timezone/location.)An advantage to the 3-column approach is that it's explicit: with a single DATETIME
column, you can't tell at a glance if it's been converted to UTC before insertion.
Regarding the descent of accuracy through timezone/abbreviation/offset:
America/Juneau
, you can know accurately what the wall clock time is for them at any point in the past or future (barring changes to the way Daylight Savings is handled in that location). The start/end points of DST, and whether it's used at all, are dependent upon location, so this is the only reliable way.-0700
, you will be unable to predict a wall clock time in the past or future. For example, in the United States, Colorado and Arizona both use MST, but Arizona doesn't observe DST. So if the user uploads his cat photo at 14:00 -0700
during the winter months, was he in Arizona or California? If you added six months exactly to that date, would it be 14:00
or 13:00
for the user?These things are important to consider when your application has time, dates, or scheduling as core function.
References:
Here is is the trick:
Here is your 'PHP' to use that variable:
<?php
$name = 'PHP variable';
echo '<script>';
echo 'var name = ' . json_encode($name) . ';';
echo '</script>';
?>
Now you have a JavaScript variable called 'name'
, and here is your JavaScript code to use that variable:
<script>
console.log("I am everywhere " + name);
</script>
Using @Adrian tips, I found a solution:
I'm using GROUP BY and COUNT. I tried to use DISTINCT with ORDER BY but I'm getting error message: "not a SELECTed expression"
select id from
(
SELECT id FROM a -- returns 1,4,2,3
UNION ALL -- changed to ALL
SELECT id FROM b -- returns 2,1
)
GROUP BY id ORDER BY count(id);
Thanks Adrian and this blog.
It's more flexible and simple way to use pipe
method.
var fs = require('fs');
var http = require('http');
http.createServer(function(request, response) {
response.writeHead(200, {'Content-Type': 'text/html'});
var file = fs.createReadStream('index.html');
file.pipe(response);
}).listen(8080);
console.log('listening on port 8080...');
opened wamp/bin/apache/apache2.4.4/bin/php config.. wamp/bin/php/php5.4.16/php conf settings, php-ini production, php-ini dev, phpForApache find extension=php_openssl.dll and uncomment by removing ;
How about using os.kill? See the docs here: http://docs.python.org/library/os.html#os.kill
CTRL+Space
It depends on what do you mean by python functions? if they were written in cpython you can not directly call them you will have to use JNI, but if they were written in Jython you can easily call them from java, as jython ultimately generates java byte code.
Now when I say written in cpython or jython it doesn't make much sense because python is python and most code will run on both implementations unless you are using specific libraries which relies on cpython or java.
The easiest way to use PhantomJS in python is via Selenium. The simplest installation method is
npm -g install phantomjs-prebuilt
After installation, you may use phantom as simple as:
from selenium import webdriver
driver = webdriver.PhantomJS() # or add to your PATH
driver.set_window_size(1024, 768) # optional
driver.get('https://google.com/')
driver.save_screenshot('screen.png') # save a screenshot to disk
sbtn = driver.find_element_by_css_selector('button.gbqfba')
sbtn.click()
If your system path environment variable isn't set correctly, you'll need to specify the exact path as an argument to webdriver.PhantomJS()
. Replace this:
driver = webdriver.PhantomJS() # or add to your PATH
... with the following:
driver = webdriver.PhantomJS(executable_path='/usr/local/lib/node_modules/phantomjs/lib/phantom/bin/phantomjs')
References:
Output debug info to STDERR:
$curlHandler = curl_init();
curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://postman-echo.com/get?foo=bar',
CURLOPT_RETURNTRANSFER => true,
/**
* Specify debug option
*/
CURLOPT_VERBOSE => true,
]);
curl_exec($curlHandler);
curl_close($curlHandler);
Output debug info to file:
$curlHandler = curl_init();
curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://postman-echo.com/get?foo=bar',
CURLOPT_RETURNTRANSFER => true,
/**
* Specify debug option.
*/
CURLOPT_VERBOSE => true,
/**
* Specify log file.
* Make sure that the folder is writable.
*/
CURLOPT_STDERR => fopen('./curl.log', 'w+'),
]);
curl_exec($curlHandler);
curl_close($curlHandler);
See https://github.com/andriichuk/php-curl-cookbook#debug-request
It's Easy.
Example from MSDN:
public static void Main()
{
// Use the file name to load the assembly into the current
// application domain.
Assembly a = Assembly.Load("example");
// Get the type to use.
Type myType = a.GetType("Example");
// Get the method to call.
MethodInfo myMethod = myType.GetMethod("MethodA");
// Create an instance.
object obj = Activator.CreateInstance(myType);
// Execute the method.
myMethod.Invoke(obj, null);
}
Here's a reference link
bit late but here is working solution for me
var myBaseProperty = (typeof(BaseClass)).GetProperties();//get base code properties
var allProperty = entity.GetProperties()[0].DeclaringType.GetProperties();//get derived class property plus base code as it is derived from it
var declaredClassProperties = allProperty.Where(x => !myBaseProperty.Any(l => l.Name == x.Name)).ToList();//get the difference
In above mention code I am getting the properties difference between my base class and derived class list
or select Edit Scheme
from Product
> Scheme
Menu
select Enable Zombie Objects
form the Diagnostics
tab
As alternative, if you prefer .xcconfig
files you can read this article https://therealbnut.wordpress.com/2012/01/01/setting-xcode-4-0-environment-variables-from-a-script/
I used hasOwnProperty('club')
var myobj = { "regatta_name":"ProbaRegatta",
"country":"Congo",
"status":"invited"
};
if ( myobj.hasOwnProperty("club"))
// do something with club (will be false with above data)
var data = myobj.club;
if ( myobj.hasOwnProperty("status"))
// do something with the status field. (will be true with above ..)
var data = myobj.status;
works in all current browsers.
In my case, after 30 minutes changing permissions, got into account that the XLSX file I was trying to transfer was still open in Excel.
In my case it was
username : root
password : mysql
Using : Wamp server 3.1.0
Here is one more approach to achieve this
we can use presence
with select
cities = ["Kathmandu", "Pokhara", "", "Dharan", nil, "Butwal"]
cities.select(&:presence)
["Kathmandu", "Pokhara", "Dharan", "Butwal"]
You were able to use the PHP Horde_Text_Diff package.
However this package is no longer available.
If you start tinkering with VirtualBox network settings, watch out for this: you might make new network adapters (eth1, eth2), yet have your /etc/network/interfaces
still configured for eth0.
Diagnose:
ethtool -i eth0
Cannot get driver information: no such device
Find your interfaces:
ls /sys/class/net
eth1 eth2 lo
Fix it:
Edit /etc/networking/interfaces
and replace eth0 with the appropriate interface name (e.g eth1, eth2, etc.)
:%s/eth0/eth2/g
"N/A" is not a string it is an error, try this:
=if(ISNA(A1),C1)
you have to place this fomula in cell B1 so it will get the value of your formula
The correct sizes are as following:
1)58x58
2)80x80
3)120x120
4)180x180
I had a similar problem.
I think the problem is that when you try to enclose two or more functions that deals with an array type of variable, php will return an error.
Let's say for example this one.
$data = array('key1' => 'Robert', 'key2' => 'Pedro', 'key3' => 'Jose');
// This function returns the last key of an array (in this case it's $data)
$lastKey = array_pop(array_keys($data));
// Output is "key3" which is the last array.
// But php will return “Strict Standards: Only variables should
// be passed by reference” error.
// So, In order to solve this one... is that you try to cut
// down the process one by one like this.
$data1 = array_keys($data);
$lastkey = array_pop($data1);
echo $lastkey;
There you go!
You can use Amazon Corretto. It is free to use multiplatform, production-ready distribution of the OpenJDK. It comes with long-term support that will include performance enhancements and security fixes. Check the installation instructions here.
You can also check Zulu from Azul.
One more thing I like to highlight here is both Amazon Corretto and Zulu are TCK Compliant. You can see the OpenJDK builds comparison here and here.
You can set the image to be background image and have a transparent foreground image.
For quick readers:
Don’t ever use the types Number, String, Boolean, Symbol, or Object These types refer to non-primitive boxed objects that are almost never used appropriately in JavaScript code.
source: https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html
Here is a version of xperroni's answer which is a bit more complete. It skips script and style sections and translates charrefs (e.g., ') and HTML entities (e.g., &).
It also includes a trivial plain-text-to-html inverse converter.
"""
HTML <-> text conversions.
"""
from HTMLParser import HTMLParser, HTMLParseError
from htmlentitydefs import name2codepoint
import re
class _HTMLToText(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self._buf = []
self.hide_output = False
def handle_starttag(self, tag, attrs):
if tag in ('p', 'br') and not self.hide_output:
self._buf.append('\n')
elif tag in ('script', 'style'):
self.hide_output = True
def handle_startendtag(self, tag, attrs):
if tag == 'br':
self._buf.append('\n')
def handle_endtag(self, tag):
if tag == 'p':
self._buf.append('\n')
elif tag in ('script', 'style'):
self.hide_output = False
def handle_data(self, text):
if text and not self.hide_output:
self._buf.append(re.sub(r'\s+', ' ', text))
def handle_entityref(self, name):
if name in name2codepoint and not self.hide_output:
c = unichr(name2codepoint[name])
self._buf.append(c)
def handle_charref(self, name):
if not self.hide_output:
n = int(name[1:], 16) if name.startswith('x') else int(name)
self._buf.append(unichr(n))
def get_text(self):
return re.sub(r' +', ' ', ''.join(self._buf))
def html_to_text(html):
"""
Given a piece of HTML, return the plain text it contains.
This handles entities and char refs, but not javascript and stylesheets.
"""
parser = _HTMLToText()
try:
parser.feed(html)
parser.close()
except HTMLParseError:
pass
return parser.get_text()
def text_to_html(text):
"""
Convert the given text to html, wrapping what looks like URLs with <a> tags,
converting newlines to <br> tags and converting confusing chars into html
entities.
"""
def f(mo):
t = mo.group()
if len(t) == 1:
return {'&':'&', "'":''', '"':'"', '<':'<', '>':'>'}.get(t)
return '<a href="%s">%s</a>' % (t, t)
return re.sub(r'https?://[^] ()"\';]+|[&\'"<>]', f, text)
On my projects i give all rows the class "borders" which I want it to display more like a table with even borders. Giving each child element a border on the bottom and right and the first element of each row a left border will make all of your boxes have an even border:
First give all of the rows children a border on the right and bottom
.borders div{
border-right:1px solid #999;
border-bottom:1px solid #999;
}
Next give the first child of each or a left border
.borders div:first-child{
border-left:
1px solid #999;
}
Last make sure to clear the borders for their child elements
.borders div > div{
border:0;
}
HTML:
<div class="row borders">
<div class="col-xs-5 col-md-2">Email</div>
<div class="col-xs-7 col-md-4">[email protected]</div>
<div class="col-xs-5 col-md-2">Phone</div>
<div class="col-xs-7 col-md-4">555-123-4567</div>
</div>
var hello = $('.right') // or var hello = document.getElementByClassName('right')
var bye = $('.right1')
hello.onmouseover = function()
{
bye.style.visibility = 'visible'
}
hello.onmouseout = function()
{
bye.style.visibility = 'hidden'
}
Ok I actually found the answer but thought I would 'import' the question into SO anyway
String[] files = new String[0];
or
int[] files = new int[0];
Restart your redis server.
brew services restart redis
.sudo service redis restart
/ sudo systemctl restart redis
services.msc
, Enter -> Search for Redis
then click on restart
. I personally had this issue after upgrading redis with Brew (brew upgrade
).
After rebooting the laptop, it immediately worked.
Just a side info, is_integer
is doing internally:
import math
isInteger = (math.floor(x) == x)
Not exactly in python, but the cpython implementation is implemented as mentioned above.
This might due to merge conflict same as mine, try to change local.properties for me it was wrong location for android sdk as it was override from other machine ndk.dir=/Users/???/Library/Android/sdk/ndk-bundle sdk.dir=/Users/???/Library/Android/sdk
then rebuild
if someone facing issue of CORS not working in mobile browser or mobile applications, you can set ALLOWED_HOSTS = ["your host ip"] in backend servers where your rest api exists, here your host ip is external ip to access ionic , like External: http://192.168.1.120:8100
After that in ionic type script make post or get using IP of backened server
in my case i used django rest framwork and i started server as:- python manage.py runserver 192.168.1.120:8000
and used this ip in ionic get and post calls of rest api
My Angular 2 project doesn't have the "main.ts" file mentioned other answers, but it does have a "boot.ts" file, which seems to be about the same thing. (The difference is probably due to different versions of Angular.)
Adding these two lines after the last import
directive in "boot.ts" worked for me:
import { enableProdMode } from "@angular/core";
enableProdMode();
check if its not a issue with umask
if (!function_exists('mkdir_r')) {
/**
* create directory recursively
* @param $dirName
* @param int $rights
* @param string $dir_separator
* @return bool
*/
function mkdir_r($dirName, $rights = 0744, $dir_separator = DIRECTORY_SEPARATOR) {
$dirs = explode($dir_separator, $dirName);
$dir = '';
$created = false;
foreach ($dirs as $part) {
$dir .= $part . $dir_separator;
if (!is_dir($dir) && strlen($dir) > 0) {
$created = mkdir($dir, $rights);
}
}
return $created;
}
}
if (!function_exists('ensure_dir')) {
/**
* ensure directory exist if not create
* @param $dir_path
* @param int $mode
* @param bool $use_mask
* @param int $mask
* @return bool
*/
function ensure_dir($dir_path, $mode = 0744, $use_mask = true, $mask = 0002) {
// set mask
$old_mask = $use_mask && $mask != null
? umask($mask)
: null;
try {
return is_dir($dir_path) || mkdir_r($dir_path, $mode);
} finally {
if ($use_mask && $old_mask != null) {
// restore original
umask($old_mask);
}
}
}
}
I used SSH.Net in a project a while ago and was very happy with it. It also comes with a good documentation with lots of samples on how to use it.
The original package website can be still found here, including the documentation (which currently isn't available on GitHub).
For your case the code would be something like this.
using (var client = new SshClient("hostnameOrIp", "username", "password"))
{
client.Connect();
client.RunCommand("etc/init.d/networking restart");
client.Disconnect();
}
This issue is related to Byte Order Mark in the JSON file. JSON file is not encoded as UTF8 encoding data when saved. Using File.ReadAllText(pathFile)
fix this issue.
When we are operating on Byte data and converting that to string and then passing to JsonConvert.DeserializeObject, we can use UTF32 encoding to get the string.
byte[] docBytes = File.ReadAllBytes(filePath);
string jsonString = Encoding.UTF32.GetString(docBytes);
The standard ERB templating system may work for your scenario.
def merge_into_string(animal, second_animal, action)
template = 'The <%=animal%> <%=action%> the <%=second_animal%>'
ERB.new(template).result(binding)
end
merge_into_string('tiger', 'deer', 'eats')
=> "The tiger eats the deer"
merge_into_string('bird', 'worm', 'finds')
=> "The bird finds the worm"
There is an open source program that I find online it uses openssl to encrypt and decrypt files. It does this with a single password. The great thing about this open source script is that it deletes the original unencrypted file by shredding the file. But the dangerous thing about is once the original unencrypted file is gone you have to make sure you remember your password otherwise they be no other way to decrypt your file.
Here the link it is on github
https://github.com/EgbieAnderson1/linux_file_encryptor/blob/master/file_encrypt.py
In your while statement just replace mysql_fetch_row
with mysql_fetch_array
or mysql_fetch_assoc
... whichever works...
In MySQL you can do this:
INSERT IGNORE INTO Table2(Id, Name) SELECT Id, Name FROM Table1
Does SQL Server have anything similar?
This should be performant, thread-safe and flexible enough for many uses:
#include <random>
#include <iostream>
template<typename Numeric, typename Generator = std::mt19937>
Numeric random(Numeric from, Numeric to)
{
thread_local static Generator gen(std::random_device{}());
using dist_type = typename std::conditional
<
std::is_integral<Numeric>::value
, std::uniform_int_distribution<Numeric>
, std::uniform_real_distribution<Numeric>
>::type;
thread_local static dist_type dist;
return dist(gen, typename dist_type::param_type{from, to});
}
int main(int, char*[])
{
for(auto i = 0U; i < 20; ++i)
std::cout << random<double>(0.0, 0.3) << '\n';
}
Firstly, run the command below:
apt-get update && apt-get install procps
and then run:
ps -ef
One solution which avoids MultiIndex is to create a new datetime
column setting day = 1. Then group by this column.
df = pd.DataFrame({'Date': pd.to_datetime(['2017-10-05', '2017-10-20', '2017-10-01', '2017-09-01']),
'Values': [5, 10, 15, 20]})
# normalize day to beginning of month, 4 alternative methods below
df['YearMonth'] = df['Date'] + pd.offsets.MonthEnd(-1) + pd.offsets.Day(1)
df['YearMonth'] = df['Date'] - pd.to_timedelta(df['Date'].dt.day-1, unit='D')
df['YearMonth'] = df['Date'].map(lambda dt: dt.replace(day=1))
df['YearMonth'] = df['Date'].dt.normalize().map(pd.tseries.offsets.MonthBegin().rollback)
Then use groupby
as normal:
g = df.groupby('YearMonth')
res = g['Values'].sum()
# YearMonth
# 2017-09-01 20
# 2017-10-01 30
# Name: Values, dtype: int64
pd.Grouper
The subtle benefit of this solution is, unlike pd.Grouper
, the grouper index is normalized to the beginning of each month rather than the end, and therefore you can easily extract groups via get_group
:
some_group = g.get_group('2017-10-01')
Calculating the last day of October is slightly more cumbersome. pd.Grouper
, as of v0.23, does support a convention
parameter, but this is only applicable for a PeriodIndex
grouper.
An alternative to the above idea is to convert to a string, e.g. convert datetime 2017-10-XX
to string '2017-10'
. However, this is not recommended since you lose all the efficiency benefits of a datetime
series (stored internally as numerical data in a contiguous memory block) versus an object
series of strings (stored as an array of pointers).
The patch is here: https://code.ros.org/trac/opencv/attachment/ticket/862/OpenCV-2.2-nov4l1.patch
By adding #ifdef HAVE_CAMV4L
around
#include <linux/videodev.h>
in OpenCV-2.2.0/modules/highgui/src/cap_v4l.cpp
and removing || defined (HAVE_CAMV4L2)
from line 174
allowed me to compile.
https://www.w3schools.com/bootstrap/bootstrap_ref_js_modal.asp
Note: For <a>
elements, omit data-target, and use href="#modalID"
instead.
*
C++ community has heard your request :)
*
C++ 20 provides an easy way of doing it now. It gets as simple as :
#include <vector>
...
vector<int> cnt{5, 0, 2, 8, 0, 7};
std::erase(cnt, 0);
You should check out std::erase and std::erase_if.
Not only will it remove all elements of the value (here '0'), it will do it in O(n) time complexity. Which is the very best you can get.
If your compiler does not support C++ 20, you should use erase-remove idiom:
#include <algorithm>
...
vec.erase(std::remove(vec.begin(), vec.end(), 0), vec.end());
You can't have an array of a generic type. Use List
instead.
Let us assume the database character set is UTF-8, which is the recommended setting in recent versions of Oracle. In this case, some characters take more than 1 byte to store in the database.
If you define the field as VARCHAR2(11 BYTE)
, Oracle can use up to 11 bytes for storage, but you may not actually be able to store 11 characters in the field, because some of them take more than one byte to store, e.g. non-English characters.
By defining the field as VARCHAR2(11 CHAR)
you tell Oracle it can use enough space to store 11 characters, no matter how many bytes it takes to store each one. A single character may require up to 4 bytes.
This worked perfectly for me
background-repeat: no-repeat;
background-size: 100% 100%;
if you are not using model as per your question you can do like this
@Html.Hidden("hdnFlag" , new {id = "hdnFlag", value = "hdnFlag_value" })
else if you are using model (considering passing model has hdnFlag property), you can use this approch
@Html.HiddenFor(model => model.hdnFlag, new { value = Model.hdnFlag})
From the selectors specification:
Attribute values must be CSS identifiers or strings.
Identifiers cannot start with a number. Strings must be quoted.
1
is therefore neither a valid identifier nor a string.
Use "1"
(which is a string) instead.
var a = document.querySelector('a[data-a="1"]');
Here is my solution. I first create random numbers with random.uniform, format them in to string with double precision and then convert them back to float. You can adjust the precision by changing '.2f' to '.3f' etc..
import random
from decimal import Decimal
GndSpeedHigh = float(format(Decimal(random.uniform(5, 25)), '.2f'))
GndSpeedLow = float(format(Decimal(random.uniform(2, GndSpeedHigh)), '.2f'))
GndSpeedMean = float(Decimal(format(GndSpeedHigh + GndSpeedLow) / 2, '.2f')))
print(GndSpeedMean)
You can find the codes in the DB2 Information Center. Here's a definition of the -302
from the z/OS Information Center:
THE VALUE OF INPUT VARIABLE OR PARAMETER NUMBER position-number IS INVALID OR TOO LARGE FOR THE TARGET COLUMN OR THE TARGET VALUE
On Linux/Unix/Windows DB2, you'll look under SQL Messages to find your error message. If the code is positive, you'll look for SQLxxxxW
, if it's negative, you'll look for SQLxxxxN
, where xxxx is the code you're looking up.
I used the following call inside onNavigationItemSelected
:
HomeActivity.this.setTitle(item.getTitle());
You need to put the worksheet identifier in your range statements as shown below ...
Option Explicit
Dim ws As Worksheet, a As Range
Sub forEachWs()
For Each ws In ActiveWorkbook.Worksheets
Call resizingColumns
Next
End Sub
Sub resizingColumns()
ws.Range("A:A").ColumnWidth = 20.14
ws.Range("B:B").ColumnWidth = 9.71
ws.Range("C:C").ColumnWidth = 35.86
ws.Range("D:D").ColumnWidth = 30.57
ws.Range("E:E").ColumnWidth = 23.57
ws.Range("F:F").ColumnWidth = 21.43
ws.Range("G:G").ColumnWidth = 18.43
ws.Range("H:H").ColumnWidth = 23.86
ws.Range("i:I").ColumnWidth = 27.43
ws.Range("J:J").ColumnWidth = 36.71
ws.Range("K:K").ColumnWidth = 30.29
ws.Range("L:L").ColumnWidth = 31.14
ws.Range("M:M").ColumnWidth = 31
ws.Range("N:N").ColumnWidth = 41.14
ws.Range("O:O").ColumnWidth = 33.86
End Sub
Taking in consideration the other answers I would do something like this, thanks!
.table-responsive {
@include media-breakpoint-up(md) {
display: table;
}
}
I'd suggest using the stopPropagation() method as shown in the modified fiddle:
$('body').click(function() {
$(".popup").hide();
});
$('.popup').click(function(e) {
e.stopPropagation();
});
That way you can hide the popup when you click on the body, without having to add an extra if, and when you click on the popup, the event doesn't bubble up to the body by going through the popup.
If you serialize the object that you have, you can do something like this by using "System.Xml.Serialization.XmlAttributeAttribute" on every property that you want to be specified as an attribute in your model, which in my opinion is a lot easier:
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public class UserNode
{
[System.Xml.Serialization.XmlAttributeAttribute()]
public string userName { get; set; }
[System.Xml.Serialization.XmlAttributeAttribute()]
public string passWord { get; set; }
public int Age { get; set; }
public string Name { get; set; }
}
public class LoginNode
{
public UserNode id { get; set; }
}
Then you just serialize to XML an instance of LoginNode called "Login", and that's it!
Here you have a few examples to serialize and object to XML, but I would suggest to create an extension method in order to be reusable for other objects.
My Environment: Windows 10, Xampp Control Panel v3.2.4, PHP 7.3.2
Step-1: Download a suitable version for your system from here: https://pecl.php.net/package/mcrypt/1.0.3/windows
Step-2: Unzip and copy php_mcrypt.dll file to ../xampp/php/ext/
Step-3: Open ../xampp/php/php.ini file and add a line extension=php_mcrypt.dll
Step-4: Restart apache, DONE!
I ran into this issue on GKE and the reason was no credentials for docker.
Running this resolved it:
gcloud auth configure-docker
The first allocates an object with automatic storage duration, which means it will be destructed automatically upon exit from the scope in which it is defined.
The second allocated an object with dynamic storage duration, which means it will not be destructed until you explicitly use delete
to do so.
You might try using my mailer module.
from mailer import Mailer
from mailer import Message
message = Message(From="[email protected]",
To="[email protected]")
message.Subject = "An HTML Email"
message.Html = """<p>Hi!<br>
How are you?<br>
Here is the <a href="http://www.python.org">link</a> you wanted.</p>"""
sender = Mailer('smtp.example.com')
sender.send(message)
I had a similar error, which was fixed by adding:
Options FollowSymLinks
... in the apps/[app-name]/conf/httpd-app.conf
file. This is because, in my case, an .htaccess
file wants to use rewrite rules, that are not allowed with FollowSymLinks AND SymLinksIfOwnerMatch turned off.
If your conf file already has a line with Options ...
, you can just add FollowSymLinks
to the list of options. You could end up with something like this:
Options Indexes MultiViews FollowSymLinks
You have to create the colors.xml
file in the res/values
folder of your project. The code of colors.xml
is
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="orange">#ff5500</color>
<color name="white">#ffffff</color>
<color name="transparent">#00000000</color>
<color name="date_color">#999999</color>
<color name="black">#000000</color>
<color name="gray">#999999</color>
<color name="blue">#0066cc</color>
<color name="gold">#e6b121</color>
<color name="blueback">#99FFFF</color>
<color name="articlecolor">#3399FF</color>
<color name="article_title">#3399FF</color>
<color name="cachecolor">#8ad0e8</color>
</resources>
Or, you can use Colors in your application by following way
android.graphics.Color.TRANSPARENT;
Similarly
android.graphics.Color.RED;
Try this with Swift 4
buttonSection.addTarget(self, action: #selector(actionWithParam(_:)), for: .touchUpInside)
@objc func actionWithParam(sender: UIButton){
//...
}
buttonSection.addTarget(self, action: #selector(actionWithoutParam), for: .touchUpInside)
@objc func actionWithoutParam(){
//...
}
I think you're looking for the UNION clause, a la
(SELECT * from us_music where `genre` = 'punk')
UNION
(SELECT * from de_music where `genre` = 'punk')
Before you run a select query, run this:
SET SERVEROUT ON SIZE 6000
SELECT XMLAGG(XMLELEMENT(E,SUPLR_SUPLR_ID||',')).EXTRACT('//text()') "SUPPLIER"
FROM SUPPLIERS;
Edit: I have just explained logic to pair here. If anybody want to go with the complete code then see my another answer. I have answered here for logic only but I was not able to explain properly, So I have added another answer in the same thread.
Try this to do pairing:
If you are able to search the devices then this would be your next step
ArrayList<BluetoothDevice> arrayListBluetoothDevices = NEW ArrayList<BluetoothDevice>;
I am assuming that you have the list of Bluetooth devices added in the arrayListBluetoothDevices
:
BluetoothDevice bdDevice;
bdDevice = arrayListBluetoothDevices.get(PASS_THE_POSITION_TO_GET_THE_BLUETOOTH_DEVICE);
Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
Log.i("Log","Paired");
}
} catch (Exception e)
{
e.printStackTrace();
}
The createBond()
method:
public boolean createBond(BluetoothDevice btDevice)
throws Exception
{
Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
Method createBondMethod = class1.getMethod("createBond");
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
Add this line into your Receiver in the ACTION_FOUND
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
arrayListBluetoothDevices.add(device);
}