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()
I had the same problem. mysql -u root -p
worked for me. It later asks you for a password. You should then enter the password that you had set for mysql. The default password could be password
, if you did not set one. More info here.
This works better than All please refer to this property.
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
projectVO = objectMapper.readValue(yourjsonstring, Test.class);
As mentioned here, this feature is not currently supported.
I've created a pared-down demo project for you.
You can try the above API Link from your local Fiddler to see the headers. Here is an explanation.
All this does is call the WebApiConfig
. It's nothing but code organization.
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
WebApiConfig.Register(GlobalConfiguration.Configuration);
}
}
The key method for your here is the EnableCrossSiteRequests
method. This is all that you need to do. The EnableCorsAttribute
is a globally scoped CORS attribute.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
EnableCrossSiteRequests(config);
AddRoutes(config);
}
private static void AddRoutes(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "Default",
routeTemplate: "api/{controller}/"
);
}
private static void EnableCrossSiteRequests(HttpConfiguration config)
{
var cors = new EnableCorsAttribute(
origins: "*",
headers: "*",
methods: "*");
config.EnableCors(cors);
}
}
The Get
method receives the EnableCors
attribute that we applied globally. The Another
method overrides the global EnableCors
.
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] {
"This is a CORS response.",
"It works from any origin."
};
}
// GET api/values/another
[HttpGet]
[EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")]
public IEnumerable<string> Another()
{
return new string[] {
"This is a CORS response. ",
"It works only from two origins: ",
"1. www.bigfont.ca ",
"2. the same origin."
};
}
}
You do not need to add anything special into web.config. In fact, this is what the demo's web.config looks like - it's empty.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
</configuration>
var url = "https://cors-webapi.azurewebsites.net/api/values"_x000D_
_x000D_
$.get(url, function(data) {_x000D_
console.log("We expect this to succeed.");_x000D_
console.log(data);_x000D_
});_x000D_
_x000D_
var url = "https://cors-webapi.azurewebsites.net/api/values/another"_x000D_
_x000D_
$.get(url, function(data) {_x000D_
console.log(data);_x000D_
}).fail(function(xhr, status, text) {_x000D_
console.log("We expect this to fail.");_x000D_
console.log(status);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
I use SOAPUI 5.3.0
, it has an option for creating requests/responses (also using WSDL), you can even create a mock service which will respond when you send request. Procedure is as follows:
EDIT #1:
Check out the SoapUI link for the latest version. There is a Pro version as well as the free open source version.
Yes, there does seem to be 3rd libraries (none in Java Math). Two that have come up are:
http://www.iro.umontreal.ca/~simardr/ssj/indexe.html
but, it is actually not that difficult to write your own methods to calculate mean, median, mode and range.
MEAN
public static double mean(double[] m) {
double sum = 0;
for (int i = 0; i < m.length; i++) {
sum += m[i];
}
return sum / m.length;
}
MEDIAN
// the array double[] m MUST BE SORTED
public static double median(double[] m) {
int middle = m.length/2;
if (m.length%2 == 1) {
return m[middle];
} else {
return (m[middle-1] + m[middle]) / 2.0;
}
}
MODE
public static int mode(int a[]) {
int maxValue, maxCount;
for (int i = 0; i < a.length; ++i) {
int count = 0;
for (int j = 0; j < a.length; ++j) {
if (a[j] == a[i]) ++count;
}
if (count > maxCount) {
maxCount = count;
maxValue = a[i];
}
}
return maxValue;
}
UPDATE
As has been pointed out by Neelesh Salpe, the above does not cater for multi-modal collections. We can fix this quite easily:
public static List<Integer> mode(final int[] numbers) {
final List<Integer> modes = new ArrayList<Integer>();
final Map<Integer, Integer> countMap = new HashMap<Integer, Integer>();
int max = -1;
for (final int n : numbers) {
int count = 0;
if (countMap.containsKey(n)) {
count = countMap.get(n) + 1;
} else {
count = 1;
}
countMap.put(n, count);
if (count > max) {
max = count;
}
}
for (final Map.Entry<Integer, Integer> tuple : countMap.entrySet()) {
if (tuple.getValue() == max) {
modes.add(tuple.getKey());
}
}
return modes;
}
ADDITION
If you are using Java 8 or higher, you can also determine the modes like this:
public static List<Integer> getModes(final List<Integer> numbers) {
final Map<Integer, Long> countFrequencies = numbers.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
final long maxFrequency = countFrequencies.values().stream()
.mapToLong(count -> count)
.max().orElse(-1);
return countFrequencies.entrySet().stream()
.filter(tuple -> tuple.getValue() == maxFrequency)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}
Inside your script file, put all of the commands within parentheses, like this:
(
echo start
ls -l
echo end
) | tee foo.log
I've been looking into this approach:
function getServerObject(serverObject) {
if (typeof serverObject === "undefined") {
return null;
}
return serverObject;
}
var itCameFromDotNet = getServerObject(@dotNetObject);
To me this seems to make it safer on the JS side... worst case you end up with a null variable.
Try to use this:
HTML:
<input ID="fileUpload1" runat="server" type="file">
JavaScript:
$("#fileUpload1").on('change',function() {
alert('Works!!');
});
?
Here's how you do it
private fun sendNotification() {
val notificationId = 100
val chanelid = "chanelid"
val intent = Intent(this, MainActivity::class.java)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, 0)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // you must create a notification channel for API 26 and Above
val name = "my channel"
val description = "channel description"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(chanelid, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
val notificationManager = getSystemService(NotificationManager::class.java)
notificationManager.createNotificationChannel(channel)
}
val mBuilder = NotificationCompat.Builder(this, chanelid)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Want to Open My App?")
.setContentText("Open my app and see good things")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true) // cancel the notification when clicked
.addAction(R.drawable.ic_check, "YES", pendingIntent) //add a btn to the Notification with a corresponding intent
val notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(notificationId, mBuilder.build());
}
Read full tutorial at => https://developer.android.com/training/notify-user/build-notification
Yes, there are special server side comments:
<%-- Text not sent to client --%>
Sadly none of the solutions worked for me! I solved my problem by uninstalling existing APK from my phone and it all started working perfectly!
This started happening after I've updated android studio to latest version.
With PHP 5.3, you can now do this:
function doIt($callback) { $callback(); }
doIt(function() {
// this will be done
});
Finally a nice way to do it. A great addition to PHP, because callbacks are awesome.
There are number of ways to do it:
Using filter()
(and operator)
query = meta.Session.query(User).filter(
User.firstname.like(search_var1),
User.lastname.like(search_var2)
)
Using filter_by()
(and operator)
query = meta.Session.query(User).filter_by(
firstname.like(search_var1),
lastname.like(search_var2)
)
Chaining filter()
or filter_by()
(and operator)
query = meta.Session.query(User).\
filter_by(firstname.like(search_var1)).\
filter_by(lastname.like(search_var2))
Using or_()
, and_()
, and not()
from sqlalchemy import and_, or_, not_
query = meta.Session.query(User).filter(
and_(
User.firstname.like(search_var1),
User.lastname.like(search_var2)
)
)
This solved my problem
var url = "http://localhost/tech1/index.php?route=app/upload/ajax";
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
var $link = $('.'+ids);
var $img = $link.find('i');
$link.html('Uploading..('+percentComplete+'%)');
$link.append($img);
}
}, false);
return xhr;
},
url: url,
type: "POST",
data: JSON.stringify(uploaddata),
contentType: "application/json",
dataType: "json",
success: function(result) {
console.log(result);
}
});
Those answers aren't bad, but they are limited in that they don't actually allow you to enter data. We had a similar problem where we were using barcode readers to enter data into a field, but we wanted to suppress the keyboard.
This is what I put together, it works pretty well:
https://codepen.io/bobjase/pen/QrQQvd/
<!-- must be a select box with no children to suppress the keyboard -->
input: <select id="hiddenField" />
<span id="fakecursor" />
<input type="text" readonly="readonly" id="visibleField" />
<div id="cursorMeasuringDiv" />
#hiddenField {
height:17px;
width:1px;
position:absolute;
margin-left:3px;
margin-top:2px;
border:none;
border-width:0px 0px 0px 1px;
}
#cursorMeasuringDiv {
position:absolute;
visibility:hidden;
margin:0px;
padding:0px;
}
#hiddenField:focus {
border:1px solid gray;
border-width:0px 0px 0px 1px;
outline:none;
animation-name: cursor;
animation-duration: 1s;
animation-iteration-count: infinite;
}
@keyframes cursor {
from {opacity:0;}
to {opacity:1;}
}
// whenever the visible field gets focused
$("#visibleField").bind("focus", function(e) {
// silently shift the focus to the hidden select box
$("#hiddenField").focus();
$("#cursorMeasuringDiv").css("font", $("#visibleField").css("font"));
});
// whenever the user types on his keyboard in the select box
// which is natively supported for jumping to an <option>
$("#hiddenField").bind("keypress",function(e) {
// get the current value of the readonly field
var currentValue = $("#visibleField").val();
// and append the key the user pressed into that field
$("#visibleField").val(currentValue + e.key);
$("#cursorMeasuringDiv").text(currentValue + e.key);
// measure the width of the cursor offset
var offset = 3;
var textWidth = $("#cursorMeasuringDiv").width();
$("#hiddenField").css("marginLeft",Math.min(offset+textWidth,$("#visibleField").width()));
});
When you click in the <input>
box, it simulates a cursor in that box but really puts the focus on an empty <select>
box. Select boxes naturally allow for keypresses to support jumping to an element in the list so it was only a matter of rerouting the keypress to the original input and offsetting the simulated cursor.
This won't work for backspace, delete, etc... but we didn't need those. You could probably use jQuery's trigger to send the keyboard event directly to another input box somewhere but we didn't need to bother with that so I didn't do it.
Hope this useful for you.
$(document).click(function(e){
if ($('#news_gallery').on('clicked')) {
var article = $('#news-article .news-article');
}
});
For those coming here and are using Java config you can set the Bean to lazy-init using annotations like this:
In the configuration class:
@Configuration
// @Lazy - For all Beans to load lazily
public class AppConf {
@Bean
@Lazy
public Demo demo() {
return new Demo();
}
}
For component scanning and auto-wiring:
@Component
@Lazy
public class Demo {
....
....
}
@Component
public class B {
@Autowired
@Lazy // If this is not here, Demo will still get eagerly instantiated to satisfy this request.
private Demo demo;
.......
}
You can use IPython's Module: display
to load the image. You can read more from the Doc.
from IPython.display import Image
pil_img = Image(filename='data/empire.jpg')
display(pil_img)
As OP's requirement is to use PIL
, if you want to show inline image, you can use matplotlib.pyplot.imshow
with numpy.asarray
like this too:
from matplotlib.pyplot import imshow
import numpy as np
from PIL import Image
%matplotlib inline
pil_im = Image.open('data/empire.jpg', 'r')
imshow(np.asarray(pil_im))
If you only require a preview rather than an inline, you may just use show
like this:
pil_im = Image.open('data/empire.jpg', 'r')
pil_im.show()
I had a lot of problems with the complete load of a image and the EventListener.
Whatever I tried, the results was not reliable.
But then I found the solution. It is technically not a nice one, but now I never had a failed image load.
What I did:
document.getElementById(currentImgID).addEventListener("load", loadListener1);
document.getElementById(currentImgID).addEventListener("load", loadListener2);
function loadListener1()
{
// Load again
}
function loadListener2()
{
var btn = document.getElementById("addForm_WithImage"); btn.disabled = false;
alert("Image loaded");
}
Instead of loading the image one time, I just load it a second time direct after the first time and both run trough the eventhandler.
All my headaches are gone!
By the way: You guys from stackoverflow helped me already more then hundred times. For this a very big Thank you!
You cannot specify target table for delete.
A workaround
create table term_hierarchy_backup (tid int(10)); <- check data type
insert into term_hierarchy_backup
SELECT DISTINCT(th1.tid)
FROM term_hierarchy AS th1
INNER JOIN term_hierarchy AS th2 ON (th1.tid = th2.tid AND th2.parent != 1015)
WHERE th1.parent = 1015;
DELETE FROM term_hierarchy AS th
WHERE th.parent = 1015 AND th.tid IN (select tid from term_hierarchy_backup);
First of all, I don't really see why you would want an object having only ID and Version, and all other props to be nulls. However, here is some code which will do that for you (which doesn't use JPA Em, but normal Hibernate. I assume you can find the equivalence in JPA or simply obtain the Hibernate Session obj from the em delegate Accessing Hibernate Session from EJB using EntityManager ):
List<T> results = session.createCriteria(entityClazz)
.setProjection( Projections.projectionList()
.add( Property.forName("ID") )
.add( Property.forName("VERSION") )
)
.setResultTransformer(Transformers.aliasToBean(entityClazz);
.list();
This will return a list of Objects having their ID and Version set and all other props to null, as the aliasToBean transformer won't be able to find them. Again, I am uncertain I can think of a situation where I would want to do that.
You can just use the attribute selector and then test the length:
$('input[readonly]').length == 0 // --> ok
$('input[readonly]').length > 0 // --> not ok
This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):
SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC
This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.
I was trying to write in nodejs and finally came up with this:
db.collection('collectionName').mapReduce(
function() {
for (var key in this) {
emit(key, null);
}
},
function(key, stuff) {
return null;
}, {
"out": "allFieldNames"
},
function(err, results) {
var fields = db.collection('allFieldNames').distinct('_id');
fields
.then(function(data) {
var finalData = {
"status": "success",
"fields": data
};
res.send(finalData);
delteCollection(db, 'allFieldNames');
})
.catch(function(err) {
res.send(err);
delteCollection(db, 'allFieldNames');
});
});
After reading the newly created collection "allFieldNames", delete it.
db.collection("allFieldNames").remove({}, function (err,result) {
db.close();
return;
});
This uses the modulo 10 method to figure out each digit in a number greater than 0, then this will reverse the order of the array. This is assuming you are not using "0" as a starting digit.
This is modified to take in user input.
This array is originally inserted backwards, so I had to use the Collections.reverse()
call to put it back into the user's order.
Scanner scanNumber = new Scanner(System.in);
int userNum = scanNumber.nextInt(); // user's number
// divides each digit into its own element within an array
List<Integer> checkUserNum = new ArrayList<Integer>();
while(userNum > 0) {
checkUserNum.add(userNum % 10);
userNum /= 10;
}
Collections.reverse(checkUserNum); // reverses the order of the array
System.out.print(checkUserNum);
**
use "composer remove vendor/package"
** This is Example: Install / Add Pakage
composer require firebear/importexportfree
Uninsall / Remove
composer remove firebear/importexportfree
Finaly after removing:
php -f bin/magento setup:upgrade
php bin/magento setup:static-content:deploy –f
php bin/magento indexer:reindex
php -f bin/magento cache:clean
No, Depends on the situation, sometimes it is legitimate and good design.
To understand why and when you need to call destructors explicitly, let's look at what happening with "new" and "delete".
To created an object dynamically, T* t = new T;
under the hood: 1. sizeof(T) memory is allocated. 2. T's constructor is called to initialize the allocated memory. The operator new does two things: allocation and initialization.
To destroy the object delete t;
under the hood: 1. T's destructor is called. 2. memory allocated for that object is released. the operator delete also does two things: destruction and deallocation.
One writes the constructor to do initialization, and destructor to do destruction. When you explicitly call the destructor, only the destruction is done, but not the deallocation.
A legitimate use of explicitly calling destructor, therefore, could be, "I only want to destruct the object, but I don't (or can't) release the memory allocation (yet)."
A common example of this, is pre-allocating memory for a pool of certain objects which otherwise have to be allocated dynamically.
When creating a new object, you get the chunk of memory from the pre-allocated pool and do a "placement new". After done with the object, you may want to explicitly call the destructor to finish the cleanup work, if any. But you won't actually deallocate the memory, as the operator delete would have done. Instead, you return the chunk to the pool for reuse.
Here's a dplyr
option:
library(dplyr)
# across all columns:
df %>% filter_all(any_vars(. %in% c('M017', 'M018')))
# or in only select columns:
df %>% filter_at(vars(col1, col2), any_vars(. %in% c('M017', 'M018')))
I can't get it to work on $.get()
because it has no complete
event.
I suggest to use $.ajax()
like this,
$.ajax({
url: 'http://www.example.org',
data: {'a':1,'b':2,'c':3},
dataType: 'xml',
complete : function(){
alert(this.url)
},
success: function(xml){
}
});
You must use std namespace. If this code in main.cpp you should write
using namespace std;
If this declaration is in header, then you shouldn't include namespace and just write
std::string level;
Swift Method, and supply a demo.
func topMostController() -> UIViewController {
var topController: UIViewController = UIApplication.sharedApplication().keyWindow!.rootViewController!
while (topController.presentedViewController != nil) {
topController = topController.presentedViewController!
}
return topController
}
func demo() {
let vc = ViewController()
let nav = UINavigationController.init(rootViewController: vc)
topMostController().present(nav, animated: true, completion: nil)
}
public void onClick(View v) {
Context context = v.getContext();
CharSequence text = "Message";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
For MySQL Workbench 6.1: in the home window click on the server instance(connection)/ or create a new one. In the thus opened 'connection' tab click on 'server' -> 'data import'. The rest of the steps remain as in Vishy's answer.
You can do this:
def deleteContent(pfile):
fn=pfile.name
pfile.close()
return open(fn,'w')
If for some reason you don't like interactive editors, you can use git rebase --onto
.
Say you want to modify Commit1
. First, branch from before Commit1
:
git checkout -b amending [commit before Commit1]
Second, grab Commit1
with cherry-pick
:
git cherry-pick Commit1
Now, amend your changes, creating Commit1'
:
git add ...
git commit --amend -m "new message for Commit1"
And finally, after having stashed any other changes, transplant the rest of your commits up to master
on top of your
new commit:
git rebase --onto amending Commit1 master
Read: "rebase, onto the branch amending
, all commits between Commit1
(non-inclusive) and master
(inclusive)". That is, Commit2 and Commit3, cutting the old Commit1 out entirely. You could just cherry-pick them, but this way is easier.
Remember to clean up your branches!
git branch -d amending
I finally got it working. This way only a few apps are shown by the chooser (Google Drive, Dropbox, Root Explorer, and Solid Explorer). It's working fine with the two explorers but not with Google Drive and Dropbox (I guess because they cannot access the external storage). The other MIME type like "*/*"
is also possible.
public void openFolder(){
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath()
+ File.separator + "myFolder" + File.separator);
intent.setDataAndType(uri, "text/csv");
startActivity(Intent.createChooser(intent, "Open folder"));
}
Hold CTRL and press F6 until you reached the editor you want, then release. The UI is not as pretty as the window selection, but the functionality is the same.
onMeasure()
is your opportunity to tell Android how big you want your custom view to be dependent the layout constraints provided by the parent; it is also your custom view's opportunity to learn what those layout constraints are (in case you want to behave differently in a match_parent
situation than a wrap_content
situation). These constraints are packaged up into the MeasureSpec
values that are passed into the method. Here is a rough correlation of the mode values:
layout_width
or layout_height
value was set to a specific value. You should probably make your view this size. This can also get triggered when match_parent
is used, to set the size exactly to the parent view (this is layout dependent in the framework).layout_width
or layout_height
value was set to match_parent
or wrap_content
where a maximum size is needed (this is layout dependent in the framework), and the size of the parent dimension is the value. You should not be any larger than this size.layout_width
or layout_height
value was set to wrap_content
with no restrictions. You can be whatever size you would like. Some layouts also use this callback to figure out your desired size before determine what specs to actually pass you again in a second measure request.The contract that exists with onMeasure()
is that setMeasuredDimension()
MUST be called at the end with the size you would like the view to be. This method is called by all the framework implementations, including the default implementation found in View
, which is why it is safe to call super
instead if that fits your use case.
Granted, because the framework does apply a default implementation, it may not be necessary for you to override this method, but you may see clipping in cases where the view space is smaller than your content if you do not, and if you lay out your custom view with wrap_content
in both directions, your view may not show up at all because the framework doesn't know how large it is!
Generally, if you are overriding View
and not another existing widget, it is probably a good idea to provide an implementation, even if it is as simple as something like this:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int desiredWidth = 100;
int desiredHeight = 100;
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width;
int height;
//Measure Width
if (widthMode == MeasureSpec.EXACTLY) {
//Must be this size
width = widthSize;
} else if (widthMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
width = Math.min(desiredWidth, widthSize);
} else {
//Be whatever you want
width = desiredWidth;
}
//Measure Height
if (heightMode == MeasureSpec.EXACTLY) {
//Must be this size
height = heightSize;
} else if (heightMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
height = Math.min(desiredHeight, heightSize);
} else {
//Be whatever you want
height = desiredHeight;
}
//MUST CALL THIS
setMeasuredDimension(width, height);
}
Hope that Helps.
If you're using ASP.NET MVC you might also need to remove the HandleErrorAttribute from the Global.asax.cs file:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
The return statements should place in one line. Or the other option is to remove the curly brackets that bound the HTML statement.
example:
return posts.map((post, index) =>
<div key={index}>
<h3>{post.title}</h3>
<p>{post.body}</p>
</div>
);
You can't transition between two background images, as there's no way for the browser to know what you want to interpolate. As you've discovered, you can transition the background position. If you want the image to fade in on mouse over, I think the best way to do it with CSS transitions is to put the image on a containing element and then animate the background colour to transparent on the link itself:
span {
background: url(button.png) no-repeat 0 0;
}
a {
width: 32px;
height: 32px;
text-align: left;
background: rgb(255,255,255);
-webkit-transition: background 300ms ease-in 200ms; /* property duration timing-function delay */
-moz-transition: background 300ms ease-in 200ms;
-o-transition: background 300ms ease-in 200ms;
transition: background 300ms ease-in 200ms;
}
a:hover {
background: rgba(255,255,255,0);
}
I had the same problem, This is what I did: I have a SPA with multiple views in the same page (without ajax), so this is the code of the module:
var app = angular.module('otisApp', ['chieffancypants.loadingBar', 'ngRoute']);
app.config(['$routeProvider', function($routeProvider){
$routeProvider.when('/:page', {
templateUrl: function(page){return page.page + '.html';},
controller:'otisCtrl'
})
.otherwise({redirectTo:'/otis'});
}]);
I have only one controller for all views, but, the problem is the same as the question, the controller always refresh data, in order to avoid this behavior I did what people suggest above and I created a service for that purpose, then pass it to the controller as follows:
app.factory('otisService', function($http){
var service = {
answers:[],
...
}
return service;
});
app.controller('otisCtrl', ['$scope', '$window', 'otisService', '$routeParams',
function($scope, $window, otisService, $routeParams){
$scope.message = "Hello from page: " + $routeParams.page;
$scope.update = function(answer){
otisService.answers.push(answers);
};
...
}]);
Now I can call the update function from any of my views, pass values and update my model, I haven't no needed to use html5 apis for persistence data (this is in my case, maybe in other cases would be necessary to use html5 apis like localstorage and other stuff).
I fixed mine I added to my project > app > libs android volley.jar and my problem was solved
Bash 4+ tested - This is the correct way to search for size 0:
find /path/to/dir -size 0 -type f -name "*.xml"
Search for multiple file extensions of size 0:
find /path/to/dir -size 0 -type f \( -iname \*.css -o -iname \*.js \)
Note: If you removed the \( ... \) the results would be all of the files that meet this requirement hence ignoring the size 0.
You should use the csv
module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.
import csv
with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
csvout = csv.writer(csvout)
for row in tsvin:
count = int(row[4])
if count > 0:
csvout.writerows([row[2:4] for _ in range(count)])
or, using the itertools
module to do the repeating with itertools.repeat()
:
from itertools import repeat
import csv
with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
csvout = csv.writer(csvout)
for row in tsvin:
count = int(row[4])
if count > 0:
csvout.writerows(repeat(row[2:4], count))
The backwards compatible version (IE9+) is
var parent = document.querySelector(selector);
Array.prototype.forEach.call(parent.children, function(child, index){
// Do stuff
});
The es6 way is
const parent = document.querySelector(selector);
Array.from(parent.children).forEach((child, index) => {
// Do stuff
});
If you want one row for each filename, reflecting a specific states and listing the most recent date then this is your friend:
select filename ,
status ,
max_date = max( dates )
from some_table t
group by filename , status
having status = '<your-desired-status-here>'
Easy!
For the replacement string and the replacement pattern as specified by $
.
here a resume:
link to doc : here
"hello _there_".replace(/_(.*?)_/g, "<div>$1</div>")
Note:
If you want to have a $
in the replacement string use $$
. Same as with vscode snippet system.
Adding to @sefarkas' suggestion and using quantile as cut-offs, one could explore the following option:
newdata <- subset(mydata,!(mydata$var > quantile(mydata$var, probs=c(.01, .99))[2] | mydata$var < quantile(mydata$var, probs=c(.01, .99))[1]) )
This will remove the points points beyond the 99th quantile. Care should be taken like what aL3Xa was saying about keeping outliers. It should be removed only for getting an alternative conservative view of the data.
if you can use HTML5 you can do <input type="number" />
If not you will have to either do it through javascript as you said it doesnt get submited to do it from codebehind.
<input id="numbersOnly" onkeypress='validate()' />
function validate(){
var returnString;
var text = document.getElementByID('numbersOnly').value;
var regex = /[0-9]|\./;
var anArray = text.split('');
for(var i=0; i<anArray.length; i++){
if(!regex.test(anArray[i]))
{
anArray[i] = '';
}
}
for(var i=0; i<anArray.length; i++) {
returnString += anArray[i];
}
document.getElementByID('numbersOnly').value = returnString;
}
P.S didnt test the code but it should be more or less correct if not check for typos :D You might wanna add a few more things like what to do if the string is null or empty etc. Also you could make this quicker :D
Try to change link from
/apple-touch-icon-precomposed.png
to:
<%=asset_path "apple-touch-icon-precomposed.png" %>
The solution given above worked for us as well for a long time:
mvn versions:set -DnewVersion=2.50.1-SNAPSHOT
However it stopped working yesterday, and we found it due to a recent bug in a the versions-maven-plugin
Our (temporary) workaround was to change the parent/pom.xml file as follows:
--- jackrabbit/oak/trunk/oak-parent/pom.xml 2020/08/13 13:43:11 1880829
+++ jackrabbit/oak/trunk/oak-parent/pom.xml 2020/08/13 15:17:59 1880830
@@ -329,6 +329,13 @@
<artifactId>spotbugs-maven-plugin</artifactId>
<version>3.1.11</version>
</plugin>
+
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>versions-maven-plugin</artifactId>
+ <version>2.7</version>
+ </plugin>
+
add_Pbl <= to_stdlogicvector(to_bitvector(dato_cu(25 downto 2)) sll 1);
add_Pbl is a std_logic_vector of 24 bit
dato_cu is a std_logic_vector of 32 bit
First, you need to convert the std_logic_vector
with to_bitvector()
function
because sll statement works with logic 1 and 0 bits.
You might try this way:
fprintf('%s: (%i,%i,%i)\r\n','Answer',1,2,3)
I hope this helps.
The line (or lines) between the lines beginning <<<<<<<
and ======
here:
<<<<<<< HEAD:file.txt
Hello world
=======
... is what you already had locally - you can tell because HEAD
points to your current branch or commit. The line (or lines) between the lines beginning =======
and >>>>>>>
:
=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt
... is what was introduced by the other (pulled) commit, in this case 77976da35a11
. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD
. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.
Try this :
$obj = @{
SomeProp = "Hello"
}
Write-Host "Property Value is $($obj."SomeProp")"
Warning! Your SQL isn't a good idea, because it will select all rows (no WHERE clause assumes "WHERE 1"!) and clog your application if you have a large number of rows. (What's the point of selecting 1,000 rows when 1 will do?) So instead, when selecting only one row, make sure you specify the LIMIT clause:
$sql = "SELECT id FROM games LIMIT 1"; // Select ONLY one, instead of all
$result = $db->query($sql);
$row = $result->fetch_assoc();
echo 'Game ID: '.$row['id'];
This difference requires MySQL to select only the first matching record, so ordering the table is important or you ought to use a WHERE clause. However, it's a whole lot less memory and time to find that one record, than to get every record and output row number one.
Check the collation type of each table, and make sure that they have the same collation.
After that check also the collation type of each table field that you have use in operation.
I had encountered the same error, and that tricks works on me.
Short answer: You can't.
Long answer:
Due to the way generics is implemented in Java, the generic type T is not kept at runtime. Still, you can use a private data member:
public class Foo<T>
{
private Class<T> type;
public Foo(Class<T> type) { this.type = type; }
}
Usage example:
Foo<Integer> test = new Foo<Integer>(Integer.class);
There's another way if you don't want to have older Java versions installed you can do the following:
1) Download the iReport-5.6.0.zip from https://sourceforge.net/projects/ireport/files/iReport/iReport-5.6.0/
2) Download jre-7u67-windows-x64.tar.gz (the one packed in a tar) from https://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html
3) Extract the iReport and in the extracted folder that contains the bin and etc folders throw in the jre. For example if you unpack twice the jre-7u67-windows-x64.tar.gz you end up with a folder named jre1.7.0_67. Put that folder in the iReport-5.6.0 directory:
and then go into the etc folder and edit the file ireport.conf and add the following line into it:
For Windows jdkhome=".\jre1.7.0_67"
For Linux jdkhome="./jre1.7.0_67"
Note : jre version may change! according to your download of 1.7
now if you run the ireport_w.exe from the bin folder in the iReport directory it should load just fine.
Using regular for loop is the simplest way of printing array in my opinion. Here you have a sample code based on your intArray
for (int i = 0; i < intArray.length; i++) {
System.out.print(intArray[i] + ", ");
}
It gives output as yours 1, 2, 3, 4, 5
There are two ways to exit a method early (without quitting the program):
return
keyword.Exceptions should only be used for exceptional circumstances - when the method cannot continue and it cannot return a reasonable value that would make sense to the caller. Usually though you should just return when you are done.
If your method returns void then you can write return without a value:
return;
Specifically about your code:
You should also use curly braces when you write an if statement so that it is clear which statements are inside the body of the if statement:
if (textBox1.Text == String.Empty)
{
textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
}
return; // Are you sure you want the return to be here??
If you are using .NET 4 there is a useful method that depending on your requirements you might want to consider using here: String.IsNullOrWhitespace.
Environment.Newline
instead of "\r\n"
.myArray.filter(function(a){ return a.id == some_id_you_want })[0]
You simply cannot get PowerShell to omit those pesky newlines... There is no script or cmdlet that does. Of course, Write-Host is absolute nonsense, because you can't redirect/pipe from it!
Nevertheless, you can write your own EXE file to do it which is what I explained how to do in Stack Overflow question How to output something in PowerShell.
Seems that tensorflow only work on python 3.5 at the moment, try to run this command before running the pip install
conda create --name tensorflow python=3.5
After this running the following lines :
For cpu :
pip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-1.1.0-cp35-cp35m-win_amd64.whl
For gpu :
pip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-1.1.0-cp35-cp35m-win_amd64.whl
Should work like a charm,
Cheers
Open your Android SDK Manager and ensure that you download/install a system image for the API level you are developing with.
Or, if you need to do something with each folder, have a look at the System.IO.DirectoryInfo class. It also has a Parent property that allows you to navigate to the parent directory.
function configureDropDownLists(ddl1, ddl2) {_x000D_
var colours = ['Black', 'White', 'Blue'];_x000D_
var shapes = ['Square', 'Circle', 'Triangle'];_x000D_
var names = ['John', 'David', 'Sarah'];_x000D_
_x000D_
switch (ddl1.value) {_x000D_
case 'Colours':_x000D_
ddl2.options.length = 0;_x000D_
for (i = 0; i < colours.length; i++) {_x000D_
createOption(ddl2, colours[i], colours[i]);_x000D_
}_x000D_
break;_x000D_
case 'Shapes':_x000D_
ddl2.options.length = 0;_x000D_
for (i = 0; i < shapes.length; i++) {_x000D_
createOption(ddl2, shapes[i], shapes[i]);_x000D_
}_x000D_
break;_x000D_
case 'Names':_x000D_
ddl2.options.length = 0;_x000D_
for (i = 0; i < names.length; i++) {_x000D_
createOption(ddl2, names[i], names[i]);_x000D_
}_x000D_
break;_x000D_
default:_x000D_
ddl2.options.length = 0;_x000D_
break;_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
function createOption(ddl, text, value) {_x000D_
var opt = document.createElement('option');_x000D_
opt.value = value;_x000D_
opt.text = text;_x000D_
ddl.options.add(opt);_x000D_
}
_x000D_
<select id="ddl" onchange="configureDropDownLists(this,document.getElementById('ddl2'))">_x000D_
<option value=""></option>_x000D_
<option value="Colours">Colours</option>_x000D_
<option value="Shapes">Shapes</option>_x000D_
<option value="Names">Names</option>_x000D_
</select>_x000D_
_x000D_
<select id="ddl2">_x000D_
</select>
_x000D_
This is what I've used (Swift 5)...
extension Array where Element:Equatable
{
@discardableResult
mutating func removeFirst(_ item:Any ) -> Any? {
for index in 0..<self.count {
if(item as? Element == self[index]) {
return self.remove(at: index)
}
}
return nil
}
@discardableResult
mutating func removeLast(_ item:Any ) -> Any? {
var index = self.count-1
while index >= 0 {
if(item as? Element == self[index]) {
return self.remove(at: index)
}
index -= 1
}
return nil
}
}
var arrContacts:[String] = ["A","B","D","C","B","D"]
var contacts: [Any] = ["B","D"]
print(arrContacts)
var index = 1
arrContacts.removeFirst(contacts[index])
print(arrContacts)
index = 0
arrContacts.removeLast(contacts[index])
print(arrContacts)
Results:
["A", "B", "D", "C", "B", "D"]
["A", "B", "C", "B", "D"]
["A", "B", "C", "D"]
Important: The array from which you remove items must contain Equatable elements (such as objects, strings, number, etc.)
If you like namespace constant, you can leverage struct, Friday Q&A 2011-08-19: Namespaced Constants and Functions
// in the header
extern const struct MANotifyingArrayNotificationsStruct
{
NSString *didAddObject;
NSString *didChangeObject;
NSString *didRemoveObject;
} MANotifyingArrayNotifications;
// in the implementation
const struct MANotifyingArrayNotificationsStruct MANotifyingArrayNotifications = {
.didAddObject = @"didAddObject",
.didChangeObject = @"didChangeObject",
.didRemoveObject = @"didRemoveObject"
};
Personally I prefer this method. This will overwrite the file on the destination, removes the source file and also prevent removing the source file when the copy fails.
string source = @"c:\test\SomeFile.txt";
string destination = @"c:\test\test\SomeFile.txt";
try
{
File.Copy(source, destination, true);
File.Delete(source);
}
catch
{
//some error handling
}
I would use a hashtable with in key takes the element of the array (here string) and in value an Integer.
then go through the list doing something like this :
for(String s:array){
if(hash.containsKey(s)){
Integer i = hash.get(s);
i++;
}else{
hash.put(s, new Interger(1));
}
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
You can use signals to control nginx.
According to documentation, you need to send HUP signal to nginx master process.
HUP - changing configuration, keeping up with a changed time zone (only for FreeBSD and Linux), starting new worker processes with a new configuration, graceful shutdown of old worker processes
Check the documentation here: http://nginx.org/en/docs/control.html
You can send the HUP signal to nginx master process PID like this:
kill -HUP $( cat /var/run/nginx.pid )
The command above reads the nginx PID from /var/run/nginx.pid
. By default nginx pid is written to /usr/local/nginx/logs/nginx.pid
but that can be overridden in config. Check your nginx.config
to see where it saves the PID.
Here's the Javadoc in Oracle's website for the Date class: https://docs.oracle.com/javase/8/docs/api/java/util/Date.html
If you scroll down to "Constructor Summary," you'll see the different options for how a Date object can be instantiated. Like all objects in Java, you create a new one with the following:
Date firstDate = new Date(ConstructorArgsHere);
Now you have a bit of a choice. If you don't pass in any arguments, and just do this,
Date firstDate = new Date();
it will represent the exact date and time at which you called it. Here are some other constructors you may want to make use of:
Date firstDate1 = new Date(int year, int month, int date);
Date firstDate2 = new Date(int year, int month, int date, int hrs, int min);
Date firstDate3 = new Date(int year, int month, int date, int hrs, int min, int sec);
Use:
<?php
$url = "targetpage"
function redirect$url(){
if (headers_sent()) == false{
echo '<script>window.location.href="' . $url . '";</script>';
}
}
?>
EL expression:
${requestScope.Error_Message}
There are several implicit objects in JSP EL. See Expression Language under the "Implicit Objects" heading.
Well, in my case, the px
after the width value was missing ... Interestingly, the W3C validator did not even notice this error, just silently ignored the definition.
Generally, placement new is used to get rid of allocation cost of a 'normal new'.
Another scenario where I used it is a place where I wanted to have access to the pointer to an object that was still to be constructed, to implement a per-document singleton.
You could use String.rstrip
.
result = string.rstrip('/')
for FULLSCREEN width table:
table width MUST be 100%
if need N colunms, then THs MUST be N+1
example for 3 columns:
table.fixed {_x000D_
table-layout: fixed;_x000D_
width: 100%;_x000D_
}_x000D_
table.fixed td {_x000D_
overflow: hidden;_x000D_
}
_x000D_
<table class="fixed">_x000D_
<col width=20 />_x000D_
<col width=20 />_x000D_
<col width=20 />_x000D_
<tr>_x000D_
<th>1</th>_x000D_
<th>2</th>_x000D_
<th>3</th>_x000D_
<th>FREE</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>text111111111</td>_x000D_
<td>text222222222</td>_x000D_
<td>text3333333</td>_x000D_
</tr>_x000D_
</table>
_x000D_
You can pass boolean
by coercing it, put !!
before the variable.
let isRequired = '' || null || undefined
<input :required="!!isRequired"> // it will coerce value to respective boolean
But I would like to pull your attention for the following case where the receiving component has defined type
for props. In that case, if isRequired
has defined type to be string
then passing boolean
make it type check fails and you will get Vue warning. To fix that you may want to avoid passing that prop, so just put undefined
fallback and the prop will not sent to component
let isValue = false
<any-component
:my-prop="isValue ? 'Hey I am when the value exist' : undefined"
/>
Explanation
I have been through the same problem, and tried above solutions !!
Yes, I don't see the prop
but that actually does not fulfils what required here.
My problem -
let isValid = false
<any-component
:my-prop="isValue ? 'Hey I am when the value exist': false"
/>
In the above case, what I expected is not having my-prop
get passed to the child component - <any-conponent/>
I don't see the prop
in DOM
but In my <any-component/>
component, an error pops out of prop type check failure. As in the child component, I am expecting my-prop
to be a String
but it is boolean
.
myProp : {
type: String,
required: false,
default: ''
}
Which means that child component did receive the prop even if it is false
. Tweak here is to let the child component to take the default-value
and also skip the check. Passed undefined
works though!
<any-component
:my-prop="isValue ? 'Hey I am when the value exist' : undefined"
/>
This works and my child prop is having the default value.
socket.disconnect()
Only reboots the connection firing disconnect event on client side. But gets connected again.
socket.close()
Disconnect the connection from client. The client will keep trying to connect.
You can try the Anthem library.
the easiest and safest way is to use something like this:
var waitForJQuery = setInterval(function () {
if (typeof $ != 'undefined') {
// place your code here.
clearInterval(waitForJQuery);
}
}, 10);
Combine round and ceiling to get a proper round up.
select ceiling(round(984.375000), 0)) => 984
while
select round(984.375000, 0) => 984.000000
and
select ceil (984.375000) => 985
Active 1st tab
$("#workflowTab").tabs({ active: 0 });
Active last tab
$("#workflowTab").tabs({ active: -1 });
Active 2nd tab
$("#workflowTab").tabs({ active: 1 });
Its work like an array
You can drop the new string[]
part:
List<string> values = new List<string> { "one", "two", "three" };
Open command prompt as admin and write :
bcdedit /set hypervisorlaunchtype off
I love jQuery's method chaining. Simply do...
var value = $("#text").val().replace('.',':');
//Or if you want to return the value:
return $("#text").val().replace('.',':');
Here is a shorter, but complete code.
If you need a dialog with only one button:
await showDialog(
context: context,
builder: (context) => new AlertDialog(
title: new Text('Message'),
content: Text(
'Your file is saved.'),
actions: <Widget>[
new FlatButton(
onPressed: () {
Navigator.of(context, rootNavigator: true)
.pop(); // dismisses only the dialog and returns nothing
},
child: new Text('OK'),
),
],
),
);
If you need a dialog with Yes/No buttons:
onPressed: () async {
bool result = await showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Confirmation'),
content: Text('Do you want to save?'),
actions: <Widget>[
new FlatButton(
onPressed: () {
Navigator.of(context, rootNavigator: true)
.pop(false); // dismisses only the dialog and returns false
},
child: Text('No'),
),
FlatButton(
onPressed: () {
Navigator.of(context, rootNavigator: true)
.pop(true); // dismisses only the dialog and returns true
},
child: Text('Yes'),
),
],
);
},
);
if (result) {
if (missingvalue) {
Scaffold.of(context).showSnackBar(new SnackBar(
content: new Text('Missing Value'),
));
} else {
saveObject();
Navigator.of(context).pop(_myObject); // dismisses the entire widget
}
} else {
Navigator.of(context).pop(_myObject); // dismisses the entire widget
}
}
Some time you need to access with schema
name,as an example you are using AdventureWorks Database you need to access with schemas.
SELECT s.name +'.'+v.name FROM sys.views v inner join sys.schemas s on s.schema_id = v.schema_id
This is how PHP expresses a closure. This is not evil at all and in fact it is quite powerful and useful.
Basically what this means is that you are allowing the anonymous function to "capture" local variables (in this case, $tax
and a reference to $total
) outside of it scope and preserve their values (or in the case of $total
the reference to $total
itself) as state within the anonymous function itself.
Properties props = new Properties();
URL resource = getClass().getClassLoader().getResource("data.properties");
props.load(new InputStreamReader(resource.openStream(), "UTF8"));
this works well in java 1.6. How can i do this in 1.5, Since Properties class does not have a method to pars InputStreamReader
.
Just use not
:
if not your_variable:
print("your_variable is empty")
and for your 0 as string
use:
if your_variable == "0":
print("your_variable is 0 (string)")
combine them:
if not your_variable or your_variable == "0":
print("your_variable is empty")
Python is about simplicity, so is this answer :)
In addition to Marty's excellent Answer, the SystemVerilog specification offers the byte
data type. The following declares a 4x8-bit variable (4 bytes), assigns each byte a value, then displays all values:
module tb;
byte b [4];
initial begin
foreach (b[i]) b[i] = 1 << i;
foreach (b[i]) $display("Address = %0d, Data = %b", i, b[i]);
$finish;
end
endmodule
This prints out:
Address = 0, Data = 00000001
Address = 1, Data = 00000010
Address = 2, Data = 00000100
Address = 3, Data = 00001000
This is similar in concept to Marty's reg [7:0] a [0:3];
. However, byte
is a 2-state data type (0 and 1), but reg
is 4-state (01xz). Using byte
also requires your tool chain (simulator, synthesizer, etc.) to support this SystemVerilog syntax. Note also the more compact foreach (b[i])
loop syntax.
The SystemVerilog specification supports a wide variety of multi-dimensional array types. The LRM can explain them better than I can; refer to IEEE Std 1800-2005, chapter 5.
x = cumsum(c(0, runif(100, -1, +1)))
y = cumsum(c(0, runif(100, -1, +1)))
fit = lm(y ~ x)
> names(summary(fit))
[1] "call" "terms"
[3] "residuals" "coefficients"
[5] "aliased" "sigma"
[7] "df" "r.squared"
[9] "adj.r.squared" "fstatistic"
[11] "cov.unscaled"
summary(fit)$r.squared
According to Apple documentation
Example :
var myObject = NSDate()
let futureDate = myObject.dateByAddingTimeInterval(10)
let timeSinceNow = myObject.timeIntervalSinceNow
I don't know if this is what you are looking for, but you can achieve this by passing a callback to the child class.
first define a generic callback:
public interface ITypedCallback<T> {
void execute(T type);
}
create a new ITypedCallback instance on ServerConnections instantiation:
public Server(int _address) {
serverConnectionHandler = new ServerConnections(new ITypedCallback<Socket>() {
@Override
public void execute(Socket socket) {
// do something with your socket here
}
});
}
call the execute methode on the callback object.
public class ServerConnections implements Runnable {
private ITypedCallback<Socket> callback;
public ServerConnections(ITypedCallback<Socket> _callback) {
callback = _callback;
}
@Override
public void run() {
try {
mainSocket = new ServerSocket(serverPort);
while (true) {
callback.execute(mainSocket.accept());
}
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
btw: I didn't check if it's 100% correct, directly coded it here.
Create a relative div that is placed in the flow of the page; place the base image first as relative so that the div knows how big it should be; place the overlays as absolutes relative to the upper left of the first image. The trick is to get the relatives and absolutes correct.
If you have a numpy array you can do this:
import numpy as np
from matplotlib import pyplot as plt
data = np.array([
[1, 2],
[2, 3],
[3, 6],
])
x, y = data.T
plt.scatter(x,y)
plt.show()
var appBanners = document.getElementsByClassName('appBanner');
for (var i = 0; i < appBanners.length; i ++) {
appBanners[i].style.display = 'none';
}
<meta http-equiv="Refresh" content="n;url">
That's It. Easy, Right?
<meta http-equiv="Refresh" content="n;url">
_x000D_
MySQL will assume the part before the equals references the columns named in the INSERT INTO clause, and the second part references the SELECT columns.
INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct,
inact, inadur, inadist,
smlct, smldur, smldist,
larct, lardur, lardist,
emptyct, emptydur)
SELECT id, uid, t.location, t.animal, t.starttime, t.endtime, t.entct,
t.inact, t.inadur, t.inadist,
t.smlct, t.smldur, t.smldist,
t.larct, t.lardur, t.lardist,
t.emptyct, t.emptydur
FROM tmp t WHERE uid=x
ON DUPLICATE KEY UPDATE entct=t.entct, inact=t.inact, ...
I faced same problem with background image and its child components including logo images. After wasting few hours, I found the correct way to solve this problem. This is surely helped to you.
var {View, Text, Image, ImageBackground} = require('react-native');
import Images from '@assets';
export default class Welcome extends Component {
render() {
return (
<ImageBackground source={Images.main_bg} style={styles.container}>
<View style={styles.markWrap}>
<Image source={Images.main_logo}
style={styles.mark} resizeMode="contain" />
</View>
<View style={[styles.wrapper]}>
{//Here put your other components}
</View>
</ImageBackground>
);
}
}
var styles = StyleSheet.create({
container:{
flex: 1,
},
markWrap: {
flex: 1,
marginTop: 83,
borderWidth:1, borderColor: "green"
},
mark: {
width: null,
height: null,
flex: 1,
},
wrapper:{
borderWidth:1, borderColor: "green",///for debug
flex: 1,
position:"relative",
},
}
(PS: I put on the dummy image on this screen instead of real company logo.)
In theory, yes, as long as you don't exceed the maximum url and/oor query string length for the client or server.
In practice, things can get a bit trickier. For example, it can trigger an HttpRequestValidationException on ASP.NET if the value happens to contain an "on" and you leave in the trailing "==".
The method select
accepts a list of column names (string) or expressions (Column) as a parameter. To select columns you can use:
-- column names (strings):
df.select('col_1','col_2','col_3')
-- column objects:
import pyspark.sql.functions as F
df.select(F.col('col_1'), F.col('col_2'), F.col('col_3'))
# or
df.select(df.col_1, df.col_2, df.col_3)
# or
df.select(df['col_1'], df['col_2'], df['col_3'])
-- a list of column names or column objects:
df.select(*['col_1','col_2','col_3'])
#or
df.select(*[F.col('col_1'), F.col('col_2'), F.col('col_3')])
#or
df.select(*[df.col_1, df.col_2, df.col_3])
The star operator *
can be omitted as it's used to keep it consistent with other functions like drop
that don't accept a list as a parameter.
you are describing a Problem, which I would try to solve with the VLOOKUP function rather than using VBA.
You should always consider a non-vba solution first.
Here are some application examples of VLOOKUP (or SVERWEIS in German, as i know it):
http://www.youtube.com/watch?v=RCLUM0UMLXo
http://office.microsoft.com/en-us/excel-help/vlookup-HP005209335.aspx
If you have to make it as a macro, you could use VLOOKUP as an application function - a quick solution with slow performance - or you will have to make a simillar function yourself.
If it has to be the latter, then there is need for more details on your specification, regarding performance questions.
You could copy any range to an array, loop through this array and check for your value, then copy this value to any other range. This is how i would solve this as a vba-function.
This would look something like that:
Public Sub CopyFilter()
Dim wks As Worksheet
Dim avarTemp() As Variant
'go through each worksheet
For Each wks In ThisWorkbook.Worksheets
avarTemp = wks.UsedRange
For i = LBound(avarTemp, 1) To UBound(avarTemp, 1)
'check in the first column in each row
If avarTemp(i, LBound(avarTemp, 2)) = "XYZ" Then
'copy cell
targetWks.Cells(1, 1) = avarTemp(i, LBound(avarTemp, 2))
End If
Next i
Next wks
End Sub
Ok, now i have something nice which could come in handy for myself:
Public Function FILTER(ByRef rng As Range, ByRef lngIndex As Long) As Variant
Dim avarTemp() As Variant
Dim avarResult() As Variant
Dim i As Long
avarTemp = rng
ReDim avarResult(0)
For i = LBound(avarTemp, 1) To UBound(avarTemp, 1)
If avarTemp(i, 1) = "active" Then
avarResult(UBound(avarResult)) = avarTemp(i, lngIndex)
'expand our result array
ReDim Preserve avarResult(UBound(avarResult) + 1)
End If
Next i
FILTER = avarResult
End Function
You can use it in your Worksheet like this =FILTER(Tabelle1!A:C;2) or with =INDEX(FILTER(Tabelle1!A:C;2);3) to specify the result row. I am sure someone could extend this to include the index functionality into FILTER or knows how to return a range like object - maybe I could too, but not today ;)
For Swift 4+ versions, please use the below code:
UIDevice.current.name
.as_matrix()
. One short line:df.iloc[:,[1,2,3]].as_matrix()
array([[3, 2, 0.816497],
[0, 'NaN', 'NaN'],
[2, 51, 50.0]], dtype=object)
Here are the steps for your example:
import pandas as pd
columns = ['viz', 'a1_count', 'a1_mean', 'a1_std']
index = [0,1,2]
vals = {'viz': ['n','n','n'], 'a1_count': [3,0,2], 'a1_mean': [2,'NaN', 51], 'a1_std': [0.816497, 'NaN', 50.000000]}
df = pd.DataFrame(vals, columns=columns, index=index)
Gives:
viz a1_count a1_mean a1_std
0 n 3 2 0.816497
1 n 0 NaN NaN
2 n 2 51 50
Then:
x1 = df.iloc[:,[1,2,3]].as_matrix()
Gives:
array([[3, 2, 0.816497],
[0, 'NaN', 'NaN'],
[2, 51, 50.0]], dtype=object)
Where x1 is numpy.ndarray
.
here is the complete example of how you can select and upload multiple files in asp.net using file upload control....
write this code in .aspx file..
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server" enctype="multipart/form-data">
<div>
<input type="file" id="myfile" multiple="multiple" name="myfile" runat="server" size="100" />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<br />
<asp:Label ID="Span1" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
after that write this code in .aspx.cs file..
protected void Button1_Click(object sender,EventArgs e) {
string filepath = Server.MapPath("\\Upload");
HttpFileCollection uploadedFiles = Request.Files;
Span1.Text = string.Empty;
for(int i = 0;i < uploadedFiles.Count;i++) {
HttpPostedFile userPostedFile = uploadedFiles[i];
try {
if (userPostedFile.ContentLength > 0) {
Span1.Text += "<u>File #" + (i + 1) + "</u><br>";
Span1.Text += "File Content Type: " + userPostedFile.ContentType + "<br>";
Span1.Text += "File Size: " + userPostedFile.ContentLength + "kb<br>";
Span1.Text += "File Name: " + userPostedFile.FileName + "<br>";
userPostedFile.SaveAs(filepath + "\\" + Path.GetFileName(userPostedFile.FileName));
Span1.Text += "Location where saved: " + filepath + "\\" + Path.GetFileName(userPostedFile.FileName) + "<p>";
}
} catch(Exception Ex) {
Span1.Text += "Error: <br>" + Ex.Message;
}
}
}
}
and here you go...your multiple file upload control is ready..have a happy day.
On Fedora, this works:
sudo yum install -y python-pip
sudo yum install -y lapack lapack-devel blas blas-devel
sudo yum install -y blas-static lapack-static
sudo pip install numpy
sudo pip install scipy
If you get any public key
errors while downloading, add --nogpgcheck
as parameter to yum
, for example:
yum --nogpgcheck install blas-devel
On Fedora 23 onwards, use dnf
instead of yum
.
UPDATE totals
SET total = total + 1
WHERE name = 'bill';
If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:
UPDATE totals
SET total = total + 1
WHERE name = 'bill'
AND total = 203;
Use the Array#join
method (the argument to join
is what to insert between the strings - in this case a space):
@arr.join(" ")
input autofocus, with onfocus event:
<INPUT onfocus="this.select()" TYPE="TEXT" NAME="thing" autofocus>
This lets you open a form with the desired element selected. It works by using autofocus to hit the input, which then sends itself an onfocus event, which in turn selects the text.
Using ...
search = (^.*import )(.*)(\(.*\):)
replace = $1$2
...replaces ...
from checks import checklist(_list):
...with...
from checks import checklist
Blocks in regex are delineated by parenthesis (which are not preceded by a "\")
(^.*import ) finds "from checks import " and loads it to $1 (eclipse starts counting at 1)
(.*) find the next "everything" until the next encountered "(" and loads it to $2. $2 stops at the "(" because of the next part (see next line below)
(\(.*\):) says "at the first encountered "(" after starting block $2...stop block $2 and start $3. $3 gets loaded with the "('any text'):" or, in the example, the "(_list):"
Then in the replace, just put the $1$2 to replace all three blocks with just the first two.
Can be done with preg_replace:
function str_replace_first($from, $to, $content)
{
$from = '/'.preg_quote($from, '/').'/';
return preg_replace($from, $to, $content, 1);
}
echo str_replace_first('abc', '123', 'abcdef abcdef abcdef');
// outputs '123def abcdef abcdef'
The magic is in the optional fourth parameter [Limit]. From the documentation:
[Limit] - The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).
Though, see zombat's answer for a more efficient method (roughly, 3-4x faster).
defaultMember
already is an alias - it doesn't need to be the name of the exported function/thing. Just do
import alias from 'my-module';
Alternatively you can do
import {default as alias} from 'my-module';
but that's rather esoteric.
Not sure if anyone is having the same responsive issue, but it was just a simple css solution for me.
same example
... ng-init="isCollapsed = true" ng-click="isCollapsed = !isCollapsed"> ...
... div collapse="isCollapsed"> ...
with
@media screen and (min-width: 768px) {
.collapse{
display: block !important;
}
}
1) you can float the image to the left:
<img style="float:left" src="http://i.imgur.com/hCrQkJi.png">
2)You can use an HTML table to place elements on one line.
Code below
<div class="navigation-bar">
<div id="navigation-container">
<table>
<tr>
<td><img src="http://i.imgur.com/hCrQkJi.png"></td>
<td><ul>
<li><a href="#">Home</a></li>
<li><a href="#">Projects</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Get in Touch</a></li>
</ul>
</td></tr></table>
</div>
You must NOT assume that an arbitrary input text file uses the "correct" platform-specific newline separator. This seems to be the source of your problem; it has little to do with regex.
To illustrate, on the Windows platform, System.getProperty("line.separator")
is "\r\n"
(CR+LF). However, when you run your Java code on this platform, you may very well have to deal with an input file whose line separator is simply "\n"
(LF). Maybe this file was originally created in Unix platform, and then transferred in binary (instead of text) mode to Windows. There could be many scenarios where you may run into these kinds of situations, where you must parse a text file as input which does not use the current platform's newline separator.
(Coincidentally, when a Windows text file is transferred to Unix in binary mode, many editors would display ^M
which confused some people who didn't understand what was going on).
When you are producing a text file as output, you should probably prefer the platform-specific newline separator, but when you are consuming a text file as input, it's probably not safe to make the assumption that it correctly uses the platform specific newline separator.
One way to solve the problem is to use e.g. java.util.Scanner
. It has a nextLine()
method that can return the next line (if one exists), correctly handling any inconsistency between the platform's newline separator and the input text file.
You can also combine 2 Scanner
, one to scan the file line by line, and another to scan the tokens of each line. Here's a simple usage example that breaks each line into a List<String>
. The entire file therefore becomes a List<List<String>>
.
This is probably a better approach than reading the entire file into one huge String
and then split
into lines (which are then split
into parts).
String text
= "row1\tblah\tblah\tblah\n"
+ "row2\t1\t2\t3\t4\r\n"
+ "row3\tA\tB\tC\r"
+ "row4";
System.out.println(text);
// row1 blah blah blah
// row2 1 2 3 4
// row3 A B C
// row4
List<List<String>> input = new ArrayList<List<String>>();
Scanner sc = new Scanner(text);
while (sc.hasNextLine()) {
Scanner lineSc = new Scanner(sc.nextLine()).useDelimiter("\t");
List<String> line = new ArrayList<String>();
while (lineSc.hasNext()) {
line.add(lineSc.next());
}
input.add(line);
}
System.out.println(input);
// [[row1, blah, blah, blah], [row2, 1, 2, 3, 4], [row3, A, B, C], [row4]]
java.util.Scanner
- has many examples of usageIn your test code your are trying to pass App
to the spyOn function, but spyOn will only work with objects, not classes. Generally you need to use one of two approaches here:
1) Where the click handler calls a function passed as a prop, e.g.
class App extends Component {
myClickFunc = () => {
console.log('clickity clickcty');
this.props.someCallback();
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro" onClick={this.myClickFunc}>
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
You can now pass in a spy function as a prop to the component, and assert that it is called:
describe('my sweet test', () => {
it('clicks it', () => {
const spy = jest.fn();
const app = shallow(<App someCallback={spy} />)
const p = app.find('.App-intro')
p.simulate('click')
expect(spy).toHaveBeenCalled()
})
})
2) Where the click handler sets some state on the component, e.g.
class App extends Component {
state = {
aProperty: 'first'
}
myClickFunc = () => {
console.log('clickity clickcty');
this.setState({
aProperty: 'second'
});
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro" onClick={this.myClickFunc}>
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
You can now make assertions about the state of the component, i.e.
describe('my sweet test', () => {
it('clicks it', () => {
const app = shallow(<App />)
const p = app.find('.App-intro')
p.simulate('click')
expect(app.state('aProperty')).toEqual('second');
})
})
A slight modification to one of the previous ip route ...
solutions, which eliminates the need for a grep:
ip route get 8.8.8.8 | sed -n 's|^.*src \(.*\)$|\1|gp'
React Router v3
With React Router v3, you can get query-string from this.props.location.search
(?qs1=naisarg&qs2=parmar). For example, with let params = queryString.parse(this.props.location.search)
, would give { qs1 : 'naisarg', qs2 : 'parmar'}
React Router v4
With React Router v4, the this.props.location.query
does not exist anymore. You need to use this.props.location.search
instead and parse the query parameters either by yourself or using an existing package such as query-string
.
Example
Here is a minimal example using React Router v4 and the query-string
library.
import { withRouter } from 'react-router-dom';
import queryString from 'query-string';
class ActivateAccount extends Component{
someFunction(){
let params = queryString.parse(this.props.location.search)
...
}
...
}
export default withRouter(ActivateAccount);
Rational
The React Router's team rational for removing the query
property is:
There are a number of popular packages that do query string parsing/stringifying slightly differently, and each of these differences might be the "correct" way for some users and "incorrect" for others. If React Router picked the "right" one, it would only be right for some people. Then, it would need to add a way for other users to substitute in their preferred query parsing package. There is no internal use of the search string by React Router that requires it to parse the key-value pairs, so it doesn't have a need to pick which one of these should be "right".
[...]
The approach being taken for 4.0 is to strip out all the "batteries included" kind of features and get back to just basic routing. If you need query string parsing or async loading or Redux integration or something else very specific, then you can add that in with a library specifically for your use case. Less cruft is packed in that you don't need and you can customize things to your specific preferences and needs.
You can find the full discussion on GitHub.
The JDK path might change when you update JAVA. For Mac you should go to the following path to check the JAVA version installed.
/Library/Java/JavaVirtualMachines/
Next, say JDK version that you find is jdk1.8.0_151.jdk
, the path to home directory within it is the JDK home path.
In my case it was :
/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home
You can configure it by going to File -> Project Structure -> SDKs
.
You need to first change the constraint and then animate the update.
This should be in the superview.
self.nameInputConstraint.constant = 8
Swift 2
UIView.animateWithDuration(0.5) {
self.view.layoutIfNeeded()
}
Swift 3, 4, 5
UIView.animate(withDuration: 0.5) {
self.view.layoutIfNeeded()
}
Because you're encapsulating the product again. Try to convert it like so:
let body = JSON.stringify(product);
This will output the Exception, use only to debug you should handle you exceptions better.
import java.io.PrintWriter;
import java.io.StringWriter;
public static String getStackTrace(Throwable t)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw, true);
t.printStackTrace(pw);
pw.flush();
sw.flush();
return sw.toString();
}
Follow these steps to run your application on the device connected.
1. Change directories to the root of your Android project and execute:
ant debug
2. Make sure the Android SDK platform-tools/
directory is included in your PATH
environment variable, then execute: adb install bin/<*your app name*>-debug.apk
On your device, locate <*your app name*>
and open it.
Refer Running App
My problem was that I needed to have the ""
outside the expression since I have a dynamic variable inside the sed expression itself. So than the actual solution is that one from lenn jackman that you replace the "
inside the sed regex with [\"]
.
So my complete bash is:
RELEASE_VERSION="0.6.6"
sed -i -e "s#value=[\"]trunk[\"]#value=\"tags/$RELEASE_VERSION\"#g" myfile.xml
Here is:
#
is the sed separator
[\"]
= "
in regex
value = \"tags/$RELEASE_VERSION\"
= my replacement string, important it has just the \"
for the quotes
We were seeing this same issue in one of our old projects that was targeting Framework 4.5.2. I tried several scenarios including all of the ones listed above: target 4.6.1, add System.ValueTuple package, delete bin, obj, and .vs folders. No dice. Repeat the same process for 4.7.2. Then tried removing the System.ValueTuple package since I was targeting 4.7.2 as one commenter suggested. Still nothing. Checked csproj file reference path. Looks right. Even dropped back down to 4.5.2 and installing the package again. All this with several VS restarts and deleting the same folders several times. Literally nothing worked.
I had to refactor to use a struct instead. I hope others don't continue to run into this issue in the future but thought this might be helpful if you end up as stumped up as we were.
var formStr = JSON.stringify($("#form").serializeArray());
...
function Submit(){
var newformStr = JSON.stringify($("#form").serializeArray());
if (formStr != newformStr){
...
formChangedfunct();
...
}
else {
...
formUnchangedfunct();
...
}
}
I'm one of the developers of the Tooleap SDK. We also provide a way for developers to display always on top windows and buttons, and and we have dealt with a similar situation.
One problem the answers here haven't addressed is that of the Android "Secured Buttons".
Secured buttons have the filterTouchesWhenObscured
property which means they can't be interacted with, if placed under a window, even if that window does not receive any touches. Quoting the Android documentation:
Specifies whether to filter touches when the view's window is obscured by another visible window. When set to true, the view will not receive touches whenever a toast, dialog or other window appears above the view's window. Refer to the {@link android.view.View} security documentation for more details.
An example of such a button is the install button when you try to install third party apks. Any app can display such a button if adding to the view layout the following line:
android:filterTouchesWhenObscured="true"
If you display an always-on-top window over a "Secured Button", so all the secured button parts that are covered by an overlay will not handle any touches, even if that overlay is not clickable. So if you are planing to display such a window, you should provide a way for the user to move it or dismiss it. And if a part of your overlay is transparent, take into account that your user might be confused why is a certain button in the underlying app is not working for him suddenly.
so the .animate method works only if you have given a position attribute to an element, if not it didn't move?
for example i've seen that if i declare the div but i declare nothing in the css, it does not assume his default position and it does not move it into the page, even if i declare property margin: x w y z;
You could just check if the value is not zero.
if ((Int32)(letter & Letters.AB) != 0) { }
But I would consider it a better solution to introduce a new enumeration value with value zero and compare agains this enumeration value (if possible because you must be able to modify the enumeration).
[Flags]
enum Letters
{
None = 0,
A = 1,
B = 2,
C = 4,
AB = A | B,
All = AB | C
}
if (letter != Letters.None) { }
UPDATE
Missread the question - fixed the first suggestion and just ignore the second suggestion.
if
statement is not vectorized. For vectorized if statements you should use ifelse
. In your case it is sufficient to write
w <- function(a){
if (any(a>0)){
a/sum(a)
}
else 1
}
or a short vectorised version
ifelse(a > 0, a/sum(a), 1)
It depends on which do you want to use, because first function gives output vector of length 1 (in else part) and ifelse
gives output vector of length equal to length of a
.
As simple as this...
setSize(220, 400);
setLocationRelativeTo(null);
or if you are using a frame then set the frame to
frame.setSize(220, 400);
frame.setLocationRelativeTo(null);
For clarification, from the docs:
If the component is null, or the GraphicsConfiguration associated with this component is null, the window is placed in the center of the screen.
Before mounting external storage BOOT_COMPLETE is sent execute.if your app is installed to external storage it won't receive BOOT_COMPLETE broadcast message. To prevent this you can install your application in internal storage. you can do this just adding this line in menifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:installLocation="internalOnly"
... >
Some HTC devices can enable a "fast boot" feature that is more like a deep hibernation and not a real reboot and therefore should not give the BOOT_COMPLETE intent. To recover this you can add this intent filter inside your receiver:
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
any large single block of data stored in a database, such as a picture or sound file, which does not include record fields, and cannot be directly searched by the database's search engine.
I have checked and fixed the following and got it resolved -
/etc/httpd/conf/
10.12.13.4:80
It is same as above answers, but is simple in steps
c:\SRC\folder1
c:\SRC\folder2
c:\SRC\folder3
c:\SRC\folder4
to copy all above folders to c:\DST\ except folder1 and folder2.
Step1: create a file c:\list.txt with below content, one folder name per one line
folder1\
folder2\
Step2: Go to command pompt and run as below xcopy c:\SRC*.* c:\DST*.* /EXCLUDE:c:\list.txt
Your executable's working directory is probably set to something other than the directory where it is saved. Check your IDE settings.
To answer the first part of your question:
LPCSTR
is a pointer to a const string (LP means Long Pointer)
LPCTSTR
is a pointer to a const TCHAR
string, (TCHAR
being either a wide char or char depending on whether UNICODE is defined in your project)
LPTSTR
is a pointer to a (non-const) TCHAR
string
In practice when talking about these in the past, we've left out the "pointer to a" phrase for simplicity, but as mentioned by lightness-races-in-orbit they are all pointers.
This is a great codeproject article describing C++ strings (see 2/3 the way down for a chart comparing the different types)
Solution to this problem is simple
Go to build.gradle (module.app) file
It will help us to rebuild gradle for the project, to make it sync again.
The jQuery-rss project is pretty lightweight and doesn't impose any particular styling.
The syntax can be as simple as
$("#rss-feeds").rss("http://www.recruiter.com/feed/career.xml")
See a working example at http://jsfiddle.net/jhfrench/AFHfn/
Expanding upon other answers.
npm list -g
will show you the location of globally installed packages.
If you want to output that list to a file that you can then easily search in your text editor:
npm list -g > ~/Desktop/npmfiles.txt
You can adding a +
before the string without using parseInt and parseFloat and radix, Simply
sample:
var votevalue = +$('button').data('votevalue');
alert(typeof(votevalue));
Try using white-space: nowrap;
in the container style (instead of overflow: hidden;
)
If you don't want to change your table structure, you can run the following query:
ALTER TABLE [UserStore]
NOCHECK CONSTRAINT FK_UserStore_User_UserId
ALTER TABLE [UserIdentity]
NOCHECK CONSTRAINT FK_UserIdentity_User_UserId
BEGIN TRAN
UPDATE [user]
SET Id = 10
WHERE Id = 9
UPDATE [dbo].[UserStore]
SET UserId = 10
WHERE UserId = 9
UPDATE [dbo].UserIdentity
SET UserId = 10
WHERE UserId = 9
COMMIT TRAN
ALTER TABLE [UserStore]
CHECK CONSTRAINT FK_UserStore_User_UserId
ALTER TABLE UserIdentity
CHECK CONSTRAINT FK_UserIdentity_User_UserId
There could be following things in your settings.py:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ["templates"],
'APP_DIRS': True,
'OPTIONS': {
# ... some options here ...
},
},
]
OR
STATIC_URL = '/static/'
OR
STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), )
x=pd.DataFrame([1,2,3,4,5])
y=pd.DataFrame([5,4,3,2,1])
z=pd.concat([x,y],axis=1)
You can also reference a local gem with git if you happen to be working on it.
gem 'foo',
:git => '/Path/to/local/git/repo',
:branch => 'my-feature-branch'
Then, if it changes I run
bundle exec gem uninstall foo
bundle update foo
But I am not sure everyone needs to run these two steps.
Your webapp has servletcontainer specific libraries like servlet-api.jar file in its /WEB-INF/lib. This is not right.
Remove them all.
The /WEB-INF/lib should contain only the libraries specific to the webapp, not to the servletcontainer. The servletcontainer (like Tomcat) is the one who should already provide the servletcontainer specific libraries.
If you supply libraries from an arbitrary servletcontainer of a different make/version, you'll run into this kind of problems because your webapp wouldn't be able to run on a servletcontainer of a different make/version than where those libraries are originated from.
How to solve: In Eclipse Right click on the project in eclipse Properties -> Java Build Path -> Add library -> Server Runtime Library -> Apache Tomcat
Im Maven Project:-
add follwing line in pom.xml file
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${default.javax.servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${default.javax.servlet.jsp.version}</version>
<scope>provided</scope>
</dependency>
Maybe not what you were looking for, but perhaps nice for someone to know:
If you are using .net Web Api 2 you could just do the following:
if (!ModelState.IsValid)
return BadRequest(ModelState);
Depending on the model errors, you get this result:
{
Message: "The request is invalid."
ModelState: {
model.PropertyA: [
"The PropertyA field is required."
],
model.PropertyB: [
"The PropertyB field is required."
]
}
}
Alternate Bootstrap 4 solution (this way you can use divs which are smaller than col-6):
<div class="container">
<div class="row justify-content-center">
<div class="col-4">
One of two columns
</div>
<div class="col-4">
One of two columns
</div>
</div>
</div>
<td class="first"> <?php echo $proxy ?> </td>
is inside a literal string that you are echo
ing. End the string, or concatenate it correctly:
<td class="first">' . $proxy . '</td>
This is size improvement of cmlevy answer - try
<input type=file oninput="pic.src=window.URL.createObjectURL(this.files[0])">
<img id="pic" />
_x000D_
I ended up switching to Font-Awesome Icons. They are just as good if not better, and all you need to do is link in the font, happy days.
Some simple cases can be handled by defining a default in the database schema but that doesn't handle a number of trickier cases including calculated values and keys of other models. For these cases I do this:
after_initialize :defaults
def defaults
unless persisted?
self.extras||={}
self.other_stuff||="This stuff"
self.assoc = [OtherModel.find_by_name('special')]
end
end
I've decided to use the after_initialize but I don't want it to be applied to objects that are found only those new or created. I think it is almost shocking that an after_new callback isn't provided for this obvious use case but I've made do by confirming whether the object is already persisted indicating that it isn't new.
Having seen Brad Murray's answer this is even cleaner if the condition is moved to callback request:
after_initialize :defaults, unless: :persisted?
# ":if => :new_record?" is equivalent in this context
def defaults
self.extras||={}
self.other_stuff||="This stuff"
self.assoc = [OtherModel.find_by_name('special')]
end
The jQueryUI provides a extension to animate
function that allows you to animate css class.
edit: Example here
There are also methods to add/remove/toggle class which you might also be interested in.
You can show all commits that you have locally but not upstream with
git log @{u}..
@{u}
or @{upstream}
means the upstream branch of the current branch (see git rev-parse --help
or git help revisions
for details).
Just use the NumberFormat property after the Value property: In this example the Ranges are defined using variables called ColLetter and SheetRow and this comes from a for-next loop using the integer i, but they might be ordinary defined ranges of course.
TransferSheet.Range(ColLetter & SheetRow).Value = Range(ColLetter & i).Value TransferSheet.Range(ColLetter & SheetRow).NumberFormat = Range(ColLetter & i).NumberFormat
This is the best and reliable way to do this. Here is a simple example and after that you can develop your custom logic:
//In .ts
public showUploadButton:boolean = false;
if(some logic)
{
//your logic
showUploadButton = true;
}
//In template
<button [class]="showUploadButton ? 'btn btn-default': 'btn btn-info'">Upload</button>
The compiler doesn't know that spe_context_ptr_t is a type. Check that the appropriate typedef is in scope when this code is compiled. You may have forgotten to include the appropriate header file.
Suppose you have following lines of code
MyUrl = "www.google.com" #Your url goes here
urllib.urlretrieve(MyUrl)
If you are receiving following error message
AttributeError: module 'urllib' has no attribute 'urlretrieve'
Then you should try following code to fix the issue:
import urllib.request
MyUrl = "www.google.com" #Your url goes here
urllib.request.urlretrieve(MyUrl)
Java:
int actionBarHeight;
int[] abSzAttr;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
abSzAttr = new int[] { android.R.attr.actionBarSize };
} else {
abSzAttr = new int[] { R.attr.actionBarSize };
}
TypedArray a = obtainStyledAttributes(abSzAttr);
actionBarHeight = a.getDimensionPixelSize(0, -1);
xml:
?attr/actionBarSize
On Unix you can use valgrind
to find issues. It's free and powerful. If you'd rather do it yourself you can overload the new
and delete
operators to set up a configuration where you have 1 byte with 0xDEADBEEF
before and after each new object. Then track what happens at each iteration. This can fail to catch everything (you aren't guaranteed to even touch those bytes) but it has worked for me in the past on a Windows platform.
##Configuring credential.helper
On OS X (now macOS), run this in Terminal:
git config --global credential.helper osxkeychain
It enables Git to use file Keychain.app to store username and password and to retrieve the passphrase to your private SSH key from the keychain.
For Windows use:
git config --global credential.helper wincred
For Linux use:
git config --global credential.helper cache // If you want to cache the credentials for some time (default 15 minutes)
OR
git config --global credential.helper store // if you want to store the credentials for ever (considered unsafe)
Note : The first method will cache the credentials in memory, whereas the second will store them in ~/.git-credentials
in plain text format.
Check here for more info about Linux method.
Check here for more info about all three.
##Troubleshooting
If the Git credential helper is configured correctly macOS saves the passphrase in the keychain. Sometimes the connection between SSH and the passphrases stored in the keychain can break. Run ssh-add -K
or ssh-add ~/.ssh/id_rsa
to add the key to keychain again.
For macOS v10.12 (Sierra), ssh-add -K
needs to be run after every reboot. To avoid this, create ~/.ssh/config
with this content.
Host *
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/id_rsa
From the ssh_config
man
page on 10.12.2:
UseKeychain
On macOS, specifies whether the system should search for passphrases in the user's keychain when attempting to use a particular key. When the passphrase is provided by the user, this option also specifies whether the passphrase should be stored into the keychain once it has been verified to be correct. The argument must be 'yes' or 'no'. The default is 'no'.
Apple has added Technote 2449 which explains what happened.
Prior to macOS Sierra,
ssh
would present a dialog asking for your passphrase and would offer the option to store it into the keychain. This UI was deprecated some time ago and has been removed.
Updated answer for 06/19/2015 (if you're using java 8)
Just use assertj
Using assertj-core-3.0.0 + Java 8 Lambdas
@Test
public void shouldThrowIllegalArgumentExceptionWhenPassingBadArg() {
assertThatThrownBy(() -> myService.sumTingWong("badArg"))
.isInstanceOf(IllegalArgumentException.class);
}
Reference: http://blog.codeleak.pl/2015/04/junit-testing-exceptions-with-java-8.html
Static and final have some big differences:
Static variables or classes will always be available from (pretty much) anywhere. Final is just a keyword that means a variable cannot be changed. So if had:
public class Test{
public final int first = 10;
public static int second = 20;
public Test(){
second = second + 1
first = first + 1;
}
}
The program would run until it tried to change the "first" integer, which would cause an error. Outside of this class, you would only have access to the "first" variable if you had instantiated the class. This is in contrast to "second", which is available all the time.
Shameless plug I know, but you might want to consider a jQuery plugin that I wrote:
https://github.com/benmajor/jQuery-Mobile-Events
It does not require jQuery Mobile, only jQuery.
Use the RAISERROR
function:
RAISERROR( 'This message will show up right away...',0,1) WITH NOWAIT
You shouldn't completely replace all your prints with raiserror. If you have a loop or large cursor somewhere just do it once or twice per iteration or even just every several iterations.
Also: I first learned about RAISERROR at this link, which I now consider the definitive source on SQL Server Error handling and definitely worth a read:
http://www.sommarskog.se/error-handling-I.html
Instead of writing the code from the scratch you can use jquery plug in. Such plug in can provide many configuration option as well.
Here is the one I most liked.
simply try this 'listBox' is your list and 'yu' is a veriable to which the value on index 0 will be assigned
string yu = listBox1.Items[0].ToString();
MessageBox.Show(yu);
I could get away with this:
void setup() {
Serial.begin(9600);
}
void loop() {
String message = "";
while (Serial.available())
message.concat((char) Serial.read());
if (message != "")
Serial.println(message);
}
As others have answered… div
is a “block element” (now redefined as Flow Content) and span
is an “inline element” (Phrasing Content). Yes, you may change the default presentation of these elements, but there is a difference between “flow” versus “block”, and “phrasing” versus “inline”.
An element classified as flow content can only be used where flow content is expected, and an element classified as phrasing content can be used where phrasing content is expected. Since all phrasing content is flow content, a phrasing element can also be used anywhere flow content is expected. The specs provide more detailed info.
All phrasing elements, such as strong
and em
, can only contain other phrasing elements: you can’t put a table
inside a cite
for instance. Most flow content such as div
and li
can contain all types of flow content (as well as phrasing content), but there are a few exceptions: p
, pre
, and th
are examples of non-phrasing flow content (“block elements”) that can only contain phrasing content (“inline elements”). And of course there are the normal element restrictions such as dl
and table
only being allowed to contain certain elements.
While both div
and p
are non-phrasing flow content, the div
can contain other flow content children (including more div
s and p
s). On the other hand, p
may only contain phrasing content children. That means you can’t put a div
inside a p
, even though both are non-phrasing flow elements.
Now here’s the kicker. These semantic specifications are unrelated to how the element is displayed. Thus, if you have a div
inside a span
, you will get a validation error even if you have span {display: block;}
and div {display: inline;}
in your CSS.
Rather Cast It to an Object Array.
Object obj2 = from some source . . ;
Object[] objects=(Object[])obj2;
I use Bootstrap 3.4 For me this does not work
$('#myModal').modal('hide')
In desperation,I did this:
$('#myModal').hide();
$('.modal-backdrop').hide();
Maybe it's not elegant, but it works
I faced this issue, and resolved this issue using getchar() to catch the ('\n') new char
I'm adding this for posterity; There's an easier way that doesn't involve writing more JS. Using the amazing firebug addon for firefox,
I know its a bit late for answer but this is the first link appearing in google, and none of the above solutions were working for me.
I was having the same problem i.e after uploading build from application loader it stuck in processing. This happened many times, after hours of head banging I found that as soon as I close the application loader on my Mac, build status was changed :)
I hope this answer will help many.
public void DeleteUserIMP(UserIMP useriamp) {
synchronized (ListUserIMP) {
if (ListUserIMP.isEmpty()) {
System.out.println("user is empty");
} else {
Iterator<UserIMP> it = ListUserIMP.iterator();
while (it.hasNext()) {
UserIMP user = it.next();
if (useriamp.getMoblieNumber().equals(user.getMoblieNumber())) {
it.remove();
System.out.println("remove it");
}
}
// ListUserIMP.remove(useriamp);
System.out.println(" this user removed");
}
Constants.RESULT_FOR_REGISTRATION = Constants.MESSAGE_OK;
// System.out.println("This user Deleted " + Constants.MESSAGE_OK);
}
}
Be carefully though. If you return Collections.emptyList()
and then try to do some changes with it like add()
or smth like that, u will have an UnsupportedOperationException()
because Collections.emptyList()
returns an immutable object.
A little bit late for this question, but if you:
cat /path/to/repo/.git/config
You will see the url of the repository which will include the reponame:
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
ignorecase = true
precomposeunicode = true
[remote "origin"]
url = https://github.com/your_git_user_name/your_git_repo_name.git
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
remote = origin
merge = refs/heads/master
Just for the fun. You can also access the values of the PSObject directly like below:
$assoc.psobject.Properties.value -join " - "
But if you do not specify that the object should be ordered, PowerShell will display the values in a random order. So you should add the flag [ordered]
:
$assoc = [pscustomobject] [ordered] @{
Id = 42
Name = "Slim Shady"
Owner = "Eminem"
}
If you only want to commit all the changes in one commit as if you typed yourself, --squash will do too
$ git merge --squash v1.0
$ git commit
I faced to this problem a lot when developing my company's website using WordPress. Finally I found that it happened because me and my colleague update the website at the same time as well as we installed and activated many plugins that we did not use them. The solution for me was we update the website in different time and deactivated and uninstalled those plugins.
Sorry, if this is irelevant, but will return list with matches using FindAll() in case you need this:
private bool IsContain(string cont)
{
List<string> ListToMatch= new List<string>() {"string1","string2"};
if (ListToMatch.ToArray().Any(cont.Contains))
{
return false;
}
else
return true;
}
And usage:
List<string> ListToCheck = new List<string>() {"string1","string2","string3","string4"};
List<string> FinalList = ListToCheck.FindAll(IsContain);
The final list contains only the matched elements string1 and string2 from list to check. Can easy be switched to int List.
I faced this issue when trying to set something to redis. The problem was that I previously used "set" method to set data with a certain key, like
$redis->set('persons', $persons)
Later I decided to change to "hSet" method, and I tried it this way
foreach($persons as $person){
$redis->hSet('persons', $person->id, $person);
}
Then I got the aforementioned error. So, what I had to do is to go to redis-cli and manually delete "persons" entry with
del persons
It simply couldn't write different data structure under existing key, so I had to delete the entry and hSet then.
Two-stage authentication is not supported with IIS7 Integrated mode. Authentication is now modularized, so rather than IIS performing authentication followed by asp.net performing authentication, it all happens at the same time.
You can either:
The graphicx
package provides the command \resizebox{width}{height}{object}
:
\documentclass{article}
\usepackage{graphicx}
\begin{document}
\hrule
%%%
\makeatletter%
\setlength{\@tempdima}{\the\columnwidth}% the, well columnwidth
\settowidth{\@tempdimb}{(\ref{Equ:TooLong})}% the width of the "(1)"
\addtolength{\@tempdima}{-\the\@tempdimb}% which cannot be used for the math
\addtolength{\@tempdima}{-1em}%
% There is probably some variable giving the required minimal distance
% between math and label, but because I do not know it I used 1em instead.
\addtolength{\@tempdima}{-1pt}% distance must be greater than "1em"
\xdef\Equ@width{\the\@tempdima}% space remaining for math
\begin{equation}%
\resizebox{\Equ@width}{!}{$\displaystyle{% to get everything inside "big"
A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z}$}%
\label{Equ:TooLong}%
\end{equation}%
\makeatother%
%%%
\hrule
\end{document}
Should just be this:
var jobject = JsonConvert.DeserializeObject<RootObject>(jsonstring);
You can paste the json string to here: http://json2csharp.com/ to check your classes are correct.
Look at the const
and static
section of the Rust book.
You can use something as follows:
const N: i32 = 5;
or
static N: i32 = 5;
in global space.
But these are not mutable. For mutability, you could use something like:
static mut N: i32 = 5;
Then reference them like:
unsafe {
N += 1;
println!("N: {}", N);
}
follow this tutorial. i ran the install-opencv.sh file in bash. its in the tutorial
read the example from openCV
CMakeLists.txt
cmake_minimum_required(VERSION 3.7)
project(openCVTest)
# cmake needs this line
cmake_minimum_required(VERSION 2.8)
# Define project name
project(opencv_example_project)
# Find OpenCV, you may need to set OpenCV_DIR variable
# to the absolute path to the directory containing OpenCVConfig.cmake file
# via the command line or GUI
find_package(OpenCV REQUIRED)
# If the package has been found, several variables will
# be set, you can find the full list with descriptions
# in the OpenCVConfig.cmake file.
# Print some message showing some of them
message(STATUS "OpenCV library status:")
message(STATUS " version: ${OpenCV_VERSION}")
message(STATUS " libraries: ${OpenCV_LIBS}")
message(STATUS " include path: ${OpenCV_INCLUDE_DIRS}")
if(CMAKE_VERSION VERSION_LESS "2.8.11")
# Add OpenCV headers location to your include paths
include_directories(${OpenCV_INCLUDE_DIRS})
endif()
# Declare the executable target built from your sources
add_executable(main main.cpp)
# Link your application with OpenCV libraries
target_link_libraries(main ${OpenCV_LIBS})
main.cpp
/**
* @file LinearBlend.cpp
* @brief Simple linear blender ( dst = alpha*src1 + beta*src2 )
* @author OpenCV team
*/
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include <stdio.h>
using namespace cv;
/** Global Variables */
const int alpha_slider_max = 100;
int alpha_slider;
double alpha;
double beta;
/** Matrices to store images */
Mat src1;
Mat src2;
Mat dst;
//![on_trackbar]
/**
* @function on_trackbar
* @brief Callback for trackbar
*/
static void on_trackbar( int, void* )
{
alpha = (double) alpha_slider/alpha_slider_max ;
beta = ( 1.0 - alpha );
addWeighted( src1, alpha, src2, beta, 0.0, dst);
imshow( "Linear Blend", dst );
}
//![on_trackbar]
/**
* @function main
* @brief Main function
*/
int main( void )
{
//![load]
/// Read images ( both have to be of the same size and type )
src1 = imread("../data/LinuxLogo.jpg");
src2 = imread("../data/WindowsLogo.jpg");
//![load]
if( src1.empty() ) { printf("Error loading src1 \n"); return -1; }
if( src2.empty() ) { printf("Error loading src2 \n"); return -1; }
/// Initialize values
alpha_slider = 0;
//![window]
namedWindow("Linear Blend", WINDOW_AUTOSIZE); // Create Window
//![window]
//![create_trackbar]
char TrackbarName[50];
sprintf( TrackbarName, "Alpha x %d", alpha_slider_max );
createTrackbar( TrackbarName, "Linear Blend", &alpha_slider, alpha_slider_max, on_trackbar );
//![create_trackbar]
/// Show some stuff
on_trackbar( alpha_slider, 0 );
/// Wait until user press some key
waitKey(0);
return 0;
}
Tested in linux mint 17
Using a DateTime parameter is the best way. However, if you still want to pass a DateTime as a string, then the CAST should not be necessary provided that a language agnostic format is used.
e.g.
Given a table created like :
create table t1 (id int, EndDate DATETIME)
insert t1 (id, EndDate) values (1, GETDATE())
The following should always work :
update t1 set EndDate = '20100525' where id = 1 -- YYYYMMDD is language agnostic
The following will work :
SET LANGUAGE us_english
update t1 set EndDate = '2010-05-25' where id = 1
However, this won't :
SET LANGUAGE british
update t1 set EndDate = '2010-05-25' where id = 1
This is because 'YYYY-MM-DD' is not a language agnostic format (from SQL server's point of view) .
The ISO 'YYYY-MM-DDThh:mm:ss' format is also language agnostic, and useful when you need to pass a non-zero time.
More info : http://karaszi.com/the-ultimate-guide-to-the-datetime-datatypes
In my Case since I was working in my development environment, someone had shut down the Domain Controller and Windows Credentials couldn't be authenticated. After turning on the Domain Controller, the error disappeared and everything worked just fine.