Google Maps basics
Zoom Level - zoom
0 - 19
0 lowest zoom (whole world)
19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()
So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.
protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.my_layout); Bitmap bitmap = getIntent().getParcelableExtra("image"); ImageView imageView = (ImageView) findViewById(R.id.imageview); imageView.setImageBitmap(bitmap); }
I followed this Qiita tutorial to solve my trouble.
Environment: Cordova 8.1.1
, Android Studio 3.2
, cordova-android 7.0.0
.profile
file.export PATH="/Applications/Android Studio.app/Contents/gradle/gradle-4.6/bin":$PATH
source ~/.profle
cordova build android
PS: If [email protected]
causes build error, downgrade your platform version to 6.3.0.
This code work for me. I also handled case "Never Ask Me"
In AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
In build.gradle (Module: app)
dependencies {
....
implementation "com.google.android.gms:play-services-location:16.0.0"
}
This is CurrentLocationManager.kt
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.IntentSender
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.os.CountDownTimer
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.util.Log
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.common.api.CommonStatusCodes
import com.google.android.gms.common.api.ResolvableApiException
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationServices
import com.google.android.gms.location.LocationSettingsRequest
import com.google.android.gms.location.LocationSettingsStatusCodes
import java.lang.ref.WeakReference
object CurrentLocationManager : LocationListener {
const val REQUEST_CODE_ACCESS_LOCATION = 123
fun checkLocationPermission(activity: Activity) {
if (ContextCompat.checkSelfPermission(
activity,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(
activity,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
REQUEST_CODE_ACCESS_LOCATION
)
} else {
Thread(Runnable {
// Moves the current Thread into the background
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND)
//
requestLocationUpdates(activity)
}).start()
}
}
/**
* be used in HomeActivity.
*/
const val REQUEST_CHECK_SETTINGS = 55
/**
* The number of millis in the future from the call to start().
* until the countdown is done and onFinish() is called.
*
*
* It is also the interval along the way to receive onTick(long) callbacks.
*/
private const val TWENTY_SECS: Long = 20000
/**
* Timer to get location from history when requestLocationUpdates don't return result.
*/
private var mCountDownTimer: CountDownTimer? = null
/**
* WeakReference of current activity.
*/
private var mWeakReferenceActivity: WeakReference<Activity>? = null
/**
* user's location.
*/
var currentLocation: Location? = null
@Synchronized
fun requestLocationUpdates(activity: Activity) {
if (mWeakReferenceActivity == null) {
mWeakReferenceActivity = WeakReference(activity)
} else {
mWeakReferenceActivity?.clear()
mWeakReferenceActivity = WeakReference(activity)
}
//create location request: https://developer.android.com/training/location/change-location-settings.html#prompt
val mLocationRequest = LocationRequest()
// Which your app prefers to receive location updates. Note that the location updates may be
// faster than this rate, or slower than this rate, or there may be no updates at all
// (if the device has no connectivity)
mLocationRequest.interval = 20000
//This method sets the fastest rate in milliseconds at which your app can handle location updates.
// You need to set this rate because other apps also affect the rate at which updates are sent
mLocationRequest.fastestInterval = 10000
mLocationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
//Get Current Location Settings
val builder = LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest)
//Next check whether the current location settings are satisfied
val client = LocationServices.getSettingsClient(activity)
val task = client.checkLocationSettings(builder.build())
//Prompt the User to Change Location Settings
task.addOnSuccessListener(activity) {
Log.d("CurrentLocationManager", "OnSuccessListener")
// All location settings are satisfied. The client can initialize location requests here.
// If it's failed, the result after user updated setting is sent to onActivityResult of HomeActivity.
val activity1 = mWeakReferenceActivity?.get()
if (activity1 != null) {
startRequestLocationUpdate(activity1.applicationContext)
}
}
task.addOnFailureListener(activity) { e ->
Log.d("CurrentLocationManager", "addOnFailureListener")
val statusCode = (e as ApiException).statusCode
when (statusCode) {
CommonStatusCodes.RESOLUTION_REQUIRED ->
// Location settings are not satisfied, but this can be fixed
// by showing the user a dialog.
try {
val activity1 = mWeakReferenceActivity?.get()
if (activity1 != null) {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
val resolvable = e as ResolvableApiException
resolvable.startResolutionForResult(
activity1, REQUEST_CHECK_SETTINGS
)
}
} catch (sendEx: IntentSender.SendIntentException) {
// Ignore the error.
sendEx.printStackTrace()
}
LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE -> {
// Location settings are not satisfied. However, we have no way
// to fix the settings so we won't show the dialog.
}
}
}
}
fun startRequestLocationUpdate(appContext: Context) {
val mLocationManager = appContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
if (ActivityCompat.checkSelfPermission(
appContext.applicationContext,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
) {
//Utilities.showProgressDialog(mWeakReferenceActivity.get());
if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 10000, 0f, this
)
} else {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 10000, 0f, this
)
}
}
/*Timer to call getLastKnownLocation() when requestLocationUpdates don 't return result*/
countDownUpdateLocation()
}
override fun onLocationChanged(location: Location?) {
if (location != null) {
stopRequestLocationUpdates()
currentLocation = location
}
}
override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {
}
override fun onProviderEnabled(provider: String) {
}
override fun onProviderDisabled(provider: String) {
}
/**
* Init CountDownTimer to to get location from history when requestLocationUpdates don't return result.
*/
@Synchronized
private fun countDownUpdateLocation() {
mCountDownTimer?.cancel()
mCountDownTimer = object : CountDownTimer(TWENTY_SECS, TWENTY_SECS) {
override fun onTick(millisUntilFinished: Long) {}
override fun onFinish() {
if (mWeakReferenceActivity != null) {
val activity = mWeakReferenceActivity?.get()
if (activity != null && ActivityCompat.checkSelfPermission(
activity,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
) {
val location = (activity.applicationContext
.getSystemService(Context.LOCATION_SERVICE) as LocationManager)
.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER)
stopRequestLocationUpdates()
onLocationChanged(location)
} else {
stopRequestLocationUpdates()
}
} else {
mCountDownTimer?.cancel()
mCountDownTimer = null
}
}
}.start()
}
/**
* The method must be called in onDestroy() of activity to
* removeUpdateLocation and cancel CountDownTimer.
*/
fun stopRequestLocationUpdates() {
val activity = mWeakReferenceActivity?.get()
if (activity != null) {
/*if (ActivityCompat.checkSelfPermission(activity,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {*/
(activity.applicationContext
.getSystemService(Context.LOCATION_SERVICE) as LocationManager).removeUpdates(this)
/*}*/
}
mCountDownTimer?.cancel()
mCountDownTimer = null
}
}
In MainActivity.kt
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
...
CurrentLocationManager.checkLocationPermission(this@LoginActivity)
}
override fun onDestroy() {
CurrentLocationManager.stopRequestLocationUpdates()
super.onDestroy()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == CurrentLocationManager.REQUEST_CODE_ACCESS_LOCATION) {
if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
//denied
val builder = AlertDialog.Builder(this)
builder.setMessage("We need permission to use your location for the purpose of finding friends near you.")
.setTitle("Device Location Required")
.setIcon(com.eswapp.R.drawable.ic_info)
.setPositiveButton("OK") { _, _ ->
if (ActivityCompat.shouldShowRequestPermissionRationale(
this,
Manifest.permission.ACCESS_FINE_LOCATION
)
) {
//only deny
CurrentLocationManager.checkLocationPermission(this@LoginActivity)
} else {
//never ask again
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
val uri = Uri.fromParts("package", packageName, null)
intent.data = uri
startActivityForResult(intent, CurrentLocationManager.REQUEST_CHECK_SETTINGS)
}
}
.setNegativeButton("Ask Me Later") { _, _ ->
}
// Create the AlertDialog object and return it
val dialog = builder.create()
dialog.show()
} else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
CurrentLocationManager.requestLocationUpdates(this)
}
}
}
//Forward Login result to the CallBackManager in OnActivityResult()
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
//case 1. After you allow the app access device location, Another dialog will be displayed to request you to turn on device location
//case 2. Or You chosen Never Ask Again, you open device Setting and enable location permission
CurrentLocationManager.REQUEST_CHECK_SETTINGS -> when (resultCode) {
RESULT_OK -> {
Log.d("REQUEST_CHECK_SETTINGS", "RESULT_OK")
//case 1. You choose OK
CurrentLocationManager.startRequestLocationUpdate(applicationContext)
}
RESULT_CANCELED -> {
Log.d("REQUEST_CHECK_SETTINGS", "RESULT_CANCELED")
//case 1. You choose NO THANKS
//CurrentLocationManager.requestLocationUpdates(this)
//case 2. In device Setting screen: user can enable or not enable location permission,
// so when user back to this activity, we should re-call checkLocationPermission()
CurrentLocationManager.checkLocationPermission(this@LoginActivity)
}
else -> {
//do nothing
}
}
else -> {
super.onActivityResult(requestCode, resultCode, data)
}
}
}
For Redmi and Mi devices turn off MIUI Optimization
Settings > Additional Settings > Developer Options > MIUI Optimization
Firstly make sure your API Key is valid and add this into your manifest <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Here's my maps activity.. there might be some redundant information in it since it's from a larger project I created.
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
//These variable are initalized here as they need to be used in more than one methid
private double currentLatitude; //lat of user
private double currentLongitude; //long of user
private double latitudeVillageApartmets= 53.385952001750184;
private double longitudeVillageApartments= -6.599087119102478;
public static final String TAG = MapsActivity.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
/*These methods all have to do with the map and wht happens if the activity is paused etc*/
//contains lat and lon of another marker
private void setUpMap() {
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitudeVillageApartmets, longitudeVillageApartments)).title("1"); //create marker
mMap.addMarker(marker); // adding marker
}
//contains your lat and lon
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("You are here");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom((latLng), 11.0F));
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
@Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
@Override
public void onConnected(Bundle bundle) {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else {
handleNewLocation(location);
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
@Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
}
There's a lot of methods here that are hard to understand but basically all update the map when it's paused etc. There are also connection timeouts etc. Sorry for just posting this, I tried to fix your code but I couldn't figure out what was wrong.
CAUSE: "Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app." In this case, "ACCESS_FINE_LOCATION" is a "dangerous permission and for that reason, you get this 'java.lang.SecurityException: "gps" location provider requires ACCESS_FINE_LOCATION permission.' error (https://developer.android.com/training/permissions/requesting.html).
SOLUTION: Implementing the code provided at https://developer.android.com/training/permissions/requesting.html under the "Request the permissions you need" and "Handle the permissions request response" headings.
This command would work perfectly fine :D
sudo -H pip install --upgrade package_name --ignore-installed six
(Android Studio 3.5) If you're a recent version of Android Studio, you can generate your notification images. Right click on your res folder > New > Image Asset. You will then see Configure Image Assets as shown in the image below. Change Icon Type to Notification Icons. Your images must be white and transparent. This Configure Image Assets will enforce that rule. Important: If you want the icons to be used for cloud/push notifications, you must add the meta-data under your application tag to use the newly created notification icons.
<application>
...
<meta-data android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/ic_notification" />
The configuration here is working for me:
configurations {
customProvidedRuntime
}
dependencies {
compile(
// Spring Boot dependencies
)
customProvidedRuntime('org.springframework.boot:spring-boot-starter-tomcat')
}
war {
classpath = files(configurations.runtime.minus(configurations.customProvidedRuntime))
}
springBoot {
providedConfiguration = "customProvidedRuntime"
}
ON MAC: Nothing was helping until I realised ScreenTime was blocking the update website! Turning off content filtering fix it
When your are trying to apply prod on string type of value like:
['-214' '-153' '-58' ..., '36' '191' '-37']
you will get the error.
Solution:
Append only integer value like [1,2,3]
, and you will get your expected output.
If the value is in string format before appending then, in the array you can convert the type into int
type and store it in a list
.
Add this code after sending message and before getting message from server
recyclerView.scrollToPosition(mChatList.size() - 1);
If the error persists after doing what @Burhan Khalid said
Try this line: python manage.py migrate --run-syncdb
implementation 'com.treebo:internetavailabilitychecker:1.0.1'
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
InternetAvailabilityChecker.init(this);
}
@Override
public void onLowMemory() {
super.onLowMemory();
InternetAvailabilityChecker.getInstance().removeAllInternetConnectivityChangeListeners();
}
}
I fixed it adding these lines in the build.grandle (App Module)
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar']) //it was there
compile "com.android.support:support-v4:21.0.+" //Added
compile "com.android.support:appcompat-v7:21.0.+" //Added
}
Open Terminal and type:
pip config set global.target /Users/Bob/Library/Python/3.8/lib/python/site-packages
except instead of
/Users/Bob/Library/Python/3.8/lib/python/site-packages
you would use whatever directory you want.
I've found that the command was wrong, correct command contains "broadcast" instead of "start":
adb shell am broadcast -a com.whereismywifeserver.intent.TEST --es sms_body "test from adb" -n com.whereismywifeserver/.IntentReceiver
For those people to whom none of the answers worked.... try closing the chrome://inspect/#devices tab in chrome if opened... This worked for me.
If You try to insert other than the number in the Table column you get Constraint[numbering] error.
Try to insert the only number (or) make your Table column to char Type
You can pass an ArrayList<E>
the same way, if the E
type is Serializable
.
You would call the putExtra (String name, Serializable value)
of Intent
to store, and getSerializableExtra (String name)
for retrieval.
Example:
ArrayList<String> myList = new ArrayList<String>();
intent.putExtra("mylist", myList);
In the other Activity:
ArrayList<String> myList = (ArrayList<String>) getIntent().getSerializableExtra("mylist");
In your xampppath\apache\conf\extra open file httpd-xampp.conf and find the below tag:
<LocationMatch "^/(?i:(?:xampp|licenses|phpmyadmin|webalizer|server-status|server-info))">
Order deny,allow
Deny from all
Allow from ::1 127.0.0.0/8
ErrorDocument 403 /error/HTTP_XAMPP_FORBIDDEN.html.var
and add Allow from all
after Allow from ::1 127.0.0.0/8 {line}
Restart xampp, and you are done.
Download HAXM from SDK Manager
Open your SDK Manager from Android Studio, click the icon shown in the screen shot.
Click on "Launch Standalone SDK Manager" on the "Default Settings" Dialog.
Check node "Extras > Intel x86 Emulator Accelerator (HAXM installer)" and proceed with HAXM download.
Installing or Modifying HAXM
You can now access with installation (or modifying existing installtino) of HAXM by accessing the download location. Enter this path in "run"
%localappdata%\Android\sdk\extras\intel\Hardware_Accelerated_Execution_Manager
and double click the file "intelhaxm-android.exe"
You can increase the size of memory allocated to HAXM while modifying existing HAXM install. I have a machine with 32 GB of RAM and would like to launch multiple AVDs at same time (for automated testing etc.) so I have allocated 8 GB to HAXM.
Caveat
If you are running one AVD of one 1 GB and allocated 2 GB to HAXM, you cannot run another AVD with RAM more than 1 GB. Please make sure that Android Device Monitor is not running when you are modifying or installing HAXM (just to avoid any suprises).
These steps are tested on Windows platform, but generally could be applied to other platforms too with slight modification.
If you are using Pipenv
, you may need to add this to your Pipfile
:
[packages]
python-dateutil = "*"
This is because the port is already running in the background.So you can restart the eclipse and try again. OR open the file application.properties and change the value of 'server.port' to some other value like ex:- 8000/8181
In my case:
And then it worked.
try this
String[] projection = { MediaStore.Images.Media.DATA };
@SuppressWarnings("deprecation")
Cursor cursor = managedQuery(mCapturedImageURI, projection,
null, null, null);
int column_index_data = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
image_path = cursor.getString(column_index_data);
Log.e("path of image from CAMERA......******************.........",
image_path + "");
for capturing image:
String fileName = "temp.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
values.clear();
Make sure you have the latest version of Android Studio. The support library is included by default when you create new projects. If you are adding the Support Library to a project that doesn't have it, then you just need to add a single line to your app module's build.gradle file, and then sync gradle.
build.gradle
dependencies {
...
implementation 'com.android.support:appcompat-v7:27.1.1'
}
It should just be that easy, though there may be some things to note:
27.1.1
numbers that I have here to whatever it tells you to. You can also manually check what the latest revision is if you want to.implementation
keyword replaces compile
that was used in Android Studio 2.x. (What's the difference?)constraint-layout
or recyclerview
).Let's say that I want to create the following URL:
https://www.myawesomesite.com/turtles/types?type=1&sort=relevance#section-name
To build this with the Uri.Builder
I would do the following.
Uri.Builder builder = new Uri.Builder();
builder.scheme("https")
.authority("www.myawesomesite.com")
.appendPath("turtles")
.appendPath("types")
.appendQueryParameter("type", "1")
.appendQueryParameter("sort", "relevance")
.fragment("section-name");
String myUrl = builder.build().toString();
Android Studio 2.2.3 Linux Mint 18.1
Inside your 'project view' open Gradle Scripts -> build.gradle(Module:app) and put your mouse pointer inside the word dependencies.
Click on the light bulb and click "add library dependency" and for me all the libraries I wanted were listed there.
example libraries that came up for me: compile 'com.android.support:gridlayout-v7:25.1.0' compile 'com.android.support:support-v13:25.1.0'
I am now looking to add android support by default in Gradles default configuration.
i have same problem at the moment. I just run yum install gcc
{
/your/first/command
/your/second/command
} &> /dev/null
To eliminate output from commands, you have two options:
Close the output descriptor file, which keeps it from accepting any more input. That looks like this:
your_command "Is anybody listening?" >&-
Usually, output goes either to file descriptor 1 (stdout) or 2 (stderr). If you close a file descriptor, you'll have to do so for every numbered descriptor, as &>
(below) is a special BASH syntax incompatible with >&-
:
/your/first/command >&- 2>&-
Be careful to note the order: >&-
closes stdout, which is what you want to do; &>-
redirects stdout and stderr to a file named -
(hyphen), which is not what what you want to do. It'll look the same at first, but the latter creates a stray file in your working directory. It's easy to remember: >&2
redirects stdout to descriptor 2 (stderr), >&3
redirects stdout to descriptor 3, and >&-
redirects stdout to a dead end (i.e. it closes stdout).
Also beware that some commands may not handle a closed file descriptor particularly well ("write error: Bad file descriptor"), which is why the better solution may be to...
Redirect output to /dev/null
, which accepts all output and does nothing with it. It looks like this:
your_command "Hello?" > /dev/null
For output redirection to a file, you can direct both stdout and stderr to the same place very concisely, but only in bash:
/your/first/command &> /dev/null
Finally, to do the same for a number of commands at once, surround the whole thing in curly braces. Bash treats this as a group of commands, aggregating the output file descriptors so you can redirect all at once. If you're familiar instead with subshells using ( command1; command2; )
syntax, you'll find the braces behave almost exactly the same way, except that unless you involve them in a pipe the braces will not create a subshell and thus will allow you to set variables inside.
{
/your/first/command
/your/second/command
} &> /dev/null
See the bash manual on redirections for more details, options, and syntax.
I suddenly had the same problem, after no noteworthy changes.
I solved it by deleting the app/build
directory and let gradle build the whole project new.
I'm using this tutorial and it works nicely for my application.
In my activity I put this code:
GPSTracker tracker = new GPSTracker(this);
if (!tracker.canGetLocation()) {
tracker.showSettingsAlert();
} else {
latitude = tracker.getLatitude();
longitude = tracker.getLongitude();
}
also check if your emulator runs with Google API
I was having same issue in centos 6.5
Finaly solution below worked for me
-go to http://dl.fedoraproject.org/pub/epel/6/x86_64/
-search for php-mcrypt(http://dl.fedoraproject.org/pub/epel/6/x86_64/php-mcrypt-5.3.3-3.el6.x86_64.rpm)
-execute wget http://dl.fedoraproject.org/pub/epel/6/x86_64/php-mcrypt-5.3.3-3.el6.x86_64.rpm
-rpm -ivh php-mcrypt-5.3.3-3.el6.x86_64.rpm
if there are any dependencies you can download same using http://dl.fedoraproject.org/pub/epel/6/x86_64/
The initial issue is solved by changing lat
and lon
to double.
I want to add comment to solution with Location location = locationManager.getLastKnownLocation(bestProvider);
It works to find out last known location when other app was lisnerning for that. If, for example, no app did that since device start, the code will return zeros (spent some time myself recently to figure that out).
Also, it's a good practice to stop listening when there is no need for that by locationManager.removeUpdates(this);
Also, even with permissions in manifest
, the code works when location service is enabled in Android settings on a device.
Just download and install "Samsung Kies" from this link. and everything would work as required.
Before installing, uninstall the drivers you have installed for your device.
Update:
Two possible solutions:
This simple implementation helps to pass data between fragments in a simple way. Think you want to pass data from 'Frgment1' to 'Fragment2'
In Fragment1(Set data to send)
Bundle bundle = new Bundle();
bundle.putString("key","Jhon Doe"); // set your parameteres
Fragment2 nextFragment = new Fragment2();
nextFragment.setArguments(bundle);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_drawer, nextFragment).commit();
In Fragment2 onCreateView method (Get parameteres)
String value = this.getArguments().getString("key");//get your parameters
Toast.makeText(getActivity(), value+" ", Toast.LENGTH_LONG).show();//show data in tost
The existing answers will suit most people, but for those who are looking to add shadows under the fixed header and to the right of the first (fixed) column, here's a working example (pure css):
http://jsbin.com/nayifepaxo/1/edit?html,output
The main trick in getting this to work is using ::after
to add shadows to the right of each of the first td
in each tr
:
tr td:first-child:after {
box-shadow: 15px 0 15px -15px rgba(0, 0, 0, 0.05) inset;
content: "";
position:absolute;
top:0;
bottom:0;
right:-15px;
width:15px;
}
Took me a while (too long...) to get it all working so I figured I'd share for those who are in a similar situation.
To get the path of all images in android I am using following code
public void allImages()
{
ContentResolver cr = getContentResolver();
Cursor cursor;
Uri allimagessuri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Images.Media._ID + " != 0";
cursor = cr.query(allsongsuri, STAR, selection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String fullpath = cursor.getString(cursor
.getColumnIndex(MediaStore.Images.Media.DATA));
Log.i("Image path ", fullpath + "");
} while (cursor.moveToNext());
}
cursor.close();
}
}
great answer by @Rarw. Try using a bundle to pass information from one fragment to another
Please try this:
byte[] decodedString = Base64.decode(person_object.getPhoto(),Base64.NO_WRAP);
InputStream inputStream = new ByteArrayInputStream(decodedString);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
user_image.setImageBitmap(bitmap);
There is not official api support which means that it is not documented for the public and the libraries may change at any time. I realize you don't want to leave the application but here's how you do it with an intent for anyone else wondering.
public void sendData(int num){
String fileString = "..."; //put the location of the file here
Intent mmsIntent = new Intent(Intent.ACTION_SEND);
mmsIntent.putExtra("sms_body", "text");
mmsIntent.putExtra("address", num);
mmsIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(fileString)));
mmsIntent.setType("image/jpeg");
startActivity(Intent.createChooser(mmsIntent, "Send"));
}
I haven't completely figured out how to do things like track the delivery of the message but this should get it sent.
You can be alerted to the receipt of mms the same way as sms. The intent filter on the receiver should look like this.
<intent-filter>
<action android:name="android.provider.Telephony.WAP_PUSH_RECEIVED" />
<data android:mimeType="application/vnd.wap.mms-message" />
</intent-filter>
Sadly, @jason-robinson answer above didn't work for me.
Although the rotate function works perfectly:
public static Bitmap rotateImage(Bitmap source, float angle) {
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix,
true);
}
I had to do the following to get the orientation as the Exif orientation was always 0
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode,resultCode,data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
String[] orientationColumn = {MediaStore.Images.Media.ORIENTATION};
Cursor cur = managedQuery(imageUri, orientationColumn, null, null, null);
int orientation = -1;
if (cur != null && cur.moveToFirst()) {
orientation = cur.getInt(cur.getColumnIndex(orientationColumn[0]));
}
InputStream imageStream = getContentResolver().openInputStream(selectedImage);
Bitmap bitmap = BitmapFactory.decodeStream(imageStream);
switch(orientation) {
case 90:
bitmap = rotateImage(chosen_image_bitmap, 90);
break;
case 180:
bitmap = rotateImage(chosen_image_bitmap, 180);
break;
case 270:
bitmap = rotateImage(chosen_image_bitmap, 270);
break;
default:
break;
}
imageView.setImageBitmap(bitmap );
What i have done is that import a new project into eclipse workspace, and that path of that was be
android-sdk-macosx/extras/google/google_play_services/libproject/google-play-services_lib
and add as library in your project.. that it .. simple!! you might require to add support library in your project.
ProgressDialog dialog = ProgressDialog.show(Example.this, "", "Loading...", true);
I can also confirm this error.
Workaround: is to use external maven inside m2eclipse, instead of it's embedded maven.
That is done in three steps:
1 Install maven on local machine (the test-machine was Ubuntu 10.10)
mvn --version
Apache Maven 2.2.1 (rdebian-4) Java version: 1.6.0_20 Java home: /usr/lib/jvm/java-6-openjdk/jre Default locale: de_DE, platform encoding: UTF-8 OS name: "linux" version: "2.6.35-32-generic" arch: "amd64" Family: "unix"
2 Run maven externally link how to run maven from console
> cd path-to-pom.xml > mvn test
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building Simple
[INFO] task-segment: [test]
[INFO] ------------------------------------------------------------------------
[...]
[INFO] Surefire report directory: [...]/workspace/Simple/target/surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running net.tverrbjelke.experiment.MainAppTest
Hello World
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.042 sec
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[...]
3 inside m2eclipse: switch from embedded maven to local maven
mvn --version
, or google for your MAVEN_HOME
, for me this helped me that is /usr/share/maven2
)The error-message should be gone.
What I tend to do, and I believe this is what Google intended for developers to do too, is to still get the extras from an Intent
in an Activity
and then pass any extra data to fragments by instantiating them with arguments.
There's actually an example on the Android dev blog that illustrates this concept, and you'll see this in several of the API demos too. Although this specific example is given for API 3.0+ fragments, the same flow applies when using FragmentActivity
and Fragment
from the support library.
You first retrieve the intent extras as usual in your activity and pass them on as arguments to the fragment:
public static class DetailsActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// (omitted some other stuff)
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(
android.R.id.content, details).commit();
}
}
}
In stead of directly invoking the constructor, it's probably easier to use a static method that plugs the arguments into the fragment for you. Such a method is often called newInstance
in the examples given by Google. There actually is a newInstance
method in DetailsFragment
, so I'm unsure why it isn't used in the snippet above...
Anyways, all extras provided as argument upon creating the fragment, will be available by calling getArguments()
. Since this returns a Bundle
, its usage is similar to that of the extras in an Activity
.
public static class DetailsFragment extends Fragment {
/**
* Create a new instance of DetailsFragment, initialized to
* show the text at 'index'.
*/
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
public int getShownIndex() {
return getArguments().getInt("index", 0);
}
// (other stuff omitted)
}
None of above works for godaddy server centOS 6, apache 2.4, php 5.6
Instead, you should
Install the mbstring PHP Extension with EasyApache
check if you already have it by, putty or ssh
php -m | grep mbstring
[if nothing, means missing mbstring]
Now you need to goto godaddy your account page,
click manager server,
open whm ----- search for apache,
open "easy apache 4"(my case)
Now you need customize currently installed packages,
by
click "customize" button on top line next to "currently installed package..."
search mbstring,
click on/off toggle next to it.
click next, next, .... privision..done.
Now you should have mbstring
by check again at putty(ssh)
php -m | grep mbstring [should see mbstring]
or you can find mbstring at phpinfo() page
Probably because you had something like this?
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri fileUri = CommonUtilities.getTBCameraOutputMediaFileUri();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(takePictureIntent, 2);
However you must not put the extra output into the intent, because then the data goes into the URI instead of the data variable. For that reason, you have to take the two lines in the middle out, so that you have
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, 2);
That´s what caused the problem for me, hope that helped.
If you are totally new like me, you must install the minimum SDK at first. Check the link.
This worked out perfectly for me:
Same problem other post with a good solution
Regards,
Khaled.
For Kotlin Users
You just need to add ? with Intent in onActivityResult
as the data can be null
if user cancels the transaction or anything goes wrong. So we need to define data as nullable
in onActivityResult
Just replace onActivityResult
signature of SampleActivity with below:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)
Use "bAutoWidth": false
and go through the example given below. It is working for me.
Example:
$('#tableId').dataTable({
"bAutoWidth": false
});
private Uri imageUri;
....
Intent intent = new Intent(this, GoogleActivity.class);
intent.putExtra("imageUri", imageUri.toString());
startActivity(intent);
this.finish();
And then you can fetch it like this:
imageUri = Uri.parse(extras.getString("imageUri"));
This is how you use bundle:
Bundle b = new Bundle();
b.putInt("id", id);
Fragment frag= new Fragment();
frag.setArguments(b);
retrieve value from bundle:
bundle = getArguments();
if (bundle != null) {
id = bundle.getInt("id");
}
Try This below method code to get the distance in meter between two location, hope it will help for you
public static double distance(LatLng start, LatLng end){
try {
Location location1 = new Location("locationA");
location1.setLatitude(start.latitude);
location1.setLongitude(start.longitude);
Location location2 = new Location("locationB");
location2.setLatitude(end.latitude);
location2.setLongitude(end.longitude);
double distance = location1.distanceTo(location2);
return distance;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
The question is answered already, but I want add more information about the causes.
Android app unable to start activity componentinfo
This error often comes with appropriate logs. You can read logs and can solve this issue easily.
Here is a sample log. In which you can see clearly ClassCastException
. So this issue came because TextView
cannot be cast to EditText
.
Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.403: D/AndroidRuntime(1050): Shutting down VM
11-04 01:24:10.403: W/dalvikvm(1050): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 01:24:10.543: E/AndroidRuntime(1050): FATAL EXCEPTION: main
11-04 01:24:10.543: E/AndroidRuntime(1050): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.os.Looper.loop(Looper.java:137)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 01:24:10.543: E/AndroidRuntime(1050): at java.lang.reflect.Method.invokeNative(Native Method)
11-04 01:24:10.543: E/AndroidRuntime(1050): at java.lang.reflect.Method.invoke(Method.java:525)
11-04 01:24:10.543: E/AndroidRuntime(1050): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 01:24:10.543: E/AndroidRuntime(1050): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 01:24:10.543: E/AndroidRuntime(1050): at dalvik.system.NativeStart.main(Native Method)
11-04 01:24:10.543: E/AndroidRuntime(1050): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.543: E/AndroidRuntime(1050): at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:45)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.Activity.performCreate(Activity.java:5133)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 01:24:10.543: E/AndroidRuntime(1050): ... 11 more
11-04 01:29:11.177: I/Process(1050): Sending signal. PID: 1050 SIG: 9
11-04 01:31:32.080: D/AndroidRuntime(1109): Shutting down VM
11-04 01:31:32.080: W/dalvikvm(1109): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 01:31:32.194: E/AndroidRuntime(1109): FATAL EXCEPTION: main
11-04 01:31:32.194: E/AndroidRuntime(1109): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.os.Looper.loop(Looper.java:137)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 01:31:32.194: E/AndroidRuntime(1109): at java.lang.reflect.Method.invokeNative(Native Method)
11-04 01:31:32.194: E/AndroidRuntime(1109): at java.lang.reflect.Method.invoke(Method.java:525)
11-04 01:31:32.194: E/AndroidRuntime(1109): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 01:31:32.194: E/AndroidRuntime(1109): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 01:31:32.194: E/AndroidRuntime(1109): at dalvik.system.NativeStart.main(Native Method)
11-04 01:31:32.194: E/AndroidRuntime(1109): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:31:32.194: E/AndroidRuntime(1109): at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:44)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.Activity.performCreate(Activity.java:5133)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 01:31:32.194: E/AndroidRuntime(1109): ... 11 more
11-04 01:36:33.195: I/Process(1109): Sending signal. PID: 1109 SIG: 9
11-04 02:11:09.684: D/AndroidRuntime(1167): Shutting down VM
11-04 02:11:09.684: W/dalvikvm(1167): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 02:11:09.855: E/AndroidRuntime(1167): FATAL EXCEPTION: main
11-04 02:11:09.855: E/AndroidRuntime(1167): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.os.Looper.loop(Looper.java:137)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 02:11:09.855: E/AndroidRuntime(1167): at java.lang.reflect.Method.invokeNative(Native Method)
11-04 02:11:09.855: E/AndroidRuntime(1167): at java.lang.reflect.Method.invoke(Method.java:525)
11-04 02:11:09.855: E/AndroidRuntime(1167): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 02:11:09.855: E/AndroidRuntime(1167): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 02:11:09.855: E/AndroidRuntime(1167): at dalvik.system.NativeStart.main(Native Method)
11-04 02:11:09.855: E/AndroidRuntime(1167): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 02:11:09.855: E/AndroidRuntime(1167): at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:44)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.Activity.performCreate(Activity.java:5133)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 02:11:09.855: E/AndroidRuntime(1167): ... 11 more
findViewById()
of non existing viewLike when you use findViewById(R.id.button)
when button id does not exist in layout XML.
If you wrong cast some class, then you get this error. Like you cast RelativeLayout
to LinearLayout
or EditText
to TextView
.
manifest.xml
If you did not register Activity in manifest.xml
then this error comes.
findViewById()
with declaration at top levelBelow code is incorrect. This will create error. Because you should do findViewById()
after calling setContentView()
. Because an View can be there after it is created.
public class MainActivity extends Activity {
ImageView mainImage = (ImageView) findViewById(R.id.imageViewMain); //incorrect way
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainImage = (ImageView) findViewById(R.id.imageViewMain); //correct way
//...
}
}
abstract
Activity class.When you try to start an Activity which is abstract, you will will get this error. So just remove abstract
keyword before activity class name.
If your activity is written in Kotlin and you have not setup kotlin in your app. then you will get error. You can follow simple steps as written in Android Link or Kotlin Link. You can check this answer too.
Read about Downcast and Upcast
In my experience, I've found it best to go with the GPS fix unless it's not available. I don't know much about other location providers, but I know that for GPS there are a few tricks that can be used to give a bit of a ghetto precision measure. The altitude is often a sign, so you could check for ridiculous values. There is the accuracy measure on Android location fixes. Also if you can see the number of satellites used, this can also indicate the precision.
An interesting way of getting a better idea of the accuracy could be to ask for a set of fixes very rapidly, like ~1/sec for 10 seconds and then sleep for a minute or two. One talk I've been to has led to believe that some android devices will do this anyway. You would then weed out the outliers (I've heard Kalman filter mentioned here) and use some kind of centering strategy to get a single fix.
Obviously the depth you get to here depends on how hard your requirements are. If you have particularly strict requirement to get THE BEST location possible, I think you'll find that GPS and network location are as similar as apples and oranges. Also GPS can be wildly different from device to device.
In case you don't know fragments in your activity just enumerate them all and send activity result arguments:
//Java
// In your activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
for (Fragment fragment : getSupportFragmentManager().getFragments()) {
fragment.onActivityResult(requestCode, resultCode, data);
}
}
//Kotlin
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
for (fragment in supportFragmentManager.fragments) {
fragment.onActivityResult(requestCode, resultCode, data)
}
}
You could use for (String key : keys) { Object o = get(key);
to return an Object, call getClass().getName()
on it to get the type, and then do a set of if name.equals("String") type things to work out which method you should actually be calling, in order to get the value?
put function
etname=(EditText)findViewById(R.id.Name);
tvname=(TextView)findViewById(R.id.tvName);
b1= (ImageButton) findViewById(R.id.Submit);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
String s=etname.getText().toString();
Intent ii=new Intent(getApplicationContext(), MainActivity2.class);
ii.putExtra("name", s);
Toast.makeText(getApplicationContext(),"Page 222", Toast.LENGTH_LONG).show();
startActivity(ii);
}
});
getfunction
public class MainActivity2 extends Activity {
TextView tvname;
EditText etname;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
tvname = (TextView)findViewById(R.id.tvName);
etname=(EditText)findViewById(R.id.Name);
Intent iin= getIntent();
Bundle b = iin.getExtras();
if(b!=null)
{
String j2 =(String) b.get("name");
etname.setText(j2);
Toast.makeText(getApplicationContext(),"ok",Toast.LENGTH_LONG).show();
}
}
Toolbear74 is right log4j.XML is required.
In order to get the XML to validate the <param>
tags need to be BEFORE the <rollingPolicy>
I suggest setting a logging threshold <param name="threshold" value="info"/>
When Creating a Log4j.xml file don't forget to to copy the log4j.dtd into the same location.
Here is an example:
<?xml version="1.0" encoding="windows-1252"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration>
<!-- Daily Rolling File Appender that compresses old files -->
<appender name="file" class="org.apache.log4j.rolling.RollingFileAppender" >
<param name="threshold" value="info"/>
<rollingPolicy name="file"
class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
<param name="FileNamePattern"
value="${catalina.base}/logs/myapp.log.%d{yyyy-MM-dd}.gz"/>
<param name="ActiveFileName" value="${catalina.base}/logs/myapp.log"/>
</rollingPolicy>
<layout class="org.apache.log4j.EnhancedPatternLayout" >
<param name="ConversionPattern"
value="%d{ISO8601} %-5p - %-26.26c{1} - %m%n" />
</layout>
</appender>
<root>
<priority value="debug"></priority>
<appender-ref ref="file" />
</root>
</log4j:configuration>
Considering that your setting a FileNamePattern
and an ActiveFileName
I think that setting a File
property is redundant and possibly even erroneous
Try renaming your log4j.properties and dropping in a log4j.xml similar to my example and see what happens.
The source code for the Android mobile application open-gpstracker which you appreciated is available here.
You can checkout the code using SVN client application or via Git:
Debugging the source code will surely help you.
Your byte array is too small. Each pixel takes up 4 bytes, not just 1, so multiply your size * 4 so that the array is big enough.
Make sure that the component has the "exported" flag set to true. Also the component defining the permission should be installed before the component that uses it.
Had the same issue, probably some kind of bug.
Even the fullScroll(ScrollView.FOCUS_UP)
from the other answer didn't work.
Only thing that worked for me was calling scroll_view.smoothScrollTo(0,0)
right after the dialog is shown.
For android 19+ you can get it in Telephony.Sms.Intents.SMS_RECEIVED_ACTION)
. There are more in the Intent
s class that 're worth looking
at
This code sends array of integer values
Initialize array List
List<Integer> test = new ArrayList<Integer>();
Add values to array List
test.add(1);
test.add(2);
test.add(3);
Intent intent=new Intent(this, targetActivty.class);
Send the array list values to target activity
intent.putIntegerArrayListExtra("test", (ArrayList<Integer>) test);
startActivity(intent);
here you get values on targetActivty
Intent intent=getIntent();
ArrayList<String> test = intent.getStringArrayListExtra("test");
OK, there is more to it than that, you need zlib. zlib is part of CentOS, but you need the development form to get zlib.h ... notice that the yum name of zlib development
is quite different possibly than for apt-get on ubuntu/debian, what follows actually works
with my CentOS version
in particular, you do ./configure on git, then try make, and the first build fails with missing zlib.h
I used a two-step procedure to resolve this a) Got RPMFORGE for my version of CentOS
See: www.centos.org/modules/newbb/viewtopic.php?topic_id=18506&forum=38 and this: wiki.centos.org/AdditionalResources/Repositories/RPMForge
In my case [as root, or with sudo]
$ wget http://packages.sw.be/rpmforge-release/rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm
$ rpm -K rpmforge-release-0.5.2-2.el5.rf.*.rpm
$ rpm -i rpmforge-release-0.5.2-2.el5.rf.*.rpm
## Note: the RPM for rpmforge is small (like 12.3K) but don't let that fool
## you; it augments yum the next time you use yum
## [this is the name that YUM found] (still root or sudo)
$ yum install zlib-devel.x86_64
## and finally in the source directory for git (still root or sudo):
$ ./configure (this worked before, but I ran it again to be sure)
$ make
$ make install
(this install put it by default in /usr/local/bin/git
... not my favorite choice, but OK for the default)... and git works fine!
Mathias Lin code working beautifully. However, you might want to consider changing this part inside drawPath method:
if (lngLat.length >= 2 && gp1.getLatitudeE6() > 0 && gp1.getLongitudeE6() > 0
&& gp2.getLatitudeE6() > 0 && gp2.getLongitudeE6() > 0) {
GeoPoint can be less than zero as well, I switch mine to:
if (lngLat.length >= 2 && gp1.getLatitudeE6() != 0 && gp1.getLongitudeE6() != 0
&& gp2.getLatitudeE6() != 0 && gp2.getLongitudeE6() != 0) {
Thank you :D
You can make your enum implement Parcelable which is quite easy for enums:
public enum MyEnum implements Parcelable {
VALUE;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(final Parcel dest, final int flags) {
dest.writeInt(ordinal());
}
public static final Creator<MyEnum> CREATOR = new Creator<MyEnum>() {
@Override
public MyEnum createFromParcel(final Parcel source) {
return MyEnum.values()[source.readInt()];
}
@Override
public MyEnum[] newArray(final int size) {
return new MyEnum[size];
}
};
}
You can then use Intent.putExtra(String, Parcelable).
UPDATE: Please note wreckgar's comment that enum.values()
allocates a new array at each call.
UPDATE: Android Studio features a live template ParcelableEnum
that implements this solution. (On Windows, use Ctrl+J)
An alternate to the above solutions is using Aliases for Tables:
UPDATE T1 SET T1.extrasPrice = (SELECT SUM(T2.Price) FROM BookingPitchExtras T2 WHERE T2.pitchID = T1.ID)
FROM BookingPitches T1;
You could implement a onActivityResult in Class B as well and launch Class C using startActivityForResult. Once you get the result in Class B then set the result there (for Class A) based on the result from Class C. I haven't tried this out but I think this should work.
Another thing to look out for is that Activity A should not be a singleInstance activity. For startActivityForResult to work your Class B needs to be a sub activity to Activity A and that is not possible in a single instance activity, the new Activity (Class B) starts in a new task.
None of the above solutions address the generic intention of the original request. What if we don't know the id of the anchor? What if it doesn't have an id? What if it doesn't even have an href parameter (e.g. prev/next icon in a carousel)? What if we want to apply the action to multiple anchors with different models in an agnostic fashion? Here's an example that does something instead of a click, then later simulates the click (for any anchor or other tag):
var clicker = null;
$('a').click(function(e){
clicker=$(this); // capture the clicked dom object
/* ... do something ... */
e.preventDefault(); // prevent original click action
});
clicker[0].click(); // this repeats the original click. [0] is necessary.
G'day, I too can say that I tried everything mentioned in these posts and a few more from elsewhere. The #1 problem for me was that the new Intent always had a null bundle. My issue was in focusing too much on the details of "have I included .this or .that". My solution was in taking a step back from the detail and looking at the overall structure of the notification. When I did that I managed to place the key parts of the code in the correct sequence. So, if you're having similar issues check for:
1. Intent notificationIntent = new Intent(MainActivity.this, NotificationActivity.class);
2a. Bundle bundle = new Bundle();
//I like specifying the data type much better. eg bundle.putInt
2b. notificationIntent.putExtras(bundle);
3. PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, WIZARD_NOTIFICATION_ID, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
4. NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
5. NotificationCompat.Builder nBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notify)
.setContentTitle(title)
.setContentText(content)
.setContentIntent(contentIntent)
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
.setAutoCancel(false)//false is standard. true == automatically removes the notification when the user taps it.
.setColor(getResources().getColor(R.color.colorPrimary))
.setCategory(Notification.CATEGORY_REMINDER)
.setPriority(Notification.PRIORITY_HIGH)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
notificationManager.notify(WIZARD_NOTIFICATION_ID, nBuilder.build());
With this sequence I get a valid bundle.
After I removed
\usepackage{fontspec}% font selecting commands
\usepackage{xunicode}% unicode character macros
\usepackage{xltxtra} % some fixes/extras
it seems to have worked "correctly".
It may be worth noting that the headers and footers only appear from page 2 onwards. Although I've tried the fix for this given in the fancyhdr documentation, I can't get it to work either.
FYI: MikTeX 2.7 under Vista
I'm a total noob, I came here to figure out VB's 'not equal to' syntax, so I figured I'd throw it in here in case someone else needed it:
<%If Not boolean_variable%>Do this if boolean_variable is false<%End If%>
I managed to create a simple console "hello world" with QT Creator
used creator 2.4.1 and QT 4.8.0 on windows 7
two ways to do this
Plain C++
do the following
or
QT Console
example: for QT console "hello world"
file - new file project 'project name '
other projects - QT Console Application
Targets select 'Desktop'
project management - next
code:
#include <QtCore/QCoreApplication>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
cout<<" hello world";
return a.exec();
}
ctrl -R to run
compilers used for above MSVC 2010 (QT SDK) , and minGW(QT SDK)
hope this helps someone
As I have just started to use QT recently and also searched the Www for info and examples to get started with simple examples still searching...
The globals()
function returns a dictionary, where keys are names of objects you can name (and values, by the way, are id
s of these objects)
The exec()
function takes a string and executes it as if you just type it in a python console. So, the code is
for i in list(globals().keys()):
if(i[0] != '_'):
exec('del {}'.format(i))
Adding to @Greg Hewgill answer: if you want to be able to match both date-time and only date, you can make the "time" part of the regex optional:
(\d{4})-(\d{2})-(\d{2})( (\d{2}):(\d{2}):(\d{2}))?
this way you will match both 2008-09-01 12:35:42
and 2008-09-01
Build up a JavaScript data structure with the required information, then turn it into the json string at the end.
Based on what I think you're doing, try something like this:
var result = [];
for (var name in goals) {
if (goals.hasOwnProperty(name)) {
result.push({name: name, goals: goals[name]});
}
}
res.contentType('application/json');
res.send(JSON.stringify(result));
or something along those lines.
This can be achieved using inline-block JS fiddle here
<html>
<body class="body">
<div class="form">
<form class="email-form">
<input type="text" class="input">
<a href="#" class="button">Button</a>
</form>
</div>
</body>
</html>
<style>
* {
box-sizing: border-box;
}
.body {
font-family: Arial, sans-serif;
font-size: 14px;
line-height: 20px;
color: #333;
}
.form {
display: block;
margin: 0 0 15px;
}
.email-form {
display: block;
margin-top: 20px;
margin-left: 20px;
}
.button {
height: 40px;
display: inline-block;
padding: 9px 15px;
background-color: grey;
color: white;
border: 0;
line-height: inherit;
text-decoration: none;
cursor: pointer;
}
.input {
display: inline-block;
width: 200px;
height: 40px;
margin-bottom: 0px;
padding: 9px 12px;
color: #333333;
vertical-align: middle;
background-color: #ffffff;
border: 1px solid #cccccc;
margin: 0;
line-height: 1.42857143;
}
</style>
It seems Yahoo server does some heuristic based on User-Agent
in a case Accept
header is set to */*
.
Accept: text/html
did the trick for me.
e.g.
wget --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0" http://yahoo.com
Note: if you don't declare Accept
header then wget
automatically adds Accept:*/*
which means give me anything you have.
Here is the notes (from Brian Goetz book) I made, that might be of help to you
AtomicXXX classes
provide Non-blocking Compare-And-Swap implementation
Takes advantage of the support provide by hardware (the CMPXCHG instruction on Intel) When lots of threads are running through your code that uses these atomic concurrency API, they will scale much better than code which uses Object level monitors/synchronization. Since, Java's synchronization mechanisms makes code wait, when there are lots of threads running through your critical sections, a substantial amount of CPU time is spent in managing the synchronization mechanism itself (waiting, notifying, etc). Since the new API uses hardware level constructs (atomic variables) and wait and lock free algorithms to implement thread-safety, a lot more of CPU time is spent "doing stuff" rather than in managing synchronization.
not only offer better throughput, but they also provide greater resistance to liveness problems such as deadlock and priority inversion.
If your project doesn't have an upstream branch, that is if this is the very first time the remote repository is going to know about the branch created in your local repository the following command should work.
git push --set-upstream origin <branch-name>
This is the solution I use. It has more lines but it will only create the datepicker once.
$('#txtSearch').datepicker({
constrainInput:false,
beforeShow: function(){
var t = $('#ddlSearchType').val();
if( ['Required Date', 'Submitted Date'].indexOf(t) ) {
$('#txtSearch').prop('readonly', false);
return false;
}
else $('#txtSearch').prop('readonly', true);
}
});
The datepicker will not show unless the value of ddlSearchType is either "Required Date" or "Submitted Date"
echo '<span style="Your CSS Styles">' . $ip['cityName'] . '</span>';
Apple Updated Doc:
Each remote notification includes a payload. The payload contains information about how the system should alert the user as well as any custom data you provide. The maximum size allowed for a notification payload depends on which provider API you employ. When using the HTTP/2 provider API, maximum payload size is 4096 bytes. Using the legacy binary interface, maximum payload size is 2048 bytes. Apple Push Notification service (APNs) refuses any notification that exceeds the maximum size.
This is how it worked for me.
Object
var my_object ={"Super Hero":["Iron Man", "Super Man"]};
Set
Encode the stringified object with encodeURIComponent() and set as attribute:
var data_str = encodeURIComponent(JSON.stringify(my_object));
$("div#mydiv").attr("data-hero",data-str);
Get
To get the value as an object, parse the decoded, with decodeURIComponent(), attribute value:
var data_str = $("div#mydiv").attr("data-hero");
var my_object = JSON.parse(decodeURIComponent(data_str));
In case of Mac OS X Maverick when MySQL is installed via Homebrew it's located at /usr/local/opt/mysql/my.cnf
Step 1. Install "Apache_OpenOffice_4.1.2" in your system Step 2. Download "unoconv" library from github or any where else.
-> C:\Program Files (x86)\OpenOffice 4\program\python.exe = Path of open office install directory
-> D:\wamp\www\doc_to_pdf\libobasis4.4-pyuno\unoconv = Path of library folder
-> D:/wamp/www/doc_to_pdf/files/'.$pdf_File_name.' = path and file name of pdf
-> D:/wamp/www/doc_to_pdf/files/'.$doc_file_name = Path of your document file.
If pdf not created than last step is Go to ->Control Panel\All Control Panel Items\Administrative Tools-> services-> find "wampapache" -> right click and click on property -> click on logon tab Than check checkbox of allow service to interact with desktop
Create sample .php file and put below code and run on wamp or xampp server
$result = exec('"C:\Program Files (x86)\OpenOffice 4\program\python.exe" D:\wamp\www\doc_to_pdf\libobasis4.4-pyuno\unoconv -f pdf -o D:/wamp/www/doc_to_pdf/files/'.$pdf_File_name.' D:/wamp/www/doc_to_pdf/files/'.$doc_file_name);
This code working for me in windows-8 operating system
Caveat emptor: For some reasons classes like this seem to break the multiprocessing package. I just struggled with this bug for awhile before finding this SO: Finding exception in python multiprocessing
For Dialog This may helpful for someone. I want a dialog to take full width of screen. searched a lot but nothing found useful. Finally this worked for me:
mDialog.setContentView(R.layout.my_custom_dialog);
mDialog.getWindow().setBackgroundDrawable(null);
after adding this, my dialog appears in full width of screen.
I was having same issue in IE9. I followed the above answer and I added the line:
<meta http-equiv="X-UA-Compatible" content="IE=8;FF=3;OtherUA=4" />
in my <head>
and it worked.
I'd factor out the prepared statement handling to at least a method. In this case, because there are no results it is fairly simple (and assuming that the connection is an instance variable that doesn't change):
private PreparedStatement updateSales;
public void updateSales(int sales, String cof_name) throws SQLException {
if (updateSales == null) {
updateSales = con.prepareStatement(
"UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
}
updateSales.setInt(1, sales);
updateSales.setString(2, cof_name);
updateSales.executeUpdate();
}
At that point, it is then just a matter of calling:
updateSales(75, "Colombian");
Which is pretty simple to integrate with other things, yes? And if you call the method many times, the update will only be constructed once and that will make things much faster. Well, assuming you don't do crazy things like doing each update in its own transaction...
Note that the types are fixed. This is because for any particular query/update, they should be fixed so as to allow the database to do its job efficiently. If you're just pulling arbitrary strings from a CSV file, pass them in as strings. There's also no locking; far better to keep individual connections to being used from a single thread instead.
Well, this is simple. The above for
loops are semantically equivalent to
int i = 0;
while(i < 5) {
printf("%d", i);
i++;
}
and
int i = 0;
while(i < 5) {
printf("%d", i);
++i;
}
Note that the lines i++;
and ++i;
have the same semantics FROM THE PERSPECTIVE OF THIS BLOCK OF CODE. They both have the same effect on the value of i
(increment it by one) and therefore have the same effect on the behavior of these loops.
Note that there would be a difference if the loop was rewritten as
int i = 0;
int j = i;
while(j < 5) {
printf("%d", i);
j = ++i;
}
int i = 0;
int j = i;
while(j < 5) {
printf("%d", i);
j = i++;
}
This is because in first block of code j
sees the value of i
after the increment (i
is incremented first, or pre-incremented, hence the name) and in the second block of code j
sees the value of i
before the increment.
If you don't have this ipython_notebook_config.py file, you can create one by following the readme and typing
ipython profile create
I'd like to second Polin's answer and just add one thing in case you are still stuck. This code certainly does work to set a specific cookie expiration time. One issue you may be having is that if you are using Chrome and accessing your page via "http://localhost..." or "file://", Chrome will not store cookies. The easy fix for this is to use a simple http server (like node's http-server if you haven't already) and navigate to your page explicitly as "http://127.0.0.1" in which case Chrome WILL store cookies for local development. This had me hung up for a bit as, if you don't do this, your expires key will simply have the value of "session" when you investigate it in the console or in Dev Tools.
You'll first need to separate your numpy array into two separate arrays containing x and y values.
x = [1, 2, 3, 9]
y = [1, 4, 1, 3]
curve_fit also requires a function that provides the type of fit you would like. For instance, a linear fit would use a function like
def func(x, a, b):
return a*x + b
scipy.optimize.curve_fit(func, x, y)
will return a numpy array containing two arrays: the first will contain values for a
and b
that best fit your data, and the second will be the covariance of the optimal fit parameters.
Here's an example for a linear fit with the data you provided.
import numpy as np
from scipy.optimize import curve_fit
x = np.array([1, 2, 3, 9])
y = np.array([1, 4, 1, 3])
def fit_func(x, a, b):
return a*x + b
params = curve_fit(fit_func, x, y)
[a, b] = params[0]
This code will return a = 0.135483870968
and b = 1.74193548387
Here's a plot with your points and the linear fit... which is clearly a bad one, but you can change the fitting function to obtain whatever type of fit you would like.
In additional you should disable your antivirus or manage it to open 80 port on your system.
From here: http://docs.oracle.com/javase/tutorial/information/glossary.html
field
property
attribute
variable
i had a similar problem - firefox returned the correct value of obj.clientHeight but ie did not- it returned 0. I changed it to obj.offsetHeight and it worked. Seems there is some state that ie has for clientheight - that makes it iffy...
extract(hour from age(now(),links.created))
gives you a floor-rounded count of the hour difference.
set this :
#inner-right {
height: 100%;
max-height: 96%;//change here
overflow: auto;
background: ivory;
}
this will solve your problem.
Ken Liu has it right in my opinion. The maven dependency plugin allows you to expand all the dependencies, which you can then treat as resources. This allows you to include them in the main artifact. The use of the assembly plugin creates a secondary artifact which can be difficult to modify - in my case I wanted to add custom manifest entries. My pom ended up as:
<project>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>unpack-dependencies</id>
<phase>package</phase>
<goals>
<goal>unpack-dependencies</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
...
<resources>
<resource>
<directory>${basedir}/target/dependency</directory>
<targetPath>/</targetPath>
</resource>
</resources>
</build>
...
</project>
Getting a cross-domain JSON with jQuery in Internet Explorer 8 and newer versions
Very useful link:
Can help with the trouble of returning json from a X Domain Request.
Hope this helps somebody.
Based on answers in this thread I've created checklist-model directive that covers all cases:
For topic-starter case it would be:
<label ng-repeat="fruit in ['apple', 'orange', 'pear', 'naartjie']">
<input type="checkbox" checklist-model="selectedFruits" checklist-value="fruit"> {{fruit}}
</label>
Try this coding
<div>
<iframe id='iframe2' src="Mypage.aspx" frameborder="0" style="overflow: hidden; height: 100%;
width: 100%; position: absolute;"></iframe>
</div>
You don't need floats. In fact, they're useless because floats are ignored in flexbox.
You also don't need CSS positioning.
There are several flex methods available. auto
margins have been mentioned in another answer.
Here are two other options:
justify-content: space-between
and the order
property.justify-content: space-between
and reverse the order of the divs..parent {_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
}_x000D_
_x000D_
.parent:first-of-type > div:last-child { order: -1; }_x000D_
_x000D_
p { background-color: #ddd;}
_x000D_
<p>Method 1: Use <code>justify-content: space-between</code> and <code>order-1</code></p>_x000D_
_x000D_
<div class="parent">_x000D_
<div class="child" style="float:right"> Ignore parent? </div>_x000D_
<div>another child </div>_x000D_
</div>_x000D_
_x000D_
<hr>_x000D_
_x000D_
<p>Method 2: Use <code>justify-content: space-between</code> and reverse the order of _x000D_
divs in the mark-up</p>_x000D_
_x000D_
<div class="parent">_x000D_
<div>another child </div>_x000D_
<div class="child" style="float:right"> Ignore parent? </div>_x000D_
</div>
_x000D_
Following on from Naresh's answer, dynamic polymorphism is only 'dynamic' in Java because of the presence of the virtual machine and its ability to interpret the code at run time rather than the code running natively.
In C++ it must be resolved at compile time if it is being compiled to a native binary using gcc, obviously; however, the runtime jump and thunk in the virtual table is still referred to as a 'lookup' or 'dynamic'. If C inherits B, and you declare B* b = new C(); b->method1();
, b will be resolved by the compiler to point to a B object inside C (for a simple class inherits a class situation, the B object inside C and C will start at the same memory address so nothing is required to be done; it will be pointing at the vptr that they both use). If C inherits B and A, the virtual function table of the A object inside C entry for method1 will have a thunk which will offset the pointer to the start of the encapsulating C object and then pass it to the real A::method1() in the text segment which C has overridden. For C* c = new C(); c->method1()
, c will be pointing to the outer C object already and the pointer will be passed to C::method1() in the text segment. Refer to: http://www.programmersought.com/article/2572545946/
In java, for B b = new C(); b.method1();
, the virtual machine is able to dynamically check the type of the object paired with b and can pass the correct pointer and call the correct method. The extra step of the virtual machine eliminates the need for virtual function tables or the type being resolved at compile time, even when it could be known at compile time. It's just a different way of doing it which makes sense when a virtual machine is involved and code is only compiled to bytecode.
I am surprised not to see the following pattern here, which actually looks very simple.
// shout.ts
class ShoutSingleton {
helloWorld() { return 'hi'; }
}
export let Shout = new ShoutSingleton();
Usage
import { Shout } from './shout';
Shout.helloWorld();
try below, assuming running port is 8000
:
free-port() { kill "$(lsof -t -i :8000)"; }
I found the reference here
Here is a query for showing all databases in one Sql engine
Select * from Sys.Databases
You need to access image IDs using R.mipmap.yourImageName
You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.
Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String
'Assign data to first item in array
compArray(1) = "asdf"
'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"
'Prints "ErrorState"
Debug.Print Computers("Computer Name")
Collections cannot be sorted so if you need to sort data you will probably want to use an array.
Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx
Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx
Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!
Edit:
Sub ArrayExample()
Dim subject As String
Dim TestArray() As String
Dim counter As Long
subject = "Example"
counter = Len(subject)
ReDim TestArray(1 To counter) As String
For counter = 1 To Len(subject)
TestArray(counter) = Right(Left(subject, counter), 1)
Next
End Sub
The following worked for me:
-> file
-> settings
-> plugins
-> disable the android support plugin
-> you will be prompted to restart
-> once restarted re-enable the plugin and other dependency plugins that might have been disabled in the process
-> you will be prompted to restart once again. Hopefully when android studio restarts the second time the preview should render.
openpyxl
# -*- coding: utf-8 -*-
import openpyxl
file = 'sample.xlsx'
wb = openpyxl.load_workbook(filename=file)
# Seleciono la Hoja
ws = wb.get_sheet_by_name('Hoja1')
# Valores a Insertar
ws['A3'] = 42
ws['A4'] = 142
# Escribirmos en el Fichero
wb.save(file)
Try Clink. It's awesome, especially if you are used to bash
keybindings and features.
(As already pointed out - there is a similar question: Is there a better Windows Console Window?)
Since most of us like oneliners:
Convert.ToBase64String(File.ReadAllBytes(imageFilepath));
If you need it as Base64 byte array:
Encoding.ASCII.GetBytes(Convert.ToBase64String(File.ReadAllBytes(imageFilepath)));
No. I guess you were hoping that something like num1 = 20 if someBoolValue
would work, but it doesn't. I think the best way is with the if
statement as you have written it:
if someBoolValue:
num1 = 20
Reset the file in a correct state, commit, and push again.
If you're sure nobody else has fetched your changes yet, you can use --amend
when committing, to modify your previous commit (i.e. rewrite history), and then push. I think you'll have to use the -f
option when pushing, to force the push, though.
I tried all the answers provided here. However none of them worked for me in shared hosting. However, soultion mentioned here works for me How to solve "CSRF Token Mismatch" in Laravel l
In case you use jQuery you need to wait for $(window).load
, because the embedded SVG document might not be yet loaded at $(document).ready
$(window).load(function () {
//alert("Document loaded, including graphics and embedded documents (like SVG)");
var a = document.getElementById("alphasvg");
//get the inner DOM of alpha.svg
var svgDoc = a.contentDocument;
//get the inner element by id
var delta = svgDoc.getElementById("delta");
delta.addEventListener("mousedown", function(){ alert('hello world!')}, false);
});
If you can use ansible, and set the sudo rights in it, then you can easily use this script. If you're wanting to script something like this, it means you need to do it on more than one system. Therefore, you should try to automate that as well.
CSV files have no limit of rows you can add to them. Excel won't hold more that the 1 million lines of data if you import a CSV file having more lines.
Excel will actually ask you whether you want to proceed when importing more than 1 million data rows. It suggests to import the remaining data by using the text import wizard again - you will need to set the appropriate line offset.
Or if you have an array of [key, value]
arrays, you can do:
[[1, 2], [3, 4]].inject({}) do |r, s|
r.merge!({s[0] => s[1]})
end # => { 1 => 2, 3 => 4 }
Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.
Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.
As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:
Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.
Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:
meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)
Formula is from Chris Broadfoot's comment.
Google Maps basics
Zoom Level - zoom
0 - 19
0 lowest zoom (whole world)
19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()
What you're looking for are the scales for each zoom level. Use these:
20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9 : 2311162.307000
8 : 4622324.614000
7 : 9244649.227000
6 : 18489298.450000
5 : 36978596.910000
4 : 73957193.820000
3 : 147914387.600000
2 : 295828775.300000
1 : 591657550.500000
Instead of using the new pragmas, you can also use __attribute__((optimize("O0")))
for your needs. This has the advantage of just applying to a single function and not all functions defined in the same file.
Usage example:
void __attribute__((optimize("O0"))) foo(unsigned char data) {
// unmodifiable compiler code
}
You can use, for example:
words = [word.replace('[br]','<br />') for word in words]
If you have access to Underscore, you can use the following:
if (_.contains([1, 3, 12], foo)) {
// ...
}
contains
used to work in Lodash as well (prior to V4), now you have to use includes
if (_.includes([1, 3, 12], foo)) {
handleYellowFruit();
}
PK - Primary Key
NN - Not Null
BIN - Binary (stores data as binary strings. There is no character set so sorting and comparison is based on the numeric values of the bytes in the values.)
UN - Unsigned (non-negative numbers only. so if the range is -500 to 500, instead its 0 - 1000, the range is the same but it starts at 0)
UQ - Create/remove Unique Key
ZF - Zero-Filled (if the length is 5 like INT(5) then every field is filled with 0’s to the 5th digit. 12 = 00012, 400 = 00400, etc. )
AI - Auto Increment
G - Generated column. i.e. value generated by a formula based on the other columns
pip3 install --upgrade pip
worked for me
You can use the react-moment package
-> https://www.npmjs.com/package/react-moment
Put in your file the next line:
import moment from "moment";
date_create: moment().format("DD-MM-YYYY hh:mm:ss")
Note that the mode of opening files is 'a' or some other have alphabet 'a' will also make error because of the overwritting.
pointer = open('makeaafile.txt', 'ab+')
tes = pickle.load(pointer, encoding='utf-8')
If you are running code and want to take input via running your program in the terminal, the best thing to do is to run it in terminal directly by just right click and choose "Run Python File in Terminal".
Try using list.AddRange(VTSWeb.GetDailyWorktimeViolations(VehicleID2));
x+=y
is shorthand in many languages for set x to x + y
. The sum will be, as hinted by its name, the sum of the numbers in data
.
In Notepad++ go to Plugins > Plugin manager > Show Plugin Manager
then find Xml Tools
plugin. Tick the box and click Install
Open XML document you want to validate and click Ctrl+Shift+Alt+M (Or use Menu if this is your preference Plugins > XML Tools > Validate Now
).
Following dialog will open:
Click on ...
. Point to XSD file and I am pretty sure you'll be able to handle things from here.
Hope this saves you some time.
EDIT:
Plugin manager was not included in some versions of Notepad++ because many users didn't like commercials that it used to show. If you want to keep an older version, however still want plugin manager, you can get it on github, and install it by extracting the archive and copying contents to plugins and updates folder.
In version 7.7.1
plugin manager is back under a different guise... Plugin Admin
so now you can simply update notepad++ and have it back.
#button {
line-height: 12px;
width: 18px;
font-size: 8pt;
font-family: tahoma;
margin-top: 1px;
margin-right: 2px;
position: absolute;
top: 0;
right: 0;
}
You could use an expects script. I have not written one in quite some time but it should look like below. You will need to head the script with #!/usr/bin/expect
#!/usr/bin/expect -f
spawn ssh HOSTNAME
expect "login:"
send "username\r"
expect "Password:"
send "password\r"
interact
If you need to get all the files in the folder named 'Data', just code it as below
string[] Documents = System.IO.Directory.GetFiles("../../Data/");
Now the 'Documents' consists of array of complete object name of two text files in the 'Data' folder 'Data'.
Use doubleval()
. But be very careful about using decimals in financial transactions, and validate that user input very carefully.
I'll add this in here as my problem had something todo with my virtualenv
:
I hadn't activated my virtual environment and was trying to install my requirements, this ultimately led to my install failing and throwing this error message.
So make sure you activate your virtualenv!
After spending hours, I found that I missed 's'
letter in table name
It was [Table("Employee")]
instead of [Table("Employees")]
The following solution will work for Bootstrap 4.
.modal .modal-dialog {
max-width: 850px;
}
try this:
Dim ws as Worksheet
Set ws = Thisworkbook.Sheets("Sheet2")
With ws
.Range("E2").Formula = "=VLOOKUP(D2,Sheet1!$A:$C,1,0)"
End With
End Sub
This just the simplified version of what you want.
No need to use Application
if you will just output the answer in the Range("E2")
.
If you want to stick with your logic, declare the variables.
See below for example.
Sub Test()
Dim rng As Range
Dim ws1, ws2 As Worksheet
Dim MyStringVar1 As String
Set ws1 = ThisWorkbook.Sheets("Sheet1")
Set ws2 = ThisWorkbook.Sheets("Sheet2")
Set rng = ws2.Range("D2")
With ws2
On Error Resume Next 'add this because if value is not found, vlookup fails, you get 1004
MyStringVar1 = Application.WorksheetFunction.VLookup(rng, ws1.Range("A1:C65536").Value, 1, False)
On Error GoTo 0
If MyStringVar1 = "" Then MsgBox "Item not found" Else MsgBox MyStringVar1
End With
End Sub
Hope this get's you started.
You can use this
"abcdefg".index('c') #=> 2
You can absolutely inject mocks on MyLauncher in your test. I am sure if you show what mocking framework you are using someone would be quick to provide an answer. With mockito I would look into using @RunWith(MockitoJUnitRunner.class) and using annotations for myLauncher. It would look something like what is below.
@RunWith(MockitoJUnitRunner.class)
public class MyLauncherTest
@InjectMocks
private MyLauncher myLauncher = new MyLauncher();
@Mock
private MyService myService;
@Test
public void someTest() {
}
}
To print a schema, I use jade and do an export to a file of the database then bring it into word to format and print
SSL properties are set at the JVM level via system properties. Meaning you can either set them when you run the program (java -D....) Or you can set them in code by doing System.setProperty.
The specific keys you have to set are below:
javax.net.ssl.keyStore- Location of the Java keystore file containing an application process's own certificate and private key. On Windows, the specified pathname must use forward slashes, /, in place of backslashes.
javax.net.ssl.keyStorePassword - Password to access the private key from the keystore file specified by javax.net.ssl.keyStore. This password is used twice: To unlock the keystore file (store password), and To decrypt the private key stored in the keystore (key password).
javax.net.ssl.trustStore - Location of the Java keystore file containing the collection of CA certificates trusted by this application process (trust store). On Windows, the specified pathname must use forward slashes,
/
, in place of backslashes,\
.If a trust store location is not specified using this property, the SunJSSE implementation searches for and uses a keystore file in the following locations (in order):
$JAVA_HOME/lib/security/jssecacerts
$JAVA_HOME/lib/security/cacerts
javax.net.ssl.trustStorePassword - Password to unlock the keystore file (store password) specified by
javax.net.ssl.trustStore
.javax.net.ssl.trustStoreType - (Optional) For Java keystore file format, this property has the value jks (or JKS). You do not normally specify this property, because its default value is already jks.
javax.net.debug - To switch on logging for the SSL/TLS layer, set this property to ssl.
The JavaDoc explains it very well:
With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.
SO_TIMEOUT
is the timeout that a read()
call will block. If the timeout is reached, a java.net.SocketTimeoutException will be thrown. If you want to block forever put this option to zero (the default value), then the read()
call will block until at least 1 byte could be read.
Hoho.. It should be very easy to use Gallery to implement this, using ViewPager is much harder. But i still encourage to use ViewPager since Gallery really have many problems and is deprecated since android 4.2.
In PagerAdapter there is a method getPageWidth() to control page size, but only by this you cannot achieve your target.
Try to read the following 2 articles for help.
using System.Net.NetworkInformation;
public static bool PingHost(string nameOrAddress)
{
bool pingable = false;
Ping pinger = null;
try
{
pinger = new Ping();
PingReply reply = pinger.Send(nameOrAddress);
pingable = reply.Status == IPStatus.Success;
}
catch (PingException)
{
// Discard PingExceptions and return false;
}
finally
{
if (pinger != null)
{
pinger.Dispose();
}
}
return pingable;
}
background-image
instead of background
This works in Opera : http://jsfiddle.net/ZNsbU/5/
But it doesn't work in FF5 nor IE8. (yay for outdated browsers :D )
body {
background:url(http://www.google.com/intl/en_com/images/srpr/logo3w.png) 400px 200px / 600px 400px no-repeat;
}
You could do it like this :
body {
background:url(http://www.google.com/intl/en_com/images/srpr/logo3w.png) 400px 400px no-repeat;
background-size:20px 20px
}
Which works in FF5 and Opera but not in IE8.
there is no CSS selector for selecting a parent of a selected child.
you could do it with JavaScript
Oddly, working on a .js file and Ctrl, Shift, += works to zoom in (and Ctrl - works to zoom out but you have to select 1 or 2 after Ctrl -). This only works when I'm in the js file but the zoom applies to all my open tabs. Using Eclipse Juno on Ubuntu.
I had the same problem and couln't find the solution. Finally I realized, that with owlcarousel ver. 2.3.4 I have to include not only owl.carousel.js, but owl.autoplay.js file too.
I dont exactly know what you want to do.But you cant send data of one form using a submit button of another form.
You could do one thing either use sessions or use hidden fields that has the submit button. You could use javascript/jquery to pass the values from the first form to the hidden fields of the second form.Then you could submit the form.
Or else the easiest you could do is use sessions.
<form>
<input type="text" class="input-text " value="" size="32" name="user_data[firstname]" id="elm_6">
<input type="text" class="input-text " value="" size="32" name="user_data[lastname]" id="elm_7">
</form>
<form action="#">
<input type="text" class="input-text " value="" size="32" name="user_data[b_firstname]" id="elm_14">
<input type="text" class="input-text " value="" size="32" name="user_data[s_firstname]" id="elm_16">
<input type="submit" value="Continue" name="dispatch[checkout.update_steps]">
</form>
$('input[type=submit]').click(function(){
$('#elm_14').val($('#elm_6').val());
$('#elm_16').val($('#elm_7').val());
});
This is the jsfiddle for it http://jsfiddle.net/FPsdy/102/
let str = "{\"names\": [\"Bob\", \"Tim\", \"Tina\"]}"
let data = str.data(using: String.Encoding.utf8, allowLossyConversion: false)!
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject]
if let names = json["names"] as? [String]
{
print(names)
}
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
$count = DB::table('category_issue')->count();
will give you the number of items.
For more detailed information check Fluent Query Builder section in beautiful Laravel Documentation.
Use OpenCSV for reliability. Split should never be used for these kind of things. Here's a snippet from a program of my own, it's pretty straightforward. I check if a delimiter character was specified and use this one if it is, if not I use the default in OpenCSV (a comma). Then i read the header and fields
CSVReader reader = null;
try {
if (delimiter > 0) {
reader = new CSVReader(new FileReader(this.csvFile), this.delimiter);
}
else {
reader = new CSVReader(new FileReader(this.csvFile));
}
// these should be the header fields
header = reader.readNext();
while ((fields = reader.readNext()) != null) {
// more code
}
catch (IOException e) {
System.err.println(e.getMessage());
}
check here
http://c-faq.com/lib/randrange.html
For any of these techniques, it's straightforward to shift the range, if necessary; numbers in the range [M, N] could be generated with something like
M + rand() / (RAND_MAX / (N - M + 1) + 1)
Another related function is whos
. It will list all sorts of information (dimensions, byte size, type) for the variables in a given workspace.
>> a = [0 0 7];
>> whos a
Name Size Bytes Class Attributes
a 1x3 24 double
>> b = 'James Bond';
>> whos b
Name Size Bytes Class Attributes
b 1x10 20 char
OracleXETNSListener - this service has to be started if it was disabled.
run -> services.msc
and look out for that services
In your case, the error is that you're trying to generate an Error
instance. Error
in Swift 3 is a protocol that can be used to define a custom error. This feature is especially for pure Swift applications to run on different OS.
In iOS development the NSError
class is still available and it conforms to Error
protocol.
So, if your purpose is only to propagate this error code, you can easily replace
var errorTemp = Error(domain:"", code:httpResponse.statusCode, userInfo:nil)
with
var errorTemp = NSError(domain:"", code:httpResponse.statusCode, userInfo:nil)
Otherwise check the Sandeep Bhandari's answer regarding how to create a custom error type
Tried all above, none worked .. finally worked when I switch connected as from MTP to Camera(PTP).
A lot of these seem to be overcomplicated. I achieved what I wanted with just the following:
$(".ui-accordion-content").show();
Follow the below steps:
If you don't find your WWDR certificate in Login or System tab, then select category "All items" on the left side. Most probably you will get to see an expired WWDR certificate here, and you can remove it. An expired certificate is always shown with a red asterisk.
Here's a simple way
for (i in 1:10) {
skip_to_next <- FALSE
# Note that print(b) fails since b doesn't exist
tryCatch(print(b), error = function(e) { skip_to_next <<- TRUE})
if(skip_to_next) { next }
}
Note that the loop completes all 10 iterations, despite errors. You can obviously replace print(b)
with any code you want. You can also wrap many lines of code in {
and }
if you have more than one line of code inside the tryCatch
Set the image to be the background of a div, then set the background size to be half the width of the image.
<div class="myimage"></div>
Then in your css, if your image is 300px x 200px:
.myimage {
background: url('images/myimage.png') no-repeat;
background-size:150px;
width:150px;
height:100px;
}
Why did you miss Sparrow, Starling, Kestrel, Amazon SQS, Beanstalkd, Kafka, IronMQ ?
Message Queue Servers
Message queue servers are available in various languages, Erlang (RabbitMQ), C (beanstalkd), Ruby (Starling or Sparrow), Scala (Kestrel, Kafka) or Java (ActiveMQ). A short overview can be found here
Sparrow
Starling
Kestrel
RabbitMQ
Apache ActiveMQ
Beanstalkd
Amazon SQS
Kafka
ZMQ
EagleMQ
IronMQ
I hope that this will be helpful for us. source
You have to manually copy each key/value pair to a new map
. This is a loop that people have to reprogram any time they want a deep copy of a map
.
You can automatically generate the function for this by installing mapper
from the maps
package using
go get -u github.com/drgrib/maps/cmd/mapper
and running
mapper -types string:aStruct
which will generate the file map_float_astruct.go
containing not only a (deep) Copy
for your map but also other "missing" map
functions ContainsKey
, ContainsValue
, GetKeys
, and GetValues
:
func ContainsKeyStringAStruct(m map[string]aStruct, k string) bool {
_, ok := m[k]
return ok
}
func ContainsValueStringAStruct(m map[string]aStruct, v aStruct) bool {
for _, mValue := range m {
if mValue == v {
return true
}
}
return false
}
func GetKeysStringAStruct(m map[string]aStruct) []string {
keys := []string{}
for k, _ := range m {
keys = append(keys, k)
}
return keys
}
func GetValuesStringAStruct(m map[string]aStruct) []aStruct {
values := []aStruct{}
for _, v := range m {
values = append(values, v)
}
return values
}
func CopyStringAStruct(m map[string]aStruct) map[string]aStruct {
copyMap := map[string]aStruct{}
for k, v := range m {
copyMap[k] = v
}
return copyMap
}
Full disclosure: I am the creator of this tool. I created it and its containing package because I found myself constantly rewriting these algorithms for the Go map
for different type combinations.
Even though the above solutions do work,This answer is for you in case you want to reverse the clock instead of undoing a git pull.I mean if you want to get your exact repo the way it was X
Mins back then run the command
git reset --hard branchName@{"X Minutes ago"}
Note: before you actually go ahead and run this command please only try this command if you are sure about the time you want to go back to and heres about my situation.
I was currently on a branch develop
, I was supposed to checkout to a new branch and pull in another branch lets say Branch A
but I accidentally ran
git pull origin B
before checking out.
so to undo this change I tried this command
git reset --hard develop@{"10 Minutes ago"}
if you are on windows cmd and get error: unknown switch `e
try adding quotes like this
git reset --hard 'develop@{"10 Minutes ago"}'
You can basically wrap it into another div
and set its position
to fixed
.
.bg {_x000D_
position: fixed;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
.jqbox_innerhtml {_x000D_
width: 500px;_x000D_
height: 200px;_x000D_
margin: 5% auto;_x000D_
padding: 10px;_x000D_
border: 5px solid #ccc;_x000D_
background-color: #fff;_x000D_
}
_x000D_
<div class="bg">_x000D_
<div class="jqbox_innerhtml">_x000D_
This should be inside a horizontally and vertically centered box._x000D_
</div>_x000D_
</div>
_x000D_
$criteria = new \Doctrine\Common\Collections\Criteria();
$criteria->where($criteria->expr()->gt('id', 'id'))
->setMaxResults(1)
->orderBy(array("id" => $criteria::DESC));
$results = $articlesRepo->matching($criteria);
The selected answer did not work in my Web API application. I had to use
System.Web.HttpRuntime.AppDomainAppPath
You guys are forgetting that the colon is also used in the ternary operator (though I don't know if jquery uses it for this purpose).
the ternary operator is an expression form (expressions return a value) of an if/then statement. it's used like this:
var result = (condition) ? (value1) : (value2) ;
A ternary operator could also be used to produce side effects just like if/then, but this is profoundly bad practice.
Here is some main point which differentiate Spring, Spring MVC and Spring Boot :
Spring :
Spring MVC
Spring Boot :
(Evolution like : Spring -> Spring MVC -> Spring Boot, So newer version have the compatibility of old version features.) Note : It doesn't contain all point.
Accepted answer works like a charm but if the object has a list of objects it won't work as expected so here is my solution after some digging.
Following this thread advice, here is how I've done.
It isn't the best for debugging your API with postman but it is working as expected for me.
Original object: { page: 1, size: 5, filters: [{ field: "id", value: 1, comparison: "EQ" }
Encoded object: eyJwYWdlIjoxLCJzaXplIjo1LCJmaWx0ZXJzIjpbeyJmaWVsZCI6ImlkUGFyZW50IiwiY29tcGFyaXNvbiI6Ik5VTEwifV19
@GetMapping
fun list(@RequestParam search: String?): ResponseEntity<ListDTO> {
val filter: SearchFilterDTO = decodeSearchFieldDTO(search)
...
}
private fun decodeSearchFieldDTO(search: String?): SearchFilterDTO {
if (search.isNullOrEmpty()) return SearchFilterDTO()
return Gson().fromJson(String(Base64.getDecoder().decode(search)), SearchFilterDTO::class.java)
}
And here the SearchFilterDTO and FilterDTO
class SearchFilterDTO(
var currentPage: Int = 1,
var pageSize: Int = 10,
var sort: Sort? = null,
var column: String? = null,
var filters: List<FilterDTO> = ArrayList<FilterDTO>(),
var paged: Boolean = true
)
class FilterDTO(
var field: String,
var value: Any,
var comparison: Comparison
)
Michael Kropats solution in VB.net
Private Function RandomString(ByVal length As Integer, Optional ByVal allowedChars As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") As String
If length < 0 Then Throw New ArgumentOutOfRangeException("length", "length cannot be less than zero.")
If String.IsNullOrEmpty(allowedChars) Then Throw New ArgumentException("allowedChars may not be empty.")
Dim byteSize As Integer = 256
Dim hash As HashSet(Of Char) = New HashSet(Of Char)(allowedChars)
'Dim hash As HashSet(Of String) = New HashSet(Of String)(allowedChars)
Dim allowedCharSet() = hash.ToArray
If byteSize < allowedCharSet.Length Then Throw New ArgumentException(String.Format("allowedChars may contain no more than {0} characters.", byteSize))
' Guid.NewGuid and System.Random are not particularly random. By using a
' cryptographically-secure random number generator, the caller is always
' protected, regardless of use.
Dim rng = New System.Security.Cryptography.RNGCryptoServiceProvider()
Dim result = New System.Text.StringBuilder()
Dim buf = New Byte(128) {}
While result.Length < length
rng.GetBytes(buf)
Dim i
For i = 0 To buf.Length - 1 Step +1
If result.Length >= length Then Exit For
' Divide the byte into allowedCharSet-sized groups. If the
' random value falls into the last group and the last group is
' too small to choose from the entire allowedCharSet, ignore
' the value in order to avoid biasing the result.
Dim outOfRangeStart = byteSize - (byteSize Mod allowedCharSet.Length)
If outOfRangeStart <= buf(i) Then
Continue For
End If
result.Append(allowedCharSet(buf(i) Mod allowedCharSet.Length))
Next
End While
Return result.ToString()
End Function
This should do the trick for you.
For one word:
if (!string.Contains("One"))
For two words:
if (!(string.Contains("One") && string.Contains("Two")))
is the ajax uploader refreshing your input element? if so you should consider using .live() method.
$('#imageFile').live('change', function(){ uploadFile(); });
update:
from jQuery 1.7+ you should use now .on()
$(parent_element_selector_here or document ).on('change','#imageFile' , function(){ uploadFile(); });
Use java -cp myjar.jar com.mypackage.myClass
.
If the class is not in a package then simply java -cp myjar.jar myClass
.
If you are not within the directory where myJar.jar
is located, then you can do:
On Unix or Linux platforms:
java -cp /location_of_jar/myjar.jar com.mypackage.myClass
On Windows:
java -cp c:\location_of_jar\myjar.jar com.mypackage.myClass
Personally, I use
if not (x is None):
which is understood immediately without ambiguity by every programmer, even those not expert in the Python syntax.
This can also happen if you have the wrong python27.dll file (in case of Windows), to solve this just re-install (or extract) python with the exact corresponding dll version. I had a similar experience.
It turns out that you can create 32-bit ODBC connections using C:\Windows\SysWOW64\odbcad32.exe
. My solution was to create the 32-bit ODBC connection as a System DSN. This still didn't allow me to connect to it since .NET couldn't look it up. After significant and fruitless searching to find how to get the OdbcConnection class to look for the DSN in the right place, I stumbled upon a web site that suggested modifying the registry to solve a different problem.
I ended up creating the ODBC connection directly under HKLM\Software\ODBC
. I looked in the SysWOW6432 key to find the parameters that were set up using the 32-bit version of the ODBC administration tool and recreated this in the standard location. I didn't add an entry for the driver, however, as that was not installed by the standard installer for the app either.
After creating the entry (by hand), I fired up my windows service and everything was happy.
@PointerNull gave good solution, but it is not perfect. It doesn't work on some devices with big files and show buggy Gif animation with delta frames on pre ICS version. I found solution without this bugs. It is library with native decoding to drawable: koral's android-gif-drawable.
Filestash is the perfect tool for that:
Also Filestash is open source. (Disclaimer: I am the author)
A bit more readable comparing is done by casting event.key
to upper case (I used onkeyup - needed the event to fire once upon each key tap):
window.onkeyup = function(event) {
let key = event.key.toUpperCase();
if ( key == 'W' ) {
// 'W' key is pressed
} else if ( key == 'D' ) {
// 'D' key is pressed
}
}
Each key has it's own code, get it out by outputting value of "key" variable (eg for arrow up key it will be 'ARROWUP' - (casted to uppercase))
The secret is simple: Ctrl+Shift+F
I knew I am late to the party but below is the correct way to deal with this, the key is to use InputStreamBody
in place of FileBody
to upload multi-part file.
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("https://someserver.com/api/path/");
postRequest.addHeader("Authorization",authHeader);
//don't set the content type here
//postRequest.addHeader("Content-Type","multipart/form-data");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
File file = new File(filePath);
FileInputStream fileInputStream = new FileInputStream(file);
reqEntity.addPart("parm-name", new InputStreamBody(fileInputStream,"image/jpeg","file_name.jpg"));
postRequest.setEntity(reqEntity);
HttpResponse response = httpclient.execute(postRequest);
}catch(Exception e) {
Log.e("URISyntaxException", e.toString());
}
Have a look at config.sample.inc.php: you will find examples of the configuration directives that you should copy to your config.inc.php (copy the missing ones). Then, have a look at examples/create_tables.sql which will help you create the missing tables.
The complete documentation for this is available at http://docs.phpmyadmin.net/en/latest/setup.html#phpmyadmin-configuration-storage.
There is a little known feature, which makes this even better. You can use a configurable default value instead of a hard-coded one, here is an example:
config.properties:
timeout.default=30
timeout.myBean=60
context.xml:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>config.properties</value>
</property>
</bean>
<bean id="myBean" class="Test">
<property name="timeout" value="${timeout.myBean:${timeout.default}}" />
</bean>
To use the default while still being able to easily override later, do this in config.properties:
timeout.myBean = ${timeout.default}
Always remember to be careful with nulls in pl/sql conditional clauses as null is never greater, smaller, equal or unequal to anything. Best way to avoid them is to use nvl.
For example
declare
i integer;
begin
if i <> 1 then
i:=1;
foobar();
end if;
end;
/
Never goes inside the if clause.
These would work.
if 1<>nvl(i,1) then
if i<> 1 or i is null then
just override onCreateOptionsMenu like this in your MainPage.java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
J(2)EE, strictly speaking, is a set of API
s (as the current top answer has it) which enable a programmer to build distributed, transactional systems. The idea was to abstract away the complicated distributed, transactional bits (which would be implemented by a Container such as WebSphere or Weblogic), leaving the programmer to develop business logic free from worries about storage mechanisms and synchronization.
In reality, it was a cobbled-together, design-by-committee mish-mash, which was pushed pretty much for the benefit of vendors like IBM, Oracle and BEA so they could sell ridicously over-complicated, over-engineered, over-useless products. Which didn't have the most basic features (such as scheduling)!
J2EE was a marketing construct.
Although this doesnt answer the question directly about command line, but from Windows OS, use the Windows Explorer ftp://username@server
this will use Passive Mode by default
For command line, active mode is the default
Perhaps you have some very weird and restrictive SELinux rules in place?
If not, try strace -o /tmp/wtf -fF curl -v google.com
and try to spot from /tmp/wtf
output file what's going on.
From the official Node.js documentation:
A Node.js package is also available in the official repo for Debian Sid (unstable), Jessie (testing) and Wheezy (wheezy-backports) as "nodejs". It only installs a nodejs binary.
So, if you only type sudo apt-get install nodejs
, it does not install other goodies such as npm.
You need to type:
curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
sudo apt-get install -y nodejs
Optional: install build tools
To compile and install native add-ons from npm you may also need to install build tools:
sudo apt-get install -y build-essential
More info: Docs
I have resolved the said
MqttException (0) - javax.net.ssl.SSLHandshakeException: No subjectAltNames on the certificate match
error by adding one (can add multiple) alternative subject name in the server certificate (having CN=example.com) which after prints the part of certificate as below:
Subject Alternative Name:
DNS: example.com
I used KeyExplorer on windows for generating my server certificate. You can follow this link for adding alternative subject names (follow the only part for adding it).
Here, check out this function:
function seo_friendly_url($string){
$string = str_replace(array('[\', \']'), '', $string);
$string = preg_replace('/\[.*\]/U', '', $string);
$string = preg_replace('/&(amp;)?#?[a-z0-9]+;/i', '-', $string);
$string = htmlentities($string, ENT_COMPAT, 'utf-8');
$string = preg_replace('/&([a-z])(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig|quot|rsquo);/i', '\\1', $string );
$string = preg_replace(array('/[^a-z0-9]/i', '/[-]+/') , '-', $string);
return strtolower(trim($string, '-'));
}
XAMPP only offers MySQL (Database Server) & Apache (Webserver) in one setup and you can manage them with the xampp starter.
After the successful installation navigate to your xampp folder and execute the xampp-control.exe
Press the start Button at the mysql row.
Now you've successfully started mysql. Now there are 2 different ways to administrate your mysql server and its databases.
But at first you have to set/change the MySQL Root password. Start the Apache server and type localhost
or 127.0.0.1
in your browser's address bar. If you haven't deleted anything from the htdocs folder the xampp status page appears. Navigate to security settings and change your mysql root password.
Now, you can browse to your phpmyadmin under http://localhost/phpmyadmin
or download a windows mysql client for example navicat lite or mysql workbench. Install it and log in to your mysql server with your new root password.
Building off of @s1m0nw1 excellent answer I made the following changes.
Code:
private object RandomRangeSingleton : Random()
fun ClosedRange<Int>.random() = RandomRangeSingleton.nextInt((endInclusive + 1) - start) + start
Test Case:
fun testRandom() {
Assert.assertTrue(
(0..1000).all {
(0..5).contains((0..5).random())
}
)
Assert.assertTrue(
(0..1000).all {
(0..4).contains((0 until 5).random())
}
)
Assert.assertFalse(
(0..1000).all {
(0..4).contains((0..5).random())
}
)
}
var now = new Date();_x000D_
now.setMinutes(now.getMinutes() + 30); // timestamp_x000D_
now = new Date(now); // Date object_x000D_
console.log(now);
_x000D_
REASON WHY THIS HAPPENS (EXPLANATION)
suppose we have 2 tables users and subscription.
1 user has 1 subscription
IN USER MODEL, we have
public function subscription()
{
return $this->hasOne('App\Subscription','user_id');
}
we can access subscription details as follows
$users = User:all();
foreach($users as $user){
echo $user->subscription;
}
if any of the user does not have a subscription, which can be a case. we cannot use arrow function further after subscription like below
$user->subscription->abc [this will not work]
$user->subscription['abc'] [this will work]
but if the user has a subscription
$user->subscription->abc [this will work]
NOTE: try putting a if condition like this
if($user->subscription){
return $user->subscription->abc;
}
Better option is to do this in your view model like
public class MyVM
{
int _propertyValue = 5;//set Default Value here
public int PropertyName{
get
{
return _propertyValue;
}
set
{
_propertyValue = value;
}
}
}
Then in your view
@Html.EditorFor(c => c.PropertyName)
will work the way u want it (if no value default value will be there)
NOTE: Please check device location latitude & logitude if you are using simulator means. By defaults its none only.
Step 1: Import CoreLocation
framework in .h File
#import <CoreLocation/CoreLocation.h>
Step 2: Add delegate CLLocationManagerDelegate
@interface yourViewController : UIViewController<CLLocationManagerDelegate>
{
CLLocationManager *locationManager;
CLLocation *currentLocation;
}
Step 3: Add this code in class file
- (void)viewDidLoad
{
[super viewDidLoad];
[self CurrentLocationIdentifier]; // call this method
}
Step 4: Method to detect current location
//------------ Current Location Address-----
-(void)CurrentLocationIdentifier
{
//---- For getting current gps location
locationManager = [CLLocationManager new];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
//------
}
Step 5: Get location using this method
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
currentLocation = [locations objectAtIndex:0];
[locationManager stopUpdatingLocation];
CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error)
{
if (!(error))
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(@"\nCurrent Location Detected\n");
NSLog(@"placemark %@",placemark);
NSString *locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
NSString *Address = [[NSString alloc]initWithString:locatedAt];
NSString *Area = [[NSString alloc]initWithString:placemark.locality];
NSString *Country = [[NSString alloc]initWithString:placemark.country];
NSString *CountryArea = [NSString stringWithFormat:@"%@, %@", Area,Country];
NSLog(@"%@",CountryArea);
}
else
{
NSLog(@"Geocode failed with error %@", error);
NSLog(@"\nCurrent Location Not Detected\n");
//return;
CountryArea = NULL;
}
/*---- For more results
placemark.region);
placemark.country);
placemark.locality);
placemark.name);
placemark.ocean);
placemark.postalCode);
placemark.subLocality);
placemark.location);
------*/
}];
}
Interceptors
I had the same issue and the reason was that I hadn't returned the response in the interceptor. Javascript thought, rightfully so, that I wanted to return undefined
for the promise:
// Add a request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
Don't forget to return
the mapped array , like:
lapsList() {
return this.state.laps.map((data) => {
return (
<View><Text>{data.time}</Text></View>
)
})
}
Reference for the map()
method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
You can use slice with no arguments to copy an array:
var foo,
bar;
foo = [3,1,2];
bar = foo.slice().sort();
Late to the game, but you can do it without @string/xyz
by using ?android:attr
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="?android:attr/versionName"
/>
<!-- or -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="?android:attr/versionCode"
/>
I've always used it on the command line and not as a library, but HTMLDOC gives me excellent results, and it handles at least some CSS (I couldn't easily see how much).
Here's a sample command line
htmldoc --webpage -t pdf --size letter --fontsize 10pt index.html > index.pdf
Here's another take on this. contextlib.redirect_stdout
with io.StringIO()
as documented is great, but it's still a bit verbose for every day use. Here's how to make it a one-liner by subclassing contextlib.redirect_stdout
:
import sys
import io
from contextlib import redirect_stdout
class capture(redirect_stdout):
def __init__(self):
self.f = io.StringIO()
self._new_target = self.f
self._old_targets = [] # verbatim from parent class
def __enter__(self):
self._old_targets.append(getattr(sys, self._stream)) # verbatim from parent class
setattr(sys, self._stream, self._new_target) # verbatim from parent class
return self # instead of self._new_target in the parent class
def __repr__(self):
return self.f.getvalue()
Since __enter__ returns self, you have the context manager object available after the with block exits. Moreover, thanks to the __repr__ method, the string representation of the context manager object is, in fact, stdout. So now you have,
with capture() as message:
print('Hello World!')
print(str(message)=='Hello World!\n') # returns True
Starting with Version 42, released April 14, 2015, Chrome blocks all NPAPI plugins, including Java. Until September 2015 there will be a way around this, by going to chrome://flags/#enable-npapi
and clicking on Enable
. After that, you will have to use the IE tab extension to run the Direct-X version of the Java plugin.
Base(Base::UPtr n):next(std::move(n)) {}
should be much better as
Base(Base::UPtr&& n):next(std::forward<Base::UPtr>(n)) {}
and
void setNext(Base::UPtr n)
should be
void setNext(Base::UPtr&& n)
with same body.
And ... what is evt
in handle()
??
For nodemon users: Just use the --ignore flag to solve the problem.
Example:
nodemon app.js --ignore node_modules/ --ignore data/
I had a similar problem (using 3.5) and lost 1/2 a day to it but here is a something that works - I am retired and just learning Python so I can help my grandson (12) with it.
mydict2={'Atlanta':78,'Macon':85,'Savannah':72}
maxval=(max(mydict2.values()))
print(maxval)
mykey=[key for key,value in mydict2.items()if value==maxval][0]
print(mykey)
YEILDS;
85
Macon
I had this same problem.
Did:
f1 = plt.figure(1)
# code for figure 1
# don't write 'plt.show()' here
f2 = plt.figure(2)
# code for figure 2
plt.show()
Write 'plt.show()' only once, after the last figure.
Worked for me.
The best way to do this would be to use the promise returning function as it is, like this
lookupValue(file).then(function(res) {
// Write the code which depends on the `res.val`, here
});
The function which invokes an asynchronous function cannot wait till the async function returns a value. Because, it just invokes the async function and executes the rest of the code in it. So, when an async function returns a value, it will not be received by the same function which invoked it.
So, the general idea is to write the code which depends on the return value of an async function, in the async function itself.
from PIL import Image
image = Image.open('File.jpg')
image.show()
You just need to manually set the desired permissions with chmod()
:
private function writeFileContent($file, $content){
$fp = fopen($file, 'w');
fwrite($fp, $content);
fclose($fp);
// Set perms with chmod()
chmod($file, 0777);
return true;
}
import numpy as np
from scipy.spatial import distance
input_arr = np.array([[0,3,0],[2,0,0],[0,1,3],[0,1,2],[-1,0,1],[1,1,1]])
test_case = np.array([0,0,0])
dst=[]
for i in range(0,6):
temp = distance.euclidean(test_case,input_arr[i])
dst.append(temp)
print(dst)
By Default it stores to:
String DATABASE_PATH = "/data/data/" + PACKAGE_NAME + "/databases/" + DATABASE_NAME;
Where:
String DATABASE_NAME = "your_dbname";
String PACKAGE_NAME = "com.example.your_app_name";
And check whether your database is stored to Device Storage. If So, You have to use permission in Manifest.xml :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Options -MultiViews -Indexes
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
#cambiamos el valor para subir archivos
php_value memory_limit 400M
php_value post_max_size 400M
php_value upload_max_filesize 400M
php_value max_execution_time 300 #esta es la linea que necesitas agregar.
Just coerce the StatusCode
to int
.
var statusNumber;
try {
response = (HttpWebResponse)request.GetResponse();
// This will have statii from 200 to 30x
statusNumber = (int)response.StatusCode;
}
catch (WebException we) {
// Statii 400 to 50x will be here
statusNumber = (int)we.Response.StatusCode;
}
Set the architecture in build setting to Standard architectures(armv7,armv7s)
iPhone 5S is powered by A7 64bit processor. From apple docs
Xcode can build your app with both 32-bit and 64-bit binaries included. This combined binary requires a minimum deployment target of iOS 7 or later.
Note: A future version of Xcode will let you create a single app that supports the 32-bit runtime on iOS 6 and later, and that supports the 64-bit runtime on iOS 7.
From the documentation what i understood is
Update (Xcode 5.0.1)
In Xcode 5.0.1 they added the support to create 64 bit binary for iOS 5.1.1 onwards.
Xcode 5.0.1 can build your app with both 32-bit and 64-bit binaries included. This combined binary requires a minimum deployment target of iOS 5.1.1 or later. The 64-bit binary runs only on 64-bit devices running iOS 7.0.3 and later.
Update (Xcode 5.1)
Xcode 5.1 made significant change in the architecture section. This answer will be a followup for you.
Check this
I love how people completely miss the request in the original question for an IDE. Linux is NOT an IDE. That's just not what those words mean. I learned c and c++ using vi and gcc and make, and I'm not saying they aren't adequate tools, but they are NOT an IDE. Even if you use more elaborate tools like vim or emacs or whatever fancy editor you want, typing commands on a command line is not an IDE.
Also, you all know make exists as part of visual studio right? The idea that an IDE is "limiting" is just silly if you can use the IDE to speed some things, yet are still able to fall back on command line stuff when needed.
All that said, I'd suggest, as several above have, trying Code blocks. Its got decent code highlighting, a pretty effortless way to create a project, code it, run it, etc, that is the core of a real IDE, and seems fairly stable. Debugging sucks...I have never seen a decent interactive debugger in any linux/unix variant. gdb ain't it. If you're used to visual studio style debugging, you're pretty much out of luck.
Anyway, I'll go pack my things, I know the one-view-only linux crowd will shout this down and run me out of town in no time.
The answer that helped me: The directive [(ngModel)]= not working anymore in rc5
To sum it up: input fields now require property name
in the form.
In my case the problem was that https was unable to start correctly because Listen 443 was in "IfDefine SSL" derective, but my apache didnt start with -DSSL option. The fix was to change my apachectl script in:
$HTTPD -k $ARGV
to:
$HTTPD -k $ARGV -DSSL
Hope that helps somebody.
Sorry you're not using PostgreSQL...
SELECT DISTINCT ON contract, activity * FROM thetable ORDER BY contract, activity
http://www.postgresql.org/docs/8.3/static/sql-select.html#SQL-DISTINCT
Oh wait. You only want values with exactly one...
SELECT contract, activity, count() FROM thetable GROUP BY contract, activity HAVING count() = 1
I came to add:
map(str.strip, string.split(','))
but saw it had already been mentioned by Jason Orendorff in a comment.
Reading Glenn Maynard's comment in the same answer suggesting list comprehensions over map I started to wonder why. I assumed he meant for performance reasons, but of course he might have meant for stylistic reasons, or something else (Glenn?).
So a quick (possibly flawed?) test on my box applying the three methods in a loop revealed:
[word.strip() for word in string.split(',')]
$ time ./list_comprehension.py
real 0m22.876s
map(lambda s: s.strip(), string.split(','))
$ time ./map_with_lambda.py
real 0m25.736s
map(str.strip, string.split(','))
$ time ./map_with_str.strip.py
real 0m19.428s
making map(str.strip, string.split(','))
the winner, although it seems they are all in the same ballpark.
Certainly though map (with or without a lambda) should not necessarily be ruled out for performance reasons, and for me it is at least as clear as a list comprehension.
Edit:
Python 2.6.5 on Ubuntu 10.04
Try
gadget_url.value=''
addGadgetUrl.addEventListener('click', () => {_x000D_
gadget_url.value = '';_x000D_
});
_x000D_
<div>_x000D_
<p>URL</p>_x000D_
<input type="text" name="gadget_url" id="gadget_url" style="width: 350px;" class="input" value="some value" />_x000D_
<input type="button" id="addGadgetUrl" value="add gadget" />_x000D_
<br>_x000D_
<span id="error"></span>_x000D_
</div>
_x000D_
I don't know why so many downovotes (and no comments) - however (for future readers) don't think that this solution not work - It works with html provided in OP question and this is SHORTEST working solution - you can try it by yourself HERE
Pure html is not able to do what you want. My suggestion would be to write a simple javascript function to do the roudning for you.
you can use json_decode
function
foreach (json_decode($response) as $area)
{
print_r($area); // this is your area from json response
}
See this fiddle
I Had similar issue. Every project has his own gradle folder, check if in your project root there's another gradle folder:
/my_projects_root_folder/project/gradle
/my_projects_root_folder/gradle
If so, in every folder you'll find /gradle/wrapper/gradle-wrapper.properties.
Check if in /my_projects_root_folder/gradle/gradle-wrapper.properties gradle version at least match /my_projects_root_folder/ project/ gradle/ gradle-wrapper.properties gradle version
Or just delete/rename your /my_projects_root_folder/gradle and restart android studio and let Gradle sync work and download required gradle.
Process p;
StringBuffer output = new StringBuffer();
try {
p = Runtime.getRuntime().exec(params[0]);
BufferedReader reader = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
p.waitFor();
}
}
catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
String response = output.toString();
return response;
To run another Python environment according to the official Virtualenv documentation, in the command line you can specify the full path to the executable Python binary, just that (no need to active the virtualenv before):
/path/to/virtualenv/bin/python
The same applies if you want to invoke a script from the command line with your virtualenv. You don't need to activate it before:
me$ /path/to/virtualenv/bin/python myscript.py
The same for a Windows environment (whether it is from the command line or from a script):
> \path\to\env\Scripts\python.exe myscript.py
This is the way I do the Scala Parser Combinator Library:
import scala.util.parsing.combinator._
class ImprovedJsonParser extends JavaTokenParsers {
def obj: Parser[Map[String, Any]] =
"{" ~> repsep(member, ",") <~ "}" ^^ (Map() ++ _)
def array: Parser[List[Any]] =
"[" ~> repsep(value, ",") <~ "]"
def member: Parser[(String, Any)] =
stringLiteral ~ ":" ~ value ^^ { case name ~ ":" ~ value => (name, value) }
def value: Parser[Any] = (
obj
| array
| stringLiteral
| floatingPointNumber ^^ (_.toDouble)
|"true"
|"false"
)
}
object ImprovedJsonParserTest extends ImprovedJsonParser {
def main(args: Array[String]) {
val jsonString =
"""
{
"languages": [{
"name": "English",
"is_active": true,
"completeness": 2.5
}, {
"name": "Latin",
"is_active": false,
"completeness": 0.9
}]
}
""".stripMargin
val result = parseAll(value, jsonString)
println(result)
}
}
See ?read.table
. Basically, when you use read.table
, you specify a number indicating the column:
##Row names in the first column
read.table(filname.txt, row.names=1)
SELECT
a AS [blabla a],
b [blabla b],
CASE c
WHEN 1 THEN 'aaa'
WHEN 2 THEN 'bbb'
ELSE 'unknown'
END AS [my alias],
d AS [blabla d]
FROM mytable
A SurfaceView
is a custom view in Android that can be used to drawn inside it.
The main difference between a View
and a SurfaceView
is that a View is drawn in the
UI Thread
, which is used for all the user interaction.
If you want to update the UI rapidly enough and render a good amount of information in
it, a SurfaceView is a better choice.
But there are a few technical insides to the SurfaceView
:
1. They are not hardware accelerated.
2. Normal views are rendered when you call the methods invalidate
or postInvalidate()
, but this does not mean the view will be
immediately updated (A VSYNC
will be sent, and the OS decides when
it gets updated. The SurfaceView
can be immediately updated.
3. A SurfaceView has an allocated surface buffer
, so it is more costly
If a GPU device has, for example, 4 multiprocessing units, and they can run 768 threads each: then at a given moment no more than 4*768 threads will be really running in parallel (if you planned more threads, they will be waiting their turn).
threads are organized in blocks. A block is executed by a multiprocessing unit. The threads of a block can be indentified (indexed) using 1Dimension(x), 2Dimensions (x,y) or 3Dim indexes (x,y,z) but in any case xyz <= 768 for our example (other restrictions apply to x,y,z, see the guide and your device capability).
Obviously, if you need more than those 4*768 threads you need more than 4 blocks. Blocks may be also indexed 1D, 2D or 3D. There is a queue of blocks waiting to enter the GPU (because, in our example, the GPU has 4 multiprocessors and only 4 blocks are being executed simultaneously).
Suppose we want one thread to process one pixel (i,j).
We can use blocks of 64 threads each. Then we need 512*512/64 = 4096 blocks (so to have 512x512 threads = 4096*64)
It's common to organize (to make indexing the image easier) the threads in 2D blocks having blockDim = 8 x 8 (the 64 threads per block). I prefer to call it threadsPerBlock.
dim3 threadsPerBlock(8, 8); // 64 threads
and 2D gridDim = 64 x 64 blocks (the 4096 blocks needed). I prefer to call it numBlocks.
dim3 numBlocks(imageWidth/threadsPerBlock.x, /* for instance 512/8 = 64*/
imageHeight/threadsPerBlock.y);
The kernel is launched like this:
myKernel <<<numBlocks,threadsPerBlock>>>( /* params for the kernel function */ );
Finally: there will be something like "a queue of 4096 blocks", where a block is waiting to be assigned one of the multiprocessors of the GPU to get its 64 threads executed.
In the kernel the pixel (i,j) to be processed by a thread is calculated this way:
uint i = (blockIdx.x * blockDim.x) + threadIdx.x;
uint j = (blockIdx.y * blockDim.y) + threadIdx.y;
Try Aspose.Words for java.
Aspose.Words for Java is an advanced (commercial) class library for Java that enables you to perform a great range of document processing tasks directly within your Java applications.
Aspose.Words for Java supports DOC, OOXML, RTF, HTML and OpenDocument formats. With Aspose.Words you can generate, modify, and convert documents without using Microsoft Word.
Adding to the above answers: To find the package name of installed apps on any android device: Go to Storage/Android/data/< package-name >
Use lodash as bertandg indicated. The reason angular no longer has this method, is because angular 1 was a stand-alone framework, and external libraries often ran into issues with the angular execution context. Angular 2 does not have that problem, so use whatever library that you want.
If you have a function like:
int foo()
{
// more stuff
foo();
}
Then foo() will keep calling itself, getting deeper and deeper, and when the space used to keep track of what functions you're in is filled up, you get the stack overflow error.
Converting String array into stream and mapping to int is the best option available in java 8.
String[] stringArray = new String[] { "0", "1", "2" };
int[] intArray = Stream.of(stringArray).mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(intArray));
I like those built-in php date expressions like +1 hour
, but for some reason, they fall out of my head all of the time. Besides, none of the IDEs I'm aware of suggest auto-completion facility for that kind of stuff. And, finally, although juggling with those strtotime
and date
functions is no rocket science, I have to google their usage each time I need them.
That's why I like the solution that eliminates (at least mitigates) those issues. Here's how adding x
hours to a date can look like:
(new Future(
new DateTimeFromISO8601String('2014-11-21T06:04:31.321987+00:00'),
new NHours($x)
))
->value();
As a nice bonus, you don't have to worry about formatting the resulting value, it's already is ISO8601 format.
This example uses meringue library, you can check out more examples here.
try:
gsub('\\$', '', '$5.00$')
For checkbox with an id
<input id="id_input_checkbox13" type="checkbox"></input>
you can simply do
$("#id_input_checkbox13").prop('checked')
you will get true
or false
as return value for above syntax. You can use it in if clause as normal boolean expression.
For me it works:
document.getElementById("checkyear").value = "1";
alert(document.getElementById("checkyear").value);
Maybe your JS is not executed and you need to add a function() {} around it all.
Here is a solution based on the answer by Henrik Karlsson but with proper event triggering (based on Bootstrap sources):
$(function(){
$('[data-hide]').on('click', function ___alert_hide(e) {
var $this = $(this)
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = $(selector === '#' ? [] : selector)
if (!$parent.length) {
$parent = $this.closest('.alert')
}
$parent.trigger(e = $.Event('close.bs.alert'))
if (e.isDefaultPrevented()) return
$parent.hide()
$parent.trigger($.Event('closed.bs.alert'))
})
});
The answer mostly for me, as a note.
Found the solution in Spring security examples posted in Github.
WebSecurityConfigurerAdapter
has a overloaded configure
message that takes WebSecurity
as argument which accepts ant matchers on requests to be ignored.
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/authFailure");
}
See Spring Security Samples for more details
This sounds like an output formatting issue? If using SQL Plus, use the COLUMN command like this (assuming you want a maximum display width of 20 chars for each):
column a format a20
column b format a20
select a, b from mytable;
Simply use Window.Maximize()
command
WebDriver driver= new ChromeDriver()
driver.Manage().Window.Maximize();
Installing git and running npm install from git-bash worked for me. Make sure you are in the correct directory.
You shouldn't have to care that much. RFC 3339, according to itself, is a set of standards derived from ISO 8601. There's quite a few minute differences though, and they're all outlined in RFC 3339. I could go through them all here, but you'd probably do better just reading the document for yourself in the event you're worried:
The book is a bit dated with respect to subclass-superclass calling. It's also a little dated with respect to subclassing built-in classes.
It looks like this nowadays:
class FileInfo(dict):
"""store file metadata"""
def __init__(self, filename=None):
super(FileInfo, self).__init__()
self["name"] = filename
Note the following:
We can directly subclass built-in classes, like dict
, list
, tuple
, etc.
The super
function handles tracking down this class's superclasses and calling functions in them appropriately.
I use the tail
function:
tail(vector, n=1)
The nice thing with tail
is that it works on dataframes too, unlike the x[length(x)]
idiom.
I don't know about the Android specifics for ssl certificates, but it would make sense that Android won't accept a self signed ssl certificate off the bat. I found this post from android forums which seems to be addressing the same issue: http://androidforums.com/android-applications/950-imap-self-signed-ssl-certificates.html
To stop just some cells being selected use:
cell.userInteractionEnabled = NO;
As well as preventing selection, this also stops tableView:didSelectRowAtIndexPath: being called for the cells that have it set.
I think it is possible but only for a short time
What you have to do is set the Access Control List of the file to Public Read-Only (or Public Read/Write). You can do that programmatically using the Google Document List API, or manually through the "Share" button on the Drive image viewer.
Then you can get the URL to the image programmatically by either using the Google Document List API or using the Google Drive API (i.e. file.getDownloadUrl() in Java). You can also easily get a link to the image manually by right clicking on the image in the Google Drive default image viewer.
The problem is that this link has a limited time to live, so it will work for a little while and then stop working.
Basically the URL of the image file stored in Drive should be accessible without any authentication once it has been set shared publicly but that URL is going to change at some point. We might find a solution to this in the future like providing a permanent URL that will redirect to these changing URL but no promises...
With the standard library:
HTML Escape
try:
from html import escape # python 3.x
except ImportError:
from cgi import escape # python 2.x
print(escape("<"))
HTML Unescape
try:
from html import unescape # python 3.4+
except ImportError:
try:
from html.parser import HTMLParser # python 3.x (<3.4)
except ImportError:
from HTMLParser import HTMLParser # python 2.x
unescape = HTMLParser().unescape
print(unescape(">"))
One of the reasons why the global variable needs a prefix (called a "sigil") is because in Ruby, unlike in C, you don't have to declare your variables before assigning to them. The sigil is used as a way to be explicit about the scope of the variable.
Without a specific prefix for globals, given a statement pointNew = offset + point
inside your draw
method then offset
refers to a local variable inside the method (and results in a NameError
in this case). The same for @
used to refer to instance variables and @@
for class variables.
In other languages that use explicit declarations such as C
, Java
etc. the placement of the declaration is used to control the scope.
In theory SMTP can be handled by either TCP, UDP, or some 3rd party protocol.
As defined in RFC 821, RFC 2821, and RFC 5321:
SMTP is independent of the particular transmission subsystem and requires only a reliable ordered data stream channel.
In addition, the Internet Assigned Numbers Authority has allocated port 25 for both TCP and UDP for use by SMTP.
In practice however, most if not all organizations and applications only choose to implement the TCP protocol. For example, in Microsoft's port listing port 25 is only listed for TCP and not UDP.
The big difference between TCP and UDP that makes TCP ideal here is that TCP checks to make sure that every packet is received and re-sends them if they are not whereas UDP will simply send packets and not check for receipt. This makes UDP ideal for things like streaming video where every single packet isn't as important as keeping a continuous flow of packets from the server to the client.
Considering SMTP, it makes more sense to use TCP over UDP. SMTP is a mail transport protocol, and in mail every single packet is important. If you lose several packets in the middle of the message the recipient might not even receive the message and if they do they might be missing key information. This makes TCP more appropriate because it ensures that every packet is delivered.
The strncpy()
function is the safer one: you have to pass the maximum length the destination buffer can accept. Otherwise it could happen that the source string is not correctly 0 terminated, in which case the strcpy()
function could write more characters to destination, corrupting anything which is in the memory after the destination buffer. This is the buffer-overrun problem used in many exploits
Also for POSIX API functions like read()
which does not put the terminating 0 in the buffer, but returns the number of bytes read, you will either manually put the 0, or copy it using strncpy()
.
In your example code, index
is actually not an index, but a count
- it tells how many characters at most to copy from source to destination. If there is no null byte among the first n bytes of source, the string placed in destination will not be null terminated
I'd like to supplement BalusC's answer with the mapping rules and an example.
Mapping rules from Servlet 2.5 specification:
In our example, there're three servlets. / is the default servlet installed by us. Tomcat installs two servlets to serve jsp and jspx. So to map http://host:port/context/hello
To map http://host:port/context/hello.jsp
The following query should give the exact stuff you are looking out for.
select datediff(second, '2010-01-22 15:29:55.090' , '2010-01-22 15:30:09.153')
Here is the link from MSDN for what all you can do with datediff function . https://msdn.microsoft.com/en-us/library/ms189794.aspx
You can use Boost numeric_cast
.
This throws an exception if the source value is out of range of the destination type, but it doesn't detect loss of precision when converting to double
.
Whatever function you use, though, you should decide what you want to happen in the case where the value in the size_t
is greater than INT_MAX
. If you want to detect it use numeric_cast
or write your own code to check. If you somehow know that it cannot possibly happen then you could use static_cast
to suppress the warning without the cost of a runtime check, but in most cases the cost doesn't matter anyway.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = sdf.parse(time);
String formattedTime = output.format(d);
This works. You have to use two SimpleDateFormats, one for input and one for output, but it will give you just what you are wanting.
Instead of WorksheetFunction.Vlookup
, you can use Application.Vlookup
. If you set a Variant
equal to this it returns Error 2042 if no match is found. You can then test the variant - cellNum
in this case - with IsError
:
Sub test()
Dim ws As Worksheet: Set ws = Sheets("2012")
Dim rngLook As Range: Set rngLook = ws.Range("A:M")
Dim currName As String
Dim cellNum As Variant
'within a loop
currName = "Example"
cellNum = Application.VLookup(currName, rngLook, 13, False)
If IsError(cellNum) Then
MsgBox "no match"
Else
MsgBox cellNum
End If
End Sub
The Application
versions of the VLOOKUP
and MATCH
functions allow you to test for errors without raising the error. If you use the WorksheetFunction
version, you need convoluted error handling that re-routes your code to an error handler, returns to the next statement to evaluate, etc. With the Application
functions, you can avoid that mess.
The above could be further simplified using the IIF
function. This method is not always appropriate (e.g., if you have to do more/different procedure based on the If/Then
) but in the case of this where you are simply trying to determinie what prompt to display in the MsgBox, it should work:
cellNum = Application.VLookup(currName, rngLook, 13, False)
MsgBox IIF(IsError(cellNum),"no match", cellNum)
Consider those methods instead of On Error ...
statements. They are both easier to read and maintain -- few things are more confusing than trying to follow a bunch of GoTo
and Resume
statements.
I found a solution that is more efficient than currently accepted answer, because current answer forces all list elements to be refreshed. My solution will refresh only one element (that was touched) by calling adapters getView and recycling current view which adds even more efficiency.
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Edit object data that is represented in Viewat at list's "position"
view = mAdapter.getView(position, view, parent);
}
});
Just make sure build with correct web.xml configuration.I have update web.xml with tomcat configuration and it worked for me. Sample :-
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"_x000D_
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"_x000D_
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"_x000D_
id="WebApp_ID" version="2.5">_x000D_
<display-name>simulator</display-name>_x000D_
<description>simulator app</description>_x000D_
_x000D_
_x000D_
<!-- File upload -->_x000D_
<welcome-file-list>_x000D_
<welcome-file>index.html</welcome-file>_x000D_
</welcome-file-list>_x000D_
<!-- excel simulation -->_x000D_
<display-name>simulator</display-name>_x000D_
<description>simulator app</description>_x000D_
<!-- File upload -->_x000D_
<welcome-file-list>_x000D_
<welcome-file>InsertPage.html</welcome-file>_x000D_
</welcome-file-list>_x000D_
<servlet>_x000D_
<servlet-name>FileUploadServlet</servlet-name>_x000D_
<servlet-class>clari5.excel.FileUploadServlet</servlet-class>_x000D_
<load-on-startup>1</load-on-startup>_x000D_
</servlet>_x000D_
<servlet-mapping>_x000D_
<servlet-name>FileUploadServlet</servlet-name>_x000D_
<url-pattern>/excelSimulator/FileUploadServlet</url-pattern>_x000D_
</servlet-mapping>_x000D_
_x000D_
_x000D_
_x000D_
</web-app>
_x000D_