Step 1 : Create file named : my_button_bg.xml
Step 2 : Place this file in res/drawables.xml
Step 3 : Insert below code
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient android:startColor="#FFFFFF"
android:endColor="#00FF00"
android:angle="270" />
<corners android:radius="3dp" />
<stroke android:width="5px" android:color="#000000" />
</shape>
Step 4: Use code "android:background="@drawable/my_button_bg" where needed eg below:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your Text"
android:background="@drawable/my_button_bg"
/>
The easiest way is to use LINQ's Union
method:
var aUb = A.Union(B).ToList();
You can reset the padding (and I think everything else) with initial
to the default.
p {
padding: initial;
}
For a new version of Swift try this
override var shouldAutorotate: Bool {
return false
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.portrait
}
override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
return UIInterfaceOrientation.portrait
}
While it is true that exporting an excel file that contains special characters to csv can be a pain in the ass, there is however a simple work around: simply copy/paste the cells into a google docs and then save from there.
If you are optimizing your page for IE8 or newer, you should really consider whether you need jquery or not. Modern browsers have many assets natively which jquery provides.
If you care for performance, you can have incredible performance benefits (2-10 faster) using native javascript: http://jsperf.com/jquery-vs-native-selector-and-element-style/2
I transformed a div-tagcloud from jquery to native javascript (IE8+ compatible), the results are impressive. 4 times faster with just a little overhead.
Number of lines Execution Time
Jquery version : 340 155ms
Native version : 370 27ms
You Might Not Need Jquery provides a really nice overview, which native methods replace for which browser version.
http://youmightnotneedjquery.com/
Appendix: Further speed comparisons how native methods compete to jquery
You could also use:
SELECT t.*
FROM
TABLENAME t
JOIN
( SELECT A, MAX(col_date) AS col_date
FROM TABLENAME
GROUP BY A
) m
ON m.A = t.A
AND m.col_date = t.col_date
You need to convert the date to YYYY-MM-DD in order to insert it as a MySQL date using the default configuration.
One way to do that is STR_TO_DATE()
:
insert into your_table (...)
values (...,str_to_date('07-25-2012','%m-%d-%Y'),...);
The call stack is implemented by the x86 instruction set and the operating system.
Instructions like push and pop adjust the stack pointer while the operating system takes care of allocating memory as the stack grows for each thread.
The fact that the x86 stack "grows down" from higher to lower addresses make this architecture more susceptible to the buffer overflow attack.
Best practice of getting length is use length
filter returns the number of items of a sequence or mapping, or the length of a string. For example: {{ notcount | length }}
But you can calculate count of elements in for
loop. For example:
{% set count = 0 %}
{% for nc in notcount %}
{% set count = count + 1 %}
{% endfor %}
{{ count }}
This solution helps if you want to calculate count of elements by condition, for example you have a property name
inside object and you want to calculate count of objects with not empty names:
{% set countNotEmpty = 0 %}
{% for nc in notcount if nc.name %}
{% set countNotEmpty = countNotEmpty + 1 %}
{% endfor %}
{{ countNotEmpty }}
Useful links:
we all know generally that for sending the data according to the http standards we generally use POST request. But if you really want to use Get for sending the data in your scenario I would suggest you to use the query-string or query-parameters.
1.GET use of Query string as.
{{url}}admin/recordings/some_id
here the some_id is mendatory parameter to send and can be used and req.params.some_id at server side.
2.GET use of query string as{{url}}admin/recordings?durationExact=34&isFavourite=true
here the durationExact ,isFavourite is optional strings to send and can be used and req.query.durationExact and req.query.isFavourite at server side.
3.GET Sending arrays
{{url}}admin/recordings/sessions/?os["Windows","Linux","Macintosh"]
and you can access those array values at server side like this
let osValues = JSON.parse(req.query.os);
if(osValues.length > 0)
{
for (let i=0; i<osValues.length; i++)
{
console.log(osValues[i])
//do whatever you want to do here
}
}
You can use GCD (in the example with a 10 second delay):
let triggerTime = (Int64(NSEC_PER_SEC) * 10)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in
self.functionToCall()
})
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
self.functionToCall()
})
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
//call any function
}
To answer the question in your subject line,* yes, there are closures in Python, except they only apply inside a function, and also (in Python 2.x) they are read-only; you can't re-bind the name to a different object (though if the object is mutable, you can modify its contents). In Python 3.x, you can use the nonlocal
keyword to modify a closure variable.
def incrementer():
counter = 0
def increment():
nonlocal counter
counter += 1
return counter
return increment
increment = incrementer()
increment() # 1
increment() # 2
* The question origially asked about closures in Python.
#include <ctype>
char * remove_spaces(char * source, char * target)
{
while(*source++ && *target)
{
if (!isspace(*source))
*target++ = *source;
}
return target;
}
Notes;
if addition please, if you have a long text please you can use this css code bellow;
text-overflow: ellipsis;
overflow: visible;
white-space: nowrap;
make the whole line text visible.
Assuming you're interested in whether the variable has been explicitly assigned a value or not, the answer is "not really". There's absolutely no difference between a field (instance variable or class variable) which hasn't been explicitly assigned at all yet, and one which has been assigned its default value - 0, false, null etc.
Now if you know that once assigned, the value will never reassigned a value of null, you can use:
if (box != null) {
box.removeFromCanvas();
}
(and that also avoids a possible NullPointerException
) but you need to be aware that "a field with a value of null" isn't the same as "a field which hasn't been explicitly assigned a value". Null is a perfectly valid variable value (for non-primitive variables, of course). Indeed, you may even want to change the above code to:
if (box != null) {
box.removeFromCanvas();
// Forget about the box - we don't want to try to remove it again
box = null;
}
The difference is also visible for local variables, which can't be read before they've been "definitely assigned" - but one of the values which they can be definitely assigned is null (for reference type variables):
// Won't compile
String x;
System.out.println(x);
// Will compile, prints null
String y = null;
System.out.println(y);
I would prefer using JConsole for application monitoring, and it does have graphical view. If you’re using JDK 5.0 or above then it’s the best. Please refer to this using jconsole page for more details.
I have been primarily using it for GC tuning and finding bottlenecks.
Set it the same way you'd set the width of any other HTML element, with CSS:
audio { width: 200px; }
Note that audio
is an inline element by default in Firefox, so you might also want to set it to display: block
. Here's an example.
Simply
const char S[] = "ABCD";
should work.
What's your compiler?
Visifire supports wide range of 2D and 3D charts with zooming and panning functionality.
Full Disclosure: I have been involved in the development of Visifire.
You should use profiles.
<profiles>
<profile>
<id>otherOutputDir</id>
<build>
<directory>yourDirectory</directory>
</build>
</profile>
</profiles>
And start maven with your profile
mvn compile -PotherOutputDir
If you really want to define your directory from the command line you could do something like this (NOT recommended at all) :
<properties>
<buildDirectory>${project.basedir}/target</buildDirectory>
</properties>
<build>
<directory>${buildDirectory}</directory>
</build>
And compile like this :
mvn compile -DbuildDirectory=test
That's because you can't change the target directory by using -Dproject.build.directory
If you are using the batch conversion, in the window click "options" in the "Batch conversion settings-output format" and tick the two boxes "save transparent color" (one under "PNG" and the other under "ICO").
the xcode UI has changed a bit from one version to the next so here is where you update the plist for 9.0 beta 4 if it helps Project ->Target ->Info
For a dynamic approach, if your labels are always in front of your text areas:
$(object).prev("label").text(charsleft);
You can' just add a class to each of your DIVs and apply the rule to the class in this way:
HTML:
<div class="myclass" id="s1">...</div>
<div class="myclass" id="s2">...</div>
CSS:
//css
.myclass
{
...
}
You can do it like this:
class UsersController < ApplicationController
## Exception Handling
class NotActivated < StandardError
end
rescue_from NotActivated, :with => :not_activated
def not_activated(exception)
flash[:notice] = "This user is not activated."
Event.new_event "Exception: #{exception.message}", current_user, request.remote_ip
redirect_to "/"
end
def show
// Do something that fails..
raise NotActivated unless @user.is_activated?
end
end
What you're doing here is creating a class "NotActivated" that will serve as Exception. Using raise, you can throw "NotActivated" as an Exception. rescue_from is the way of catching an Exception with a specified method (not_activated in this case). Quite a long example, but it should show you how it works.
Best wishes,
Fabian
If it's a server socket, you should call listen()
on your socket, and then getsockname()
to find the port number on which it is listening:
struct sockaddr_in sin;
socklen_t len = sizeof(sin);
if (getsockname(sock, (struct sockaddr *)&sin, &len) == -1)
perror("getsockname");
else
printf("port number %d\n", ntohs(sin.sin_port));
As for the IP address, if you use INADDR_ANY
then the server socket can accept connections to any of the machine's IP addresses and the server socket itself does not have a specific IP address. For example if your machine has two IP addresses then you might get two incoming connections on this server socket, each with a different local IP address. You can use getsockname()
on the socket for a specific connection (which you get from accept()
) in order to find out which local IP address is being used on that connection.
HTML
<div id="mydiv" data-myval="10"></div>
JavaScript:
Using DOM's getAttribute()
property
var brand = mydiv.getAttribute("data-myval")//returns "10"
mydiv.setAttribute("data-myval", "20") //changes "data-myval" to "20"
mydiv.removeAttribute("data-myval") //removes "data-myval" attribute entirely
Using JavaScript's dataset
property
var myval = mydiv.dataset.myval //returns "10"
mydiv.dataset.myval = '20' //changes "data-myval" to "20"
mydiv.dataset.myval = null //removes "data-myval" attribute
If you have this error on PYCHARM: ImportError: No module named mysql.connector
Try this solution: Open Pycharm go to File->Settings-> Project->Python Interpreter inside Pycharm, Then press + icon to install mysql-connector. Problem solved!
I wrote telegram bot, and have some problem with update rows. Use this example, if you have Model
def update_state(chat_id, state):
try:
value = Users.query.filter(Users.chat_id == str(chat_id)).first()
value.state = str(state)
db.session.flush()
db.session.commit()
#db.session.close()
except:
print('Error in def update_state')
Why use db.session.flush()
? That's why >>> SQLAlchemy: What's the difference between flush() and commit()?
I would recommend Ulrich Drepper's SHA-256/SHA-512 based crypt implementation.
We ported these algorithms to Java, and you can find a freely licensed version of them at ftp://ftp.arlut.utexas.edu/java_hashes/.
Note that most modern (L)Unices support Drepper's algorithm in their /etc/shadow files.
You should not parse XML using tools like sed, or awk. It's error-prone.
If input changes, and before name parameter you will get new-line character instead of space it will fail some day producing unexpected results.
If you are really sure, that your input will be always formated this way, you can use cut
.
It's faster than sed
and awk
:
cut -d'"' -f2 < input.txt
It will be better to first parse it, and extract only parameter name attribute:
xpath -q -e //@name input.txt | cut -d'"' -f2
To learn more about xpath, see this tutorial: http://www.w3schools.com/xpath/
type Services
at search, then start Services
then start all VM services
My solution involves a simple Pair class I created for general utility, and which is operationally essentially the same as the framework class KeyValuePair. Then I created a couple extension functions for IEnumerable called Ordinate (from the set theory term "ordinal").
These functions will return for each item a Pair object containing the index, and the item itself.
public static IEnumerable<Pair<Int32, X>> Ordinate<X>(this IEnumerable<X> lhs)
{
return lhs.Ordinate(0);
}
public static IEnumerable<Pair<Int32, X>> Ordinate<X>(this IEnumerable<X> lhs, Int32 initial)
{
Int32 index = initial - 1;
return lhs.Select(x => new Pair<Int32, X>(++index, x));
}
Building on the answer by @Jonas_Wilms if you do not want to type in all your fields:
var result = {};
for ( let { first_field, ...fields } of your_data )
{
result[first_field] = result[first_field] || [];
result[first_field].push({ ...fields });
}
I didn't make any benchmark but I believe using a for loop would be more efficient than anything suggested in this answer as well.
Considering that in most cases you don't want your entire data contract to have types supplied, but only those which are containing an abstract or interface, or list thereof; and also considering these instances are very rare and easily identifiable within your data entities, the easiest and least verbose way is to use
[JsonProperty(ItemTypeNameHandling = TypeNameHandling.Objects)]
public IEnumerable<ISomeInterface> Items { get; set; }
as attribute on your property containing the enumerable/list/collection. This will target only that list, and only append type information for the contained objects, like this:
{
"Items": [
{
"$type": "Namespace.ClassA, Assembly",
"Property": "Value"
},
{
"$type": "Namespace.ClassB, Assembly",
"Property": "Value",
"Additional_ClassB_Property": 3
}
]
}
Clean, simple, and located where the complexity of your data model is introduced, instead of hidden away in some converter.
Nothing above helped me. The fingerprint dialog did not appear. I checked another android device and the dialog appeared and debug was possible. So the problem was on device side not on computer side I made reset "to factory settings" on device and this helped me.
You may try this way. just use a function to get your object
def get_object(self, id):
try:
return UniversityDetails.objects.get(email__exact=email)
except UniversityDetails.DoesNotExist:
return False
var str = "I expect five hundred dollars ($500) ($1).";
var rex = /\$\d+(?=\))/;
alert(rex.exec(str));
Will match the first number starting with a $ and followed by ')'. ')' will not be part of the match. The code alerts with the first match.
var str = "I expect five hundred dollars ($500) ($1).";
var rex = /\$\d+(?=\))/g;
var matches = str.match(rex);
for (var i = 0; i < matches.length; i++)
{
alert(matches[i]);
}
This code alerts with all the matches.
References:
search for "?=n" http://www.w3schools.com/jsref/jsref_obj_regexp.asp
search for "x(?=y)" https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp
(For those who stumble upon this from your search engine of choice)
This just recursively traces down the folder, so you don't need to duplicate your code twice. Also the OPs logic is needlessly complex.
Wscript.Echo "begin."
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objSuperFolder = objFSO.GetFolder(WScript.Arguments(0))
Call ShowSubfolders (objSuperFolder)
Wscript.Echo "end."
WScript.Quit 0
Sub ShowSubFolders(fFolder)
Set objFolder = objFSO.GetFolder(fFolder.Path)
Set colFiles = objFolder.Files
For Each objFile in colFiles
If UCase(objFSO.GetExtensionName(objFile.name)) = "PDF" Then
Wscript.Echo objFile.Name
End If
Next
For Each Subfolder in fFolder.SubFolders
ShowSubFolders(Subfolder)
Next
End Sub
Using the MouseEvent api, to check the pressed button, if any:
document.addEventListener('mousedown', (e) => console.log(e.buttons))
_x000D_
A number representing one or more buttons. For more than one button pressed simultaneously, the values are combined (e.g., 3 is primary + secondary).
0 : No button or un-initialized 1 : Primary button (usually the left button) 2 : Secondary button (usually the right button) 4 : Auxilary button (usually the mouse wheel button or middle button) 8 : 4th button (typically the "Browser Back" button) 16 : 5th button (typically the "Browser Forward" button)
Fairly simple process I am using SCSS obviously but you don't have to as it's just CSS in the end!
<span class="menu">Menu</span>
.menu {
position: relative;
text-decoration: none;
font-weight: 400;
color: blue;
transition: all .35s ease;
&::before {
content: "";
position: absolute;
width: 100%;
height: 2px;
bottom: 0;
left: 0;
background-color: yellow;
visibility: hidden;
-webkit-transform: scaleX(0);
transform: scaleX(0);
-webkit-transition: all 0.3s ease-in-out 0s;
transition: all 0.3s ease-in-out 0s;
}
&:hover {
color: yellow;
&::before {
visibility: visible;
-webkit-transform: scaleX(1);
transform: scaleX(1);
}
}
}
If for some people (like me earlier) the above answers don't work, I think the following answer would work (for Mac users I think) Enter the following commands to do flask run
$ export FLASK_APP = hello.py
$ export FLASK_ENV = development
$ flask run
Alternatively you can do the following (I haven't tried this but one resource online talks about it)
$ export FLASK_APP = hello.py
$ python -m flask run
source: For more
add async defer at the begining of map api key call.
If you want to make a change global to the whole notebook:
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams["figure.figsize"] = [10, 5]
Just keep it simple :)
grep + echo should suffice:
grep -qxF 'include "/configs/projectname.conf"' foo.bar || echo 'include "/configs/projectname.conf"' >> foo.bar
-q
be quiet-x
match the whole line-F
pattern is a plain stringEdit: incorporated @cerin and @thijs-wouters suggestions.
I did this by putting target="_blank" in the linkbutton
<asp:LinkButton ID="btn" runat="server" CausesValidation="false" Text="Print" Visible="false" target="_blank" />
then in the codebehind pageload just set the href attribute:
btn.Attributes("href") = String.Format(ResolveUrl("~/") + "test/TestForm.aspx?formId={0}", formId)
git config --global alias.count 'rev-list --all --count'
If you add this to your config, you can just reference the command;
git count
You can also use ddms for logcat logs where just giving search of the app name you will all info but you have to select Info instead of verbose or other options. check this below image.
The original request has been answered already.
However, I am posting the below answer for those who might be looking for generic transliteration code to transliterate any charset to Latin/English in Java.
Naive meaning of tranliteration: Translated string in it's final form/target charset sounds like the string in it's original form. If we want to transliterate any charset to Latin(English alphabets), then ICU4(ICU4J library in java ) will do the job.
Here is the code snippet in java:
import com.ibm.icu.text.Transliterator; //ICU4J library import
public static String TRANSLITERATE_ID = "NFD; Any-Latin; NFC";
public static String NORMALIZE_ID = "NFD; [:Nonspacing Mark:] Remove; NFC";
/**
* Returns the transliterated string to convert any charset to latin.
*/
public static String transliterate(String input) {
Transliterator transliterator = Transliterator.getInstance(TRANSLITERATE_ID + "; " + NORMALIZE_ID);
String result = transliterator.transliterate(input);
return result;
}
you are thinking too much... Take a look at this [i think this is what you wanted - if not let me know]
css
.even{background: red; color:white;}
.odd{background: darkred; color:white;}
html
<div class="container">
<ul class="list-unstyled">
<li class="col-md-6 odd">Dumby Content</li>
<li class="col-md-6 odd">Dumby Content</li>
<li class="col-md-6 even">Dumby Content</li>
<li class="col-md-6 even">Dumby Content</li>
<li class="col-md-6 odd">Dumby Content</li>
<li class="col-md-6 odd">Dumby Content</li>
</ul>
</div>
<div class="block blockLeft">...</div>
<div class="block blockRight">...</div>
<div class="block blockLeft">...</div>
<div class="block blockRight">...</div>
<div class="block blockLeft">...</div>
<div class="block blockRight">...</div>
block {width:300px;}
blockLeft {float:left;}
blockRight {float:right;}
But if the number of div's elements is not fixed or you don't know how much it could be, you still need JS. use jQuery :even
, :odd
Do you need the cursor to be a "wait" cursor only when it's over that particular page/usercontrol? If not, I'd suggest using Mouse.OverrideCursor:
Mouse.OverrideCursor = Cursors.Wait;
try
{
// do stuff
}
finally
{
Mouse.OverrideCursor = null;
}
This overrides the cursor for your application rather than just for a part of its UI, so the problem you're describing goes away.
add "distinct" after "select".
select distinct a.FirstName, a.LastName, v.District , v.LastName
from AddTbl a
inner join ValTbl v where a.LastName = v.LastName order by Firstname
Another option is using the map function of the purrr package.
library(purrr)
map(df,class)
The script isn't even necessary, split(1) supports the wanted feature out of the box:
split -l 75 auth.log auth.log.
The above command splits the file in chunks of 75 lines a piece, and outputs file on the form: auth.log.aa, auth.log.ab, ...
wc -l
on the original file and output gives:
321 auth.log
75 auth.log.aa
75 auth.log.ab
75 auth.log.ac
75 auth.log.ad
21 auth.log.ae
642 total
So you are doing the right thing concerning "-XX:MaxPermSize=512m": it is indeed the correct syntax. You could try to set these options directly to the Catalyna server files so they are used on server start.
Maybe this post will help you!
How to make sure that Tomcat6 reads CATALINA_OPTS on Windows?
They have set the header to SAMEORIGIN in this case, which means that they have disallowed loading of the resource in an iframe outside of their domain. So this iframe is not able to display cross domain
For this purpose you need to match the location in your apache or any other service you are using
If you are using apache then in httpd.conf file.
<LocationMatch "/your_relative_path">
ProxyPass absolute_path_of_your_application/your_relative_path
ProxyPassReverse absolute_path_of_your_application/your_relative_path
</LocationMatch>
Is that a proper connection string?
Where is the SQL Server instance located?
You will need to verify that you are able to conenct to SQL Server using the connection string, you specified above.
EDIT: Look at the State property of the recordset to see if it is Open?
Also, change the CursorLocation property to adUseClient before opening the recordset.
Following short code can help:
df3 = df3.rename(columns={c: c.replace(' ', '') for c in df3.columns})
Remove spaces from columns.
There is very useful module that can do this:
from file_read_backwards import FileReadBackwards
with FileReadBackwards("/tmp/file", encoding="utf-8") as frb:
# getting lines by lines starting from the last line up
for l in frb:
print(l)
In Controller i have specified the below code with ActionResult which is a base class that can have 11 subtypes in MVC like: ViewResult, PartialViewResult, EmptyResult, RedirectResult, RedirectToRouteResult, JsonResult, JavaScriptResult, ContentResult, FileContentResult, FileStreamResult, FilePathResult.
public ActionResult Index()
{
if (HttpContext.Session["LoggedInUser"] == null)
{
return RedirectToAction("Login", "Home");
}
else
{
return View(); // returns ViewResult
}
}
//More Examples
[HttpPost]
public ActionResult Index(string Name)
{
ViewBag.Message = "Hello";
return Redirect("Account/Login"); //returns RedirectResult
}
[HttpPost]
public ActionResult Index(string Name)
{
return RedirectToRoute("RouteName"); // returns RedirectToRouteResult
}
Likewise we can return all these 11 subtypes by using ActionResult() without specifying every subtype method explicitly. ActionResult is the best thing if you are returning different types of views.
No, you cannot. But you can create a user defined table function.
Basically it would be the wrong thing to do.
There are two ways this could be implemented:
Keep hold of the lock, only releasing it at the end of the block.
This is a really bad idea as you don't know how long the asynchronous operation is going to take. You should only hold locks for minimal amounts of time. It's also potentially impossible, as a thread owns a lock, not a method - and you may not even execute the rest of the asynchronous method on the same thread (depending on the task scheduler).
Release the lock in the await, and reacquire it when the await returns
This violates the principle of least astonishment IMO, where the asynchronous method should behave as closely as possible like the equivalent synchronous code - unless you use Monitor.Wait
in a lock block, you expect to own the lock for the duration of the block.
So basically there are two competing requirements here - you shouldn't be trying to do the first here, and if you want to take the second approach you can make the code much clearer by having two separated lock blocks separated by the await expression:
// Now it's clear where the locks will be acquired and released
lock (foo)
{
}
var result = await something;
lock (foo)
{
}
So by prohibiting you from awaiting in the lock block itself, the language is forcing you to think about what you really want to do, and making that choice clearer in the code that you write.
There is now a finished proposal for integrating String.prototype.replaceAll
into the official specification. Eventually, developers will not have to come up with their own implementations for replaceAll
- instead, modern Javascript engines will support it natively.
The proposal is at stage 4, which means that everything is complete, and all that's left is for browsers to start implementing it.
It has shipped in the latest versions of Chrome, Firefox, and Safari.
Here are the implementation details:
Per the current TC39 consensus,
String.prototype.replaceAll
behaves identically toString.prototype.replace
in all cases, except for the following two cases:
- If
searchValue
is a string,String.prototype.replace
only replaces a single occurrence of thesearchValue
, whereasString.prototype.replaceAll
replaces all occurrences of thesearchValue
(as if.split(searchValue).join(replaceValue)
or a global & properly-escaped regular expression had been used).- If
searchValue
is a non-global regular expression,String.prototype.replace
replaces a single match, whereasString.prototype.replaceAll
throws an exception. This is done to avoid the inherent confusion between the lack of a global flag (which implies "do NOT replace all") and the name of the method being called (which strongly suggests "replace all").Notably,
String.prototype.replaceAll
behaves just likeString.prototype.replace
ifsearchValue
is a global regular expression.
You can see a spec-compliant polyfill here.
In supported environments, the following snippet will log foo-bar-baz
, without throwing an error:
const str = 'foo bar baz';
console.log(
str.replaceAll(' ', '-')
);
_x000D_
here is the example which i used to retrive and parse json data from s3.
var params = {Bucket: BUCKET_NAME, Key: KEY_NAME};
new AWS.S3().getObject(params, function(err, json_data)
{
if (!err) {
var json = JSON.parse(new Buffer(json_data.Body).toString("utf8"));
// PROCESS JSON DATA
......
}
});
I had the same problem, and my solving was to replace :
return redirect(url_for('index'))
with
return render_template('indexo.html',data=Todos.query.all())
in my POST
and DELETE
route.
In my case, it worked when I removed the .idea folder from the project (Project/.ida) and re-opened Android Studio again.
Create a new "Empty Project" , Add your Cpp file to the new project, delete the line that includes stdafx.
Done.
The project no longer needs the stdafx. It is added automatically when you create projects with installed templates.
Python's print
function adds a newline character to its input. If you give it no input it will just print a newline character
print()
Will print an empty line. If you want to have an extra line after some text you're printing, you can a newline to your text
my_str = "hello world"
print(my_str + "\n")
If you're doing this a lot, you can also tell print
to add 2 newlines instead of just one by changing the end=
parameter (by default end="\n"
)
print("hello world", end="\n\n")
But you probably don't need this last method, the two before are much clearer.
Found solution in http://senthilkl.blogspot.lu/2012/11/how-to-send-html-emails-using-sendemail.html
sendEmail -f "oracle@server" -t "[email protected]" -u "Alert: Backup complete" -o message-content-type=html -o message-file=$LOG_FILE -a $LOG_FILE_ATTACH
The Angular microsyntax lets you configure a directive in a compact, friendly string. The microsyntax parser translates that string into attributes on the <ng-template>
. The let keyword declares a template input variable that you reference within the template.
Another use case could be an event dispatcher bound at runtime:
MyClass = function () {
this.events = {};
// Fire up an event (most probably from inside an instance method)
this.OnFirstRun();
// Fire up other event (most probably from inside an instance method)
this.OnLastRun();
}
MyClass.prototype.dispatchEvents = function () {
var EventStack=this.events[GetFunctionName()], i=EventStack.length-1;
do EventStack[i]();
while (i--);
}
MyClass.prototype.setEvent = function (event, callback) {
this.events[event] = [];
this.events[event].push(callback);
this["On"+event] = this.dispatchEvents;
}
MyObject = new MyClass();
MyObject.setEvent ("FirstRun", somecallback);
MyObject.setEvent ("FirstRun", someothercallback);
MyObject.setEvent ("LastRun", yetanothercallback);
The advantage here is the dispatcher can be easily reused and doesn't have to receive the dispatch queue as an argument, instead it comes implicit with the invocation name...
In the end, the general case presented here would be "using the function name as an argument so you don't have to pass it explicitly", and that could be useful in many cases, such as the jquery animate() optional callback, or in timeouts/intervals callbacks, (ie you only pass a funcion NAME).
updated
might be what you're looking for. https://vuejs.org/v2/api/#updated
On my side it was coming from an error in my settings.xml file. I had a bad tag. Just removed it, refreshed and i was good to go.
You need to deal with the optional Rank parameter of UBound
.
Dim arr(1 To 4, 1 To 3) As Variant
Debug.Print UBound(arr, 1) '? returns 4
Debug.Print UBound(arr, 2) '? returns 3
More at: UBound Function (Visual Basic)
A trick I figured out myself was
sudo ls -hal /root/ | sudo dd of=/root/test.out
The HTTP server doesn't send the response header back to the client until you either specify an error or else you start sending data. If you start sending data back to the client, then the server has to send the response head (which contains the status code) first. Once the header has been sent, you can no longer put a status code in the header, obviously.
Here's the usual problem. You start up the page, and send some initial tags (i.e. <head>
). The server then sends those tags to the client, after first sending the HTTP response header with an assumed SUCCESS status. Now you start working on the meat of the page and discover a problem. You can not send an error at this point because the response header, which would contain the error status, has already been sent.
The solution is this: Before you generate any content at all, check if there are going to be any errors. Only then, when you have assured that there will be no problems, can you then start sending content, like the tag.
In your case, it seems like you have a login page that processes a POST request from a form. You probably throw out some initial HTML, then check if the username and password are valid. Instead, you should authenticate the user/password first, before you generate any HTML at all.
For debuggable apps1 on non-rooted devices, you could use following command:
adb shell run-as package.name chmod 666 /data/data/package.name/databases/file
adb pull /data/data/package.name/databases/file
Example:
adb shell run-as com.app chmod 666 /data/data/com.app/databases/data.db
adb pull /data/data/com.app/databases/data.db
Set PATH adb for Enviroment Variables or use cd command to android sdk folder platform-tools.
Example:
cd /folder/android-sdk/platform-tools/
then use above command
1 Note that most apps in Play store are not debuggable since it requires setting the debuggable flag in the manifest.
This blog post gives a nice explanation and some background. Basically, the "permanent generation" (whose size is given by PermSize) is used to store things that the JVM has to allocate space for, but which will not (normally) be garbage-collected (hence "permanent") (+). That means for example loaded classes and static fields.
There is also a FAQ on garbage collection directly from Sun, which answers some questions about the permanent generation. Finally, here's a blog post with a lot of technical detail.
(+) Actually parts of the permanent generation will be GCed, e.g. class objects will be removed when a class is unloaded. But that was uncommon when the permanent generation was introduced into the JVM, hence the name.
A Hash function turns a variable-sized amount of text into a fixed-sized text.
Source: https://en.wikipedia.org/wiki/Hash_function
Hash functions in PHP
A hash turns a string to a hashed string. See below.
HASH:
$str = 'My age is 29';
$hash = hash('sha1', $str);
echo $hash; // OUTPUT: 4d675d9fbefc74a38c89e005f9d776c75d92623e
Passwords are usually stored in their hashed representation instead as readable text. When an end-user wants gain access to an application protected with a password then a password must be given during authentication. When the user submits his password, then the valid authentication system receives the password and hashes this given password. This password hash is compared to the hash known by the system. Access is granted in case of equality.
DEHASH:
SHA1 is a one-way hash. Which means that you can't dehash the hash.
However, you can brute-force the hash. Please see: https://hashkiller.co.uk/sha1-decrypter.aspx.
MD5, is another hash. A MD5 dehasher can be found on this website: https://www.md5online.org/.
To hamper brute-force attacks on hashes a salt can be given.
In php you can use password_hash()
for creating a password hash.
The function password_hash()
automatically creates a salt.
To verify a password on a password hash (with a salt) use password_verify()
.
// Invoke this little script 3 times, and it will give you everytime a new hash
$password = '1234';
$hash = password_hash($password, PASSWORD_DEFAULT);
echo $hash;
// OUTPUT
$2y$10$ADxKiJW/Jn2DZNwpigWZ1ePwQ4il7V0ZB4iPeKj11n.iaDtLrC8bu
$2y$10$H8jRnHDOMsHFMEZdT4Mk4uI4DCW7/YRKjfdcmV3MiA/WdzEvou71u
$2y$10$qhyfIT25jpR63vCGvRbEoewACQZXQJ5glttlb01DmR4ota4L25jaW
One password can be represented by more then one hash.
When you verify the password with different password hashes by using password_verify()
, then the password will be accepted as a valid password.
$password = '1234';
$hash = '$2y$10$ADxKiJW/Jn2DZNwpigWZ1ePwQ4il7V0ZB4iPeKj11n.iaDtLrC8bu';
var_dump( password_verify($password, $hash) );
$hash = '$2y$10$H8jRnHDOMsHFMEZdT4Mk4uI4DCW7/YRKjfdcmV3MiA/WdzEvou71u';
var_dump( password_verify($password, $hash) );
$hash = '$2y$10$qhyfIT25jpR63vCGvRbEoewACQZXQJ5glttlb01DmR4ota4L25jaW';
var_dump( password_verify($password, $hash) );
// OUTPUT
boolean true
boolean true
boolean true
An Encryption function transforms a text into a nonsensical ciphertext by using an encryption key, and vice versa.
Source: https://en.wikipedia.org/wiki/Encryption
Encryption in PHP
Let's dive into some PHP code that handles encryption.
--- The Mcrypt extention ---
ENCRYPT:
$cipher = MCRYPT_RIJNDAEL_128;
$key = 'A_KEY';
$data = 'My age is 29';
$mode = MCRYPT_MODE_ECB;
$encryptedData = mcrypt_encrypt($cipher, $key , $data , $mode);
var_dump($encryptedData);
//OUTPUT:
string '„Ùòyªq³¿ì¼üÀpå' (length=16)
DECRYPT:
$decryptedData = mcrypt_decrypt($cipher, $key , $encryptedData, $mode);
$decryptedData = rtrim($decryptedData, "\0\4"); // Remove the nulls and EOTs at the END
var_dump($decryptedData);
//OUTPUT:
string 'My age is 29' (length=12)
--- The OpenSSL extention ---
The Mcrypt extention was deprecated in 7.1. and removed in php 7.2. The OpenSSL extention should be used in php 7. See the code snippets below:
$key = 'A_KEY';
$data = 'My age is 29';
// ENCRYPT
$encryptedData = openssl_encrypt($data , 'AES-128-CBC', $key, 0, 'IV_init_vector01');
var_dump($encryptedData);
// DECRYPT
$decryptedData = openssl_decrypt($encryptedData, 'AES-128-CBC', $key, 0, 'IV_init_vector01');
var_dump($decryptedData);
//OUTPUT
string '4RJ8+18YkEd7Xk+tAMLz5Q==' (length=24)
string 'My age is 29' (length=12)
Try this
<script type="text/javascript" src="//www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
<script type="text/javascript">
function showRecaptcha() {
Recaptcha.create("YOURPUBLICKEY", 'captchadiv', {
theme: 'red',
callback: Recaptcha.focus_response_field
});
}
</script>
<div id="captchadiv"></div>
If you calll showRecaptcha the captchadiv will be populated with a new recaptcha instance.
I wanna submit my project : https://github.com/flyingangel/argparser
source argparser.sh
parse_args "$@"
Simple as that. The environment will be populated with variables with the same name as the arguments
For those who have a CREATE DATABASE script (as was my case) for the database that is causing this issue you can use the following CREATE script to match the collation:
-- Create Case Sensitive Database
CREATE DATABASE CaseSensitiveDatabase
COLLATE SQL_Latin1_General_CP1_CS_AS -- or any collation you require
GO
USE CaseSensitiveDatabase
GO
SELECT *
FROM sys.types
GO
--rest of your script here
or
-- Create Case In-Sensitive Database
CREATE DATABASE CaseInSensitiveDatabase
COLLATE SQL_Latin1_General_CP1_CI_AS -- or any collation you require
GO
USE CaseInSensitiveDatabase
GO
SELECT *
FROM sys.types
GO
--rest of your script here
This applies the desired collation to all the tables, which was just what I needed. It is ideal to try and keep the collation the same for all databases on a server. Hope this helps.
More info on the following link: SQL SERVER – Creating Database with Different Collation on Server
If you have configured the "difftool" you can use
git difftool revision_1:file_1 revision_2:file_2
Example: Comparing a file from its last commit to its previous commit on the same branch: Assuming that if you are in your project root folder
$git difftool HEAD:src/main/java/com.xyz.test/MyApp.java HEAD^:src/main/java/com.xyz.test/MyApp.java
You should have the following entries in your ~/.gitconfig or in project/.git/config file. Install the p4merge [This is my preferred diff and merge tool]
[merge]
tool = p4merge
keepBackup = false
[diff]
tool = p4merge
keepBackup = false
[difftool "p4merge"]
path = C:/Program Files (x86)/Perforce/p4merge.exe
[mergetool]
keepBackup = false
[difftool]
keepBackup = false
[mergetool "p4merge"]
path = C:/Program Files (x86)/Perforce/p4merge.exe
cmd = p4merge.exe \"$BASE\" \"$LOCAL\" \"$REMOTE\" \"$MERGED\"
Example in scala (useful in sbt file):
import collection.JavaConverters._
import java.net._
def getIpAddress: String = {
val enumeration = NetworkInterface.getNetworkInterfaces.asScala.toSeq
val ipAddresses = enumeration.flatMap(p =>
p.getInetAddresses.asScala.toSeq
)
val address = ipAddresses.find { address =>
val host = address.getHostAddress
host.contains(".") && !address.isLoopbackAddress
}.getOrElse(InetAddress.getLocalHost)
address.getHostAddress
}
Ruby String provides the codepoints
method after 1.9.1.
str = 'hello world'
str.codepoints.to_a
=> [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
str = "????"
str.codepoints.to_a
=> [20320, 22909, 19990, 30028]
function bufferToBinaryString(arrayBuffer){
return String.fromCharCode(...new Uint8Array(arrayBuffer));
}
(async () => console.log(btoa(bufferToBinaryString(await new Response(blob).arrayBuffer()))))();
or
function bufferToBinaryString(arrayBuffer){
return String.fromCharCode(...new Uint8Array(arrayBuffer));
}
new Response(blob).arrayBuffer().then(arr_buf => console.log(btoa(bufferToBinaryString(arr_buf)))))
see Response's constructor, you can turn [blob, buffer source form data, readable stream, etc.]
into Response, which can then be turned into [json, text, array buffer, blob]
with async method/callbacks.
edit: as @Ralph mentioned, turning everything into utf-8 string causes problems (unfortunately Response API doesn't provide a way converting to binary string), so array buffer is use as intermediate instead, which requires two more steps (converting it to byte array THEN to binary string), if you insist on using native btoa
method.
You can create a temporary parent node, and get the innerHTML content of it:
var el = document.createElement("p");
el.appendChild(document.createTextNode("Test"));
var tmp = document.createElement("div");
tmp.appendChild(el);
console.log(tmp.innerHTML); // <p>Test</p>
EDIT: Please see answer below about outerHTML. el.outerHTML should be all that is needed.
Ahh an event listener and change the icon through setIcon() method:
createdMarker.on("dblclick", function(evt) {
var myIcon = L.icon({
iconUrl: 'res/marker-icon-red.png',
shadowUrl: 'res/marker-shadow.png'
});
this.setIcon(myIcon);
});
Unsigned variables can only be positive numbers, because they lack the ability to indicate that they are negative.
This ability is called the 'sign' or 'signing bit'.
A side effect is that without a signing bit, they have one more bit that can be used to represent the number, doubling the maximum number it can represent.
Array slicing like in Python (From the rebash library):
array_slice() {
local __doc__='
Returns a slice of an array (similar to Python).
From the Python documentation:
One way to remember how slices work is to think of the indices as pointing
between elements, with the left edge of the first character numbered 0.
Then the right edge of the last element of an array of length n has
index n, for example:
```
+---+---+---+---+---+---+
| 0 | 1 | 2 | 3 | 4 | 5 |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
```
>>> local a=(0 1 2 3 4 5)
>>> echo $(array.slice 1:-2 "${a[@]}")
1 2 3
>>> local a=(0 1 2 3 4 5)
>>> echo $(array.slice 0:1 "${a[@]}")
0
>>> local a=(0 1 2 3 4 5)
>>> [ -z "$(array.slice 1:1 "${a[@]}")" ] && echo empty
empty
>>> local a=(0 1 2 3 4 5)
>>> [ -z "$(array.slice 2:1 "${a[@]}")" ] && echo empty
empty
>>> local a=(0 1 2 3 4 5)
>>> [ -z "$(array.slice -2:-3 "${a[@]}")" ] && echo empty
empty
>>> [ -z "$(array.slice -2:-2 "${a[@]}")" ] && echo empty
empty
Slice indices have useful defaults; an omitted first index defaults to
zero, an omitted second index defaults to the size of the string being
sliced.
>>> local a=(0 1 2 3 4 5)
>>> # from the beginning to position 2 (excluded)
>>> echo $(array.slice 0:2 "${a[@]}")
>>> echo $(array.slice :2 "${a[@]}")
0 1
0 1
>>> local a=(0 1 2 3 4 5)
>>> # from position 3 (included) to the end
>>> echo $(array.slice 3:"${#a[@]}" "${a[@]}")
>>> echo $(array.slice 3: "${a[@]}")
3 4 5
3 4 5
>>> local a=(0 1 2 3 4 5)
>>> # from the second-last (included) to the end
>>> echo $(array.slice -2:"${#a[@]}" "${a[@]}")
>>> echo $(array.slice -2: "${a[@]}")
4 5
4 5
>>> local a=(0 1 2 3 4 5)
>>> echo $(array.slice -4:-2 "${a[@]}")
2 3
If no range is given, it works like normal array indices.
>>> local a=(0 1 2 3 4 5)
>>> echo $(array.slice -1 "${a[@]}")
5
>>> local a=(0 1 2 3 4 5)
>>> echo $(array.slice -2 "${a[@]}")
4
>>> local a=(0 1 2 3 4 5)
>>> echo $(array.slice 0 "${a[@]}")
0
>>> local a=(0 1 2 3 4 5)
>>> echo $(array.slice 1 "${a[@]}")
1
>>> local a=(0 1 2 3 4 5)
>>> array.slice 6 "${a[@]}"; echo $?
1
>>> local a=(0 1 2 3 4 5)
>>> array.slice -7 "${a[@]}"; echo $?
1
'
local start end array_length length
if [[ $1 == *:* ]]; then
IFS=":"; read -r start end <<<"$1"
shift
array_length="$#"
# defaults
[ -z "$end" ] && end=$array_length
[ -z "$start" ] && start=0
(( start < 0 )) && let "start=(( array_length + start ))"
(( end < 0 )) && let "end=(( array_length + end ))"
else
start="$1"
shift
array_length="$#"
(( start < 0 )) && let "start=(( array_length + start ))"
let "end=(( start + 1 ))"
fi
let "length=(( end - start ))"
(( start < 0 )) && return 1
# check bounds
(( length < 0 )) && return 1
(( start < 0 )) && return 1
(( start >= array_length )) && return 1
# parameters start with $1, so add 1 to $start
let "start=(( start + 1 ))"
echo "${@: $start:$length}"
}
alias array.slice="array_slice"
Here you can use following code as a function:
def drawProgressBar(percent, barLen = 20):
sys.stdout.write("\r")
progress = ""
for i in range(barLen):
if i < int(barLen * percent):
progress += "="
else:
progress += " "
sys.stdout.write("[ %s ] %.2f%%" % (progress, percent * 100))
sys.stdout.flush()
With use of .format:
def drawProgressBar(percent, barLen = 20):
# percent float from 0 to 1.
sys.stdout.write("\r")
sys.stdout.write("[{:<{}}] {:.0f}%".format("=" * int(barLen * percent), barLen, percent * 100))
sys.stdout.flush()
You can used a custom view to do that. With this solution, it's finished the gradient shapes of all colors in your projects:
class GradientView(context: Context, attrs: AttributeSet) : View(context, attrs) {
// Properties
private val paint: Paint = Paint()
private val rect = Rect()
//region Attributes
var start: Int = Color.WHITE
var end: Int = Color.WHITE
//endregion
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
// Update Size
val usableWidth = width - (paddingLeft + paddingRight)
val usableHeight = height - (paddingTop + paddingBottom)
rect.right = usableWidth
rect.bottom = usableHeight
// Update Color
paint.shader = LinearGradient(0f, 0f, width.toFloat(), 0f,
start, end, Shader.TileMode.CLAMP)
// ReDraw
invalidate()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
canvas.drawRect(rect, paint)
}
}
I also create an open source project GradientView with this custom view:
https://github.com/lopspower/GradientView
implementation 'com.mikhaellopez:gradientview:1.1.0'
Viblend WPF themes are free.
If you are saying you wanna pass javascript value from one jsp to another in javascript then use URLRewriting technique to pass javascript variable to next jsp file and access that in next jsp in request object.
Other wise you can't do it.
I had my Apache service not start same as MySQL one. Please follow these steps if none of above tips works :
Note: Ports 80 and 443 must be unused by any program.
If it is in use . Just edit ports. There is a lot of tutorials about that .
DO NOT sum the rounded numbers. You're going to have inaccurate results. The total could be off significantly depending on the number of terms and the distribution of fractional parts.
Display the rounded numbers but sum the actual values. Depending on how you're presenting the numbers, the actual way to do that would vary. That way you get
14 48 10 29 __ 100
Any way you go you're going to have discrepancy. There's no way in your example to show numbers that add up to 100 without "rounding" one value the wrong way (least error would be changing 9.596 to 9)
EDIT
You need to choose between one of the following:
Most of the time when dealing with percentages #3 is the best option because it's more obvious when the total equals 101% than when the individual items don't total to 100, and you keep the individual items accurate. "Rounding" 9.596 to 9 is inaccurate in my opinion.
To explain this I sometimes add a footnote that explains that the individual values are rounded and may not total 100% - anyone that understands rounding should be able to understand that explanation.
I was trying to do the exact same thing, open a text file (a CSV for Pandas actually). Don't want to make a copy of it, just want to open it. The form-WTF has a nice file browser, but then it opens the file and makes a temporary file, which it presents as a memory stream. With a little work under the hood,
form = UploadForm()
if form.validate_on_submit():
filename = secure_filename(form.fileContents.data.filename)
filestream = form.fileContents.data
filestream.seek(0)
ef = pd.read_csv( filestream )
sr = pd.DataFrame(ef)
return render_template('dataframe.html',tables=[sr.to_html(justify='center, classes='table table-bordered table-hover')],titles = [filename], form=form)
Please note that Integer.parseInt throws an NumberFormatException if the passed string doesn't contain a parsable string.
If the value type is already double, then update the value with $set command can not change the value type double to int when using NumberInt() or NumberLong() function. So, to Change the value type, it must update the whole record.
var re = db.data.find({"name": "zero"})
re['value']=NumberInt(0)
db.data.update({"name": "zero"}, re)
You can also set auto completion to open automatically while typing.
Go to Preferences
> Java
> Editor
> Content Assist
and write .abcdefghijklmnopqrstuvwxyz
in the Auto activation triggers for Java
field.
See this question for more details.
The action bar title will, by default, use the label of the current activity, but you can also set it programmatically via ActionBar.setTitle()
.
To implement the "Back" (more precisely, "Up") button functionality you're talking about, read the "Using the App Icon for Navigation" section of the Action Bar developer guide.
Finally, to change the icon, the guide covers that as well. In short, the action bar will display the image supplied in android:icon
in your manifest's application
or activity
element, if there is one. The typical practice is to create an application icon (in all of the various densities you'll need) named ic_launcher.png
, and place it in your drawable-*
directories.
I do it using the following :-
package main
import (
"fmt"
"strings"
)
func main (){
concatenation:= strings.Join([]string{"a","b","c"},"") //where second parameter is a separator.
fmt.Println(concatenation) //abc
}
This example works perfectly in Android
In kotlin you can use a lambda expression for this. The Kotlin Array Constructor definition is:
Array(size: Int, init: (Int) -> T)
Which evaluates to:
skillsSummaryDetailLinesArray = Array(linesLen) {
i: Int -> skillsSummaryDetailLines!!.getString(i)
}
Or:
skillsSummaryDetailLinesArray = Array<String>(linesLen) {
i: Int -> skillsSummaryDetailLines!!.getString(i)
}
In this example the field definition was:
private var skillsSummaryDetailLinesArray: Array<String>? = null
Hope this helps
I got this error when using Visual Studio 2013
with Microsoft SQL Server Management Studio 2016
trying to update database with Entity Framework migrations
The fix was to install Microsoft SQL Server Management Studio 2012 SP1
as Visual Studio 2013 was missing the necessary libraries to connect to the SQL Server database.
I put together this detailed page with all the steps I took.
Let's consider that the environment that one wants to update has the name venv
.
1. Backup venv requirementes (optional)
First of all, backup the requirements of the virtual environment:
pip freeze > requirements.txt
deactivate
#Move the folder to a new one
mv venv venv_old
2. Install Python
Assuming that one doesn't have sudo access, pyenv
is a reliable and fast way to install Python
. For that, one should run
$ curl https://pyenv.run | bash
and then
$ exec $SHELL
If, when one tries to update pyenv
pyenv update
And one gets the error
bash: pyenv: command not found
It is because pyenv path wasn't exported to .bashrc. It can be solved by executing the following commands:
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n eval "$(pyenv init -)"\nfi' >> ~/.bashrc
Then restart the shell
exec "$SHELL"
Now one should install the Python version that one wants. Let's say version 3.8.3
pyenv install 3.8.3
One can confirm if it was properly installed by running
pyenv versions
The output should be the location and the versions (in this case 3.8.3)
3. Create the new virtual environment
Finally, with the new Python version installed, create a new virtual environment (let's call it venv
)
python3.8 -m venv venv
Activate it
source venv/bin/activate
and install the requirements
pip install -r requirements.txt
Now one should be up and running with a new environment.
You're on the right track. Here's a corrected version:
char str[10];
int n;
printf("type a string: ");
scanf("%s %d", str, &n);
printf("%s\n", str);
printf("%d\n", n);
Let's talk through the changes:
n
) to store your number inscanf
to read in first a string and then a number (%d
means number, as you already knew from your printf
That's pretty much all there is to it. Your code is a little bit dangerous, still, because any user input that's longer than 9 characters will overflow str
and start trampling your stack.
As far as I know you can use all mentioned technologies separately or together. It's up to you. I think you look at the problem from the wrong angle. Material Design is just the way particular elements of the page are designed, behave and put together. Material Design provides great UI/UX, but it relies on the graphic layout (HTML/CSS) rather than JS (events, interactions).
On the other hand, AngularJS and Bootstrap are front-end frameworks that can speed up your development by saving you from writing tons of code. For example, you can build web app utilizing AngularJS, but without Material Design. Or You can build simple HTML5 web page with Material Design without AngularJS or Bootstrap. Finally you can build web app that uses AngularJS with Bootstrap and with Material Design. This is the best scenario. All technologies support each other.
You can check awesome material design components for AngularJS:
https://material.angularjs.org
Short answer: AngularJS ("jqlite") doesn't support this. Include jQuery on your page (before including Angular), and it should work. See https://groups.google.com/d/topic/angular/H4haaMePJU0/discussion
Open a terminal and type:
mongo
The below command should show the listed databases:
show dbs
/* the <dbname> is the database you'd like to drop */
use <dbname>
/* the below command will delete the database */
db.dropDatabase()
The below should be the output in the terminal:
{
"dropped": "<dbname>",
"ok": 1
}
I will make this quick and easy to understand!
Instead of maxlength for type='number'
(maxlength is meant to define the maximum amount of letters for a string in a text
type), use min=''
and max=''
.
Cheers
If you choose not to use String.format, the other option is the + binary operator
String str = "Step " + a + " of " + b;
This is the equivalent of
new StringBuilder("Step ").append(String.valueOf(1)).append(" of ").append(String.valueOf(2));
Whichever you use is your choice. StringBuilder is faster, but the speed difference is marginal. I prefer to use the +
operator (which does a StringBuilder.append(String.valueOf(X)))
and find it easier to read.
You can use a much simpler formula. I just created a new workbook to test it.
Column A = Date1 | Column B = Date2 | Column C = Date3
Highlight Column A and enter the conditional formatting formula:
=AND(A1>B1,A1<C1)
You should set layout first by syntax pnlButton.setLayout()
, and then choose the most suitable layout which u want. Ex: pnlButton.setLayout(new FlowLayout(FlowLayout.LEADING, 5, 5));
. And then, take that JButton into JPanel.
Assuming that your button is in a form, you are not preventing the default behaviour of the button click from happening i.e. Your AJAX call is made in addition to the form submission; what you're very likely seeing is one of
So you should prevent the default behaviour of the button click
$('#btnSave').click(function (e) {
// prevent the default event behaviour
e.preventDefault();
$.ajax({
url: "/Home/SaveDetailedInfo",
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
// perform your save call here
if (data.status == "Success") {
alert("Done");
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error has occured!!!");
}
});
});
//*[text()='ABC']
returns
<street>ABC</street>
<comment>BLAH BLAH BLAH <br><br>ABC</comment>
In CurrentGame
component you need to change initial state because you are trying use loop for participants
but this property is undefined
that's why you get error.,
getInitialState: function(){
return {
data: {
participants: []
}
};
},
also, as player
in .map
is Object
you should get properties from it
this.props.data.participants.map(function(player) {
return <li key={player.championId}>{player.summonerName}</li>
// -------------------^^^^^^^^^^^---------^^^^^^^^^^^^^^
})
If you have recently installed or updated the Microsoft.CodeDom.Providers.DotNetCompilerPlatform
package, double-check that the versions of that package referenced in your project point to the correct, and same, version of that package:
In ProjectName.csproj
, ensure that an <Import>
tag for Microsoft.CodeDom.Providers.DotNetCompilerPlatform
is present and points to the correct version.
In ProjectName.csproj
, ensure that a <Reference>
tag for Microsoft.CodeDom.Providers.DotNetCompilerPlatform
is present, and points to the correct version, both in the Include
attribute and the child <HintPath>
.
In that project's web.config
, ensure that the <system.codedom>
tag is present, and that its child <compiler>
tags have the same version in their type
attribute.
For some reason, in my case an upgrade of this package from 1.0.5 to 1.0.8 caused the <Reference>
tag in the.csproj
to have its Include
pointing to the old version 1.0.5.0 (which I had deleted after upgrading the package), but everything else was pointing to the new and correct version 1.0.8.0.
You must use
<dd> </dd>
in the html code.
<dd>A free, open source, cross-platform,graphical web browser developed by theMozilla Corporation and hundreds of volunteers.</dd>
----------------------------------
Firefox
A free, open source, cross-platform, graphical web browser developed by the Mozilla
Corporation and hundreds of volunteers.
Here is a query, you can run it in SQL Developer (or SQL*Plus):
SELECT DS.TABLESPACE_NAME, SEGMENT_NAME, ROUND(SUM(DS.BYTES) / (1024 * 1024)) AS MB
FROM DBA_SEGMENTS DS
WHERE SEGMENT_NAME IN (SELECT TABLE_NAME FROM DBA_TABLES)
GROUP BY DS.TABLESPACE_NAME,
SEGMENT_NAME;
If you can't import MockMultipartFile
using
import org.springframework.mock.web.MockMultipartFile;
you need to add the below dependency into pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
I had a span that would create a popup. If I used "click touchstart" it would trigger parts of the popup during the touchend. I fixed this by making the span "click touchend".
Use reindex
to get all columns you need. It'll preserve the ones that are already there and put in empty columns otherwise.
p = p.reindex(columns=['1Sun', '2Mon', '3Tue', '4Wed', '5Thu', '6Fri', '7Sat'])
So, your entire code example should look like this:
df = pd.read_csv(CsvFileName)
p = df.pivot_table(index=['Hour'], columns='DOW', values='Changes', aggfunc=np.mean).round(0)
p.fillna(0, inplace=True)
columns = ["1Sun", "2Mon", "3Tue", "4Wed", "5Thu", "6Fri", "7Sat"]
p = p.reindex(columns=columns)
p[columns] = p[columns].astype(int)
Here's an example:
#Create a data frame
> d<- data.frame(a=1:3, b=2:4)
> d
a b
1 1 2
2 2 3
3 3 4
#currently, there are no levels in the `a` column, since it's numeric as you point out.
> levels(d$a)
NULL
#Convert that column to a factor
> d$a <- factor(d$a)
> d
a b
1 1 2
2 2 3
3 3 4
#Now it has levels.
> levels(d$a)
[1] "1" "2" "3"
You can also handle this when reading in your data. See the colClasses
and stringsAsFactors
parameters in e.g. readCSV()
.
Note that, computationally, factoring such columns won't help you much, and may actually slow down your program (albeit negligibly). Using a factor will require that all values are mapped to IDs behind the scenes, so any print of your data.frame requires a lookup on those levels -- an extra step which takes time.
Factors are great when storing strings which you don't want to store repeatedly, but would rather reference by their ID. Consider storing a more friendly name in such columns to fully benefit from factors.
It seems the doc evolved.
One should now use :
$("#datetimepicker1").data("DateTimePicker").date()
.
NB : Doing so return a Moment object, not a Date object
This is built from Álvaro González's answer and How to increase IDE memory limit in IntelliJ IDEA on Mac?
Go to Help > Edit Custom Properties
Add:
idea.max.intellisense.filesize=999999
Restart the IDE.
The primary difference between the two is the following
typeof Reference: http://www.delorie.com/gnu/docs/gcc/gcc_36.html
typeid Reference: https://en.wikipedia.org/wiki/Typeid
You can do:
import matplotlib.pyplot as plt
x = [1,2,3,4,5]
y = [2,1,3,6,7]
plt.plot(x, y, style='.-')
plt.show()
This will return a graph with the data points marked with a dot
When you got few list but you don't know how many exactly, use this:
listsOfProducts
contains few lists filled with objects.
List<Product> productListMerged = new List<Product>();
listsOfProducts.ForEach(q => q.ForEach(e => productListMerged.Add(e)));
Use this query to create the new table with the values from existing table
CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name;
Now you can get all the values from existing table into newly created table.
If you want to keep the heredoc indented for readability:
$ perl -pe 's/^\s*//' << EOF
line 1
line 2
EOF
The built-in method for supporting indented heredoc in Bash only supports leading tabs, not spaces.
Perl can be replaced with awk to save a few characters, but the Perl one is probably easier to remember if you know basic regular expressions.
Instead of storing the output of grep in a variable and then checking whether the variable is empty, you can do this:
if grep -q "poet" $file_name
then
echo "poet was found in $file_name"
fi
============
Here are some commonly used tests:
-d FILE
FILE exists and is a directory
-e FILE
FILE exists
-f FILE
FILE exists and is a regular file
-h FILE
FILE exists and is a symbolic link (same as -L)
-r FILE
FILE exists and is readable
-s FILE
FILE exists and has a size greater than zero
-w FILE
FILE exists and is writable
-x FILE
FILE exists and is executable
-z STRING
the length of STRING is zero
Example:
if [ -e "$file_name" ] && [ ! -z "$used_var" ]
then
echo "$file_name exists and $used_var is not empty"
fi
When you use the -m
option putty does not allocate a tty, it runs the command and quits. If you want to run an interactive script (such as a sql client), you need to tell it to allocate a tty with -t
, see 3.8.3.12 -t and -T: control pseudo-terminal allocation
. You'll avoid keeping a script on the server, as well as having to invoke it once you're connected.
Here's what I'm using to connect to mysql from a batch file:
#mysql.bat
start putty -t -load "sessionname" -l username -pw password -m c:\mysql.sh
#mysql.sh
mysql -h localhost -u username --password="foo" mydb
https://superuser.com/questions/587629/putty-run-a-remote-command-after-login-keep-the-shell-running
Your program has to run with Administrative Rights. You can't do this automatically with code, but you can request the user (in code) to elevate the rights of your program while it's running. There's a wiki on how to do this. Alternatively, any program can be run as administrator by right-clicking its icon and clicking "Run as administrator".
However, I wouldn't suggest doing this. It would be better to use something like this:
Environment.GetFolderPath(SpecialFolder.ApplicationData);
to get the AppData Folder path and create a folder there for your app. Then put the temp files there.
A URL of the form https://github.com/<owner>/<project>/commit/<hash>
will show you the changes introduced in that commit. For example here's a recent bugfix I made to one of my projects on GitHub:
https://github.com/jerith666/git-graph/commit/35e32b6a00dec02ae7d7c45c6b7106779a124685
You can also shorten the hash to any unique prefix, like so:
https://github.com/jerith666/git-graph/commit/35e32b
I know you just asked about GitHub, but for completeness: If you have the repository checked out, from the command line, you can achieve basically the same thing with either of these commands (unique prefixes work here too):
git show 35e32b6a00dec02ae7d7c45c6b7106779a124685
git log -p -1 35e32b6a00dec02ae7d7c45c6b7106779a124685
Note: If you shorten the commit hash too far, the command line gives you a helpful disambiguation message, but GitHub will just return a 404.
getParameter
- Is used for getting the information you need from the Client's HTML page
getAttribute
- This is used for getting the parameters set previously in another or the same JSP or Servlet page.
Basically, if you are forwarding or just going from one jsp/servlet to another one, there is no way to have the information you want unless you choose to put them in an Object and use the set-attribute to store in a Session variable.
Using getAttribute, you can retrieve the Session variable.
If you are lazy, and have a lot of RAM, create a sieve of Eratosthenes which is practically a giant array from which you kicked all numbers that are not prime. From then on every prime "probability" test will be super quick. The upper limit for this solution for fast results is the amount of you RAM. The upper limit for this solution for superslow results is your hard disk's capacity.
Nav.js comp inside components folder
export {Nav}
index.js in component folder
export {Nav} from './Nav';
export {Another} from './Another';
import anywhere
import {Nav, Another} from './components'
You could try letting the stream throw an exception on failure:
std::ifstream f;
//prepare f to throw if failbit gets set
std::ios_base::iostate exceptionMask = f.exceptions() | std::ios::failbit;
f.exceptions(exceptionMask);
try {
f.open(fileName);
}
catch (std::ios_base::failure& e) {
std::cerr << e.what() << '\n';
}
e.what()
, however, does not seem to be very helpful:
strerror(errno)
gives "No such file or directory."If e.what()
does not work for you (I don't know what it will tell you about the error, since that's not standardized), try using std::make_error_condition
(C++11 only):
catch (std::ios_base::failure& e) {
if ( e.code() == std::make_error_condition(std::io_errc::stream) )
std::cerr << "Stream error!\n";
else
std::cerr << "Unknown failure opening file.\n";
}
And for Touch devices like IPAD and IPHONE we can use following code
$(document).on('touchstart', function (event) {
var container = $("YOUR CONTAINER SELECTOR");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.hide();
}
});
Since bash
5.0 (released on 7 Jan 2019) you can use the built-in variable EPOCHSECONDS
.
$ echo $EPOCHSECONDS
1547624774
There is also EPOCHREALTIME
which includes fractions of seconds.
$ echo $EPOCHREALTIME
1547624774.371215
EPOCHREALTIME
can be converted to micro-seconds (µs) by removing the decimal point. This might be of interest when using bash
's built-in arithmetic (( expression ))
which can only handle integers.
$ echo ${EPOCHREALTIME/./}
1547624774371215
In all examples from above the printed time values are equal for better readability. In reality the time values would differ since each command takes a small amount of time to be executed.
The two classes are functionally equivalent, except that System.Timers.Timer
has an option to invoke all its timer expiration callbacks through ISynchronizeInvoke by setting SynchronizingObject. Otherwise, both timers invoke expiration callbacks on thread pool threads.
When you drag a System.Timers.Timer
onto a Windows Forms design surface, Visual Studio sets SynchronizingObject to the form object, which causes all expiration callbacks to be called on the UI thread.
I was having this problem, when I was calling a soap method to obtain my data, and then return a json string, when I tried to do json_decode I just keep getting null.
Since I was using nusoap to do the soap call I tried to just return json string and now I could do a json_decode, since I really neaded to get my data with a SOAP call, what I did was add ob_start() before include nusoap, id did my call genereate json string, and then before returning my json string I did ob_end_clean(), and GOT MY PROBLEM FIXED :)
EXAMPLE
//HRT - SIGNED
//20130116
//verifica se um num assoc deco é valido
ob_start();
require('/nusoap.php');
$aResponse['SimpleIsMemberResult']['IsMember'] = FALSE;
if(!empty($iNumAssociadoTmp))
{
try
{
$client = new soapclientNusoap(PartnerService.svc?wsdl',
array(
// OPTS
'trace' => 0,
'exceptions' => false,
'cache_wsdl' => WSDL_CACHE_NONE
)
);
//MENSAGEM A ENVIAR
$sMensagem1 = '
<SimpleIsMember>
<request>
<CheckDigit>'.$iCheckDigitAssociado.'</CheckDigit>
<Country>Portugal</Country>
<MemberNumber">'.$iNumAssociadoDeco.'</MemberNumber>
</request>
</SimpleIsMember>';
$aResponse = $client->call('SimpleIsMember',$sMensagem1);
$aData = array('dados'=>$aResponse->xpto, 'success'=>$aResponse->example);
}
}
ob_end_clean();
return json_encode($aData);
Just created this:
https://gist.github.com/3854049
//Setter
Storage.setObj('users.albums.sexPistols',"blah");
Storage.setObj('users.albums.sexPistols',{ sid : "My Way", nancy : "Bitch" });
Storage.setObj('users.albums.sexPistols.sid',"Other songs");
//Getters
Storage.getObj('users');
Storage.getObj('users.albums');
Storage.getObj('users.albums.sexPistols');
Storage.getObj('users.albums.sexPistols.sid');
Storage.getObj('users.albums.sexPistols.nancy');
Yes, there is another way to do this!
Step 1: Register a custom Blade directive:
<?php // code in app/Providers/AppServiceProvider.php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Blade; // <-- This is important! Without it you'll get an exception.
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
// Make a custom blade directive:
Blade::directive('shout', function ($string) {
return trim(strtoupper($string), '(\'\')');
});
// And another one for good measure:
Blade::directive('customLink', function () {
return '<a href="#">Custom Link</a>';
});
}
...
Step 2: Use your custom Blade directive:
<!-- // code in resources/views/view.blade.php -->
@shout('this is my custom blade directive!!')
<br />
@customLink
Outputs:
THIS IS MY CUSTOM BLADE DIRECTIVE!!
Custom Link
Source: https://laravel.com/docs/5.1/blade#extending-blade
Additional Reading: https://mattstauffer.co/blog/custom-conditionals-with-laravels-blade-directives
If you want to learn how to best make custom classes that you can use anywhere, see Custom Classes in Laravel 5, the Easy Way
For two or multiple arrays, this simple and clean utility method can be used:
/**
* Append the given byte arrays to one big array
*
* @param arrays The arrays to append
* @return The complete array containing the appended data
*/
public static final byte[] append(final byte[]... arrays) {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
if (arrays != null) {
for (final byte[] array : arrays) {
if (array != null) {
out.write(array, 0, array.length);
}
}
}
return out.toByteArray();
}
As was pointed out, a semaphore with a count of one is the same thing as a 'binary' semaphore which is the same thing as a mutex.
The main things I've seen semaphores with a count greater than one used for is producer/consumer situations in which you have a queue of a certain fixed size.
You have two semaphores then. The first semaphore is initially set to be the number of items in the queue and the second semaphore is set to 0. The producer does a P operation on the first semaphore, adds to the queue. and does a V operation on the second. The consumer does a P operation on the second semaphore, removes from the queue, and then does a V operation on the first.
In this way the producer is blocked whenever it fills the queue, and the consumer is blocked whenever the queue is empty.
using LINQ and Lamba, i wanted to return two field values and assign it to single entity object field;
as Name = Fname + " " + LName;
See my below code which is working as expected; hope this is useful;
Myentity objMyEntity = new Myentity
{
id = obj.Id,
Name = contxt.Vendors.Where(v => v.PQS_ID == obj.Id).Select(v=> new { contact = v.Fname + " " + v.LName}).Single().contact
}
no need to declare the 'contact'
Here's a function to pretty up your json: pretty_json
The easiest way to right pad a string with spaces (without them being trimmed) is to simply cast the string as CHAR(length). MSSQL will sometimes trim whitespace from VARCHAR (because it is a VARiable-length data type). Since CHAR is a fixed length datatype, SQL Server will never trim the trailing spaces, and will automatically pad strings that are shorter than its length with spaces. Try the following code snippet for example.
SELECT CAST('Test' AS CHAR(20))
This returns the value 'Test '
.
As of Git v2.23.0 (August 2019), git switch
is preferred over git checkout
when you’re simply switching branches/tags. I’m guessing they did this since git checkout
had two functions: for switching branches and for restoring files. So in v2.23.0, they added two new commands, git switch
, and git restore
, to separate those concerns. I would predict at some point in the future, git checkout
will be deprecated.
To switch to a normal branch, use git switch <branch-name>
. To switch to a commit-like object, including single commits and tags, use git switch --detach <commitish>
, where <commitish>
is the tag name or commit number.
The --detach
option forces you to recognize that you’re in a mode of “inspection and discardable experiments”. To create a new branch from the commitish you’re switching to, use git switch -c <new-branch> <start-point>
.
Chrome Developer Tools has an Audits tab which can show unused CSS selectors.
Run an audit, then, under Web Page Performance see Remove unused CSS rules
1 << ADDR_WIDTH
means 1 will be shifted 8 bits to the left and will be assigned as the value for RAM_DEPTH
.
In addition, 1 << ADDR_WIDTH
also means 2^ADDR_WIDTH.
Given ADDR_WIDTH = 8
, then 2^8 = 256
and that will be the value for RAM_DEPTH
As you noticed, these are Makefile {macros or variables}, not compiler options. They implement a set of conventions. (Macros is an old name for them, still used by some. GNU make doc calls them variables.)
The only reason that the names matter is the default make rules, visible via make -p
, which use some of them.
If you write all your own rules, you get to pick all your own macro names.
In a vanilla gnu make, there's no such thing as CCFLAGS. There are CFLAGS
, CPPFLAGS
, and CXXFLAGS
. CFLAGS
for the C compiler, CXXFLAGS
for C++, and CPPFLAGS
for both.
Why is CPPFLAGS
in both? Conventionally, it's the home of preprocessor flags (-D
, -U
) and both c and c++ use them. Now, the assumption that everyone wants the same define environment for c and c++ is perhaps questionable, but traditional.
P.S. As noted by James Moore, some projects use CPPFLAGS for flags to the C++ compiler, not flags to the C preprocessor. The Android NDK, for one huge example.
Another way:
x=$'Some\nstring'
readarray -t y <<<"$x"
Or, if you don't have bash 4, the bash 3.2 equivalent:
IFS=$'\n' read -rd '' -a y <<<"$x"
You can also do it the way you were initially trying to use:
y=(${x//$'\n'/ })
This, however, will not function correctly if your string already contains spaces, such as 'line 1\nline 2'
. To make it work, you need to restrict the word separator before parsing it:
IFS=$'\n' y=(${x//$'\n'/ })
...and then, since you are changing the separator, you don't need to convert the \n
to space
anymore, so you can simplify it to:
IFS=$'\n' y=($x)
This approach will function unless $x
contains a matching globbing pattern (such as "*
") - in which case it will be replaced by the matched file name(s). The read
/readarray
methods require newer bash versions, but work in all cases.
Even though your JDK in eclipse is 1.7, you need to make sure eclipse compilance level also set to 1.7. You can check compilance level--> Window-->Preferences--> Java--Compiler--compilance level.
Unsupported major minor error happens in cases where compilance level doesn't match with runtime.
You can try this for svg vector drawable
DrawableCompat.setTint(
DrawableCompat.wrap(myImageView.getDrawable()),
ContextCompat.getColor(context, R.color.another_nice_color)
);
You can easily center multiple things by creating a chain. It works both vertically and horizontally
Link to official documentation about chains
Edit to answer comment :
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="@+id/first_score"
android:layout_width="60dp"
android:layout_height="wrap_content"
android:text="10"
app:layout_constraintEnd_toStartOf="@+id/second_score"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/second_score"
app:layout_constraintBottom_toTopOf="@+id/subtitle"
app:layout_constraintHorizontal_chainStyle="spread"
app:layout_constraintVertical_chainStyle="packed"
android:gravity="center"
/>
<TextView
android:id="@+id/subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Subtitle"
app:layout_constraintTop_toBottomOf="@+id/first_score"
app:layout_constraintBottom_toBottomOf="@+id/second_score"
app:layout_constraintStart_toStartOf="@id/first_score"
app:layout_constraintEnd_toEndOf="@id/first_score"
/>
<TextView
android:id="@+id/second_score"
android:layout_width="60dp"
android:layout_height="120sp"
android:text="243"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/thrid_score"
app:layout_constraintStart_toEndOf="@id/first_score"
app:layout_constraintTop_toTopOf="parent"
android:gravity="center"
/>
<TextView
android:id="@+id/thrid_score"
android:layout_width="60dp"
android:layout_height="wrap_content"
android:text="3200"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@id/second_score"
app:layout_constraintTop_toTopOf="@id/second_score"
app:layout_constraintBottom_toBottomOf="@id/second_score"
android:gravity="center"
/>
</android.support.constraint.ConstraintLayout>
You have the horizontal chain : first_score <=> second_score <=> third_score
.
second_score
is centered vertically. The other scores are centered vertically according to it.
You can definitely create a vertical chain first_score <=> subtitle
and center it according to second_score
I solved this using the optional()
helper. Using the example here it would be:
{{ optional($usersType) }}
A more complicated example would be if, like me, say you are trying to access a property of a null object (ie. $users->type
) in a view that is using old()
helper.
value="{{ old('type', optional($users)->type }}"
Important to note that the brackets go around the object variable and not the whole thing if trying to access a property of the object.
Another solution that wasn't mentioned:
var parent = document.querySelector('.parent');
if (parent.querySelector('.child') !== null) {
// .. it's a child
}
It doesn't matter whether the element is a direct child, it will work at any depth.
Alternatively, using the .contains()
method:
var parent = document.querySelector('.parent'),
child = document.querySelector('.child');
if (parent.contains(child)) {
// .. it's a child
}
#!/usr/bin/python
import re
strs = "how^ much for{} the maple syrup? $20.99? That's[] ricidulous!!!"
print strs
nstr = re.sub(r'[?|$|.|!|a|b]',r' ',strs)#i have taken special character to remove but any #character can be added here
print nstr
nestr = re.sub(r'[^a-zA-Z0-9 ]',r'',nstr)#for removing special character
print nestr
In this case that you know that you have all items in the first place on array you can parse the string to JArray and then parse the first item using JObject.Parse
var jsonArrayString = @"
[
{
""country"": ""India"",
""city"": ""Mall Road, Gurgaon"",
},
{
""country"": ""India"",
""city"": ""Mall Road, Kanpur"",
}
]";
JArray jsonArray = JArray.Parse(jsonArrayString);
dynamic data = JObject.Parse(jsonArray[0].ToString());
I just found a solution for jaxrs-ri-2.16 - simply use
String output = response.readEntity(String.class)
this delivers the content as expected.
#!/bin/bash
file_location=/home/test/$1.json
if [ -e $policy ]; then
echo "File $1.json already exists!"
else
cat > $file_location <<EOF
{
"contact": {
"name": "xyz",
"phonenumber": "xxx-xxx-xxxx"
}
}
EOF
fi
This code checks if the given JSON file of the user is present in test home directory or not. If it's not present it will create it with the content. You can modify the file location and content according to your needs.
I got this error after I changed my model (code first) as follows:
public DateTime? DateCreated
to
public DateTime DateCreated
Present rows with null-value in DateCreated caused this error. So I had to use SQL UPDATE Statement manually for initializing the field with a standard value.
Another solution could be a specifying of the default value for the filed.
Actually you dont need to call document.getElementById()
function to get access to your div
.
You can use this object
directly by id
:
text = test.textContent || test.innerText;
alert(text);
There is a, perhaps subtle, but important misconception in a number these answers. I thought I'd add my answer to clear it up.
What is
HEAD
?
HEAD
is a symbolic reference pointing to wherever you are in your commit history. It follows you wherever you go, whatever you do, like a shadow. If you make a commit, HEAD
will move. If you checkout something, HEAD
will move. Whatever you do, if you have moved somewhere new in your commit history, HEAD
has moved along with you. To address one common misconception: you cannot detach yourself from HEAD
. That is not what a detached HEAD state is. If you ever find yourself thinking: "oh no, i'm in detached HEAD state! I've lost my HEAD!" Remember, it's your HEAD. HEAD is you. You haven't detached from the HEAD, you and your HEAD have detached from something else.
HEAD
can point to a commit, yes, but typically it does not. Let me say that again. Typically HEAD
does not point to a commit. It points to a branch reference. It is attached to that branch, and when you do certain things (e.g., commit
or reset
), the attached branch will move along with HEAD
. You can see what it is pointing to by looking under the hood.
cat .git/HEAD
Normally you'll get something like this:
ref: refs/heads/master
Sometimes you'll get something like this:
a3c485d9688e3c6bc14b06ca1529f0e78edd3f86
That's what happens when HEAD
points directly to a commit. This is called a detached HEAD, because HEAD
is pointing to something other than a branch reference. If you make a commit in this state, master
, no longer being attached to HEAD
, will no longer move along with you. It does not matter where that commit is. You could be on the same commit as your master branch, but if HEAD
is pointing to the commit rather than the branch, it is detached and a new commit will not be associated with a branch reference.
You can look at this graphically if you try the following exercise. From a git repository, run this. You'll get something slightly different, but they key bits will be there. When it is time to checkout the commit directly, just use whatever abbreviated hash you get from the first output (here it is a3c485d
).
git checkout master
git log --pretty=format:"%h: %d" -1
# a3c485d: (HEAD -> master)
git checkout a3c485d -q # (-q is for dramatic effect)
git log --pretty=format:"%h: %d" -1
# a3c485d: (HEAD, master)
OK, so there is a small difference in the output here. Checking out the commit directly (instead of the branch) gives us a comma instead of an arrow. What do you think, are we in a detached HEAD state? HEAD is still referring to a specific revision that is associated with a branch name. We're still on the master branch, aren't we?
Now try:
git status
# HEAD detached at a3c485d
Nope. We're in 'detached HEAD' state.
You can see the same representation of (HEAD -> branch)
vs. (HEAD, branch)
with git log -1
.
HEAD
is you. It points to whatever you checked out, wherever you are. Typically that is not a commit, it is a branch. If HEAD
does point to a commit (or tag), even if it's the same commit (or tag) that a branch also points to, you (and HEAD
) have been detached from that branch. Since you don't have a branch attached to you, the branch won't follow along with you as you make new commits. HEAD
, however, will.
After you do express in your terminal, then do
npm install
To install all the dependencies.
Then you can do node app to run the server.
DotLiquid is another option. You specify values from a class model as {{ user.name }}
and then at runtime you provide the data in that class, and the template with the markup, and it will merge the values in for you. It is similar to using the Razor templating engine in many ways. It supports more complex things like loops and various function like ToUpper. The nice thing is these are "safe" so that user's who create the templates can't crash your system or write unsafe code like you would in razor: http://dotliquidmarkup.org/try-online
This happened for me when I was trying to stash my changes, but then my changes had conflicts with my branch's current state.
So I did git reset --mixed
and then resolved the git conflict and stashed again.
Monitor your Cached Files Size (you can use apc.php from apc pecl package) and increase apc.shm_size according to your needs.
This solves the problem.
I am using chrome, Linux Mint; and for commenting and dis-commenting bundle of lines:
Ctrl + /
Just to be clear, TRIM by default only remove spaces (not all whitespaces). Here is the doc: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_trim
$time = 30 * 60; //30 minutes
$start_time = date('Y-m-d h:i:s', time() - $time);
$end_time = date('Y-m-d h:i:s', time() + $time);
There's nothing in the stdlib that will do it for you without creating tuple garbage, but it's not too hard to write your own. Unfortunately I've never bothered to figure out how to do the proper CanBuildFrom implicit raindance to make such things generic in the type of collection they're applied to, but if it's possible, I'm sure someone will enlighten us. :)
def foreachWithIndex[A](as: Traversable[A])(f: (Int,A) => Unit) {
var i = 0
for (a <- as) {
f(i, a)
i += 1
}
}
def mapWithIndex[A,B](in: List[A])(f: (Int,A) => B): List[B] = {
def mapWithIndex0(in: List[A], gotSoFar: List[B], i: Int): List[B] = {
in match {
case Nil => gotSoFar.reverse
case one :: more => mapWithIndex0(more, f(i, one) :: gotSoFar, i+1)
}
}
mapWithIndex0(in, Nil, 0)
}
// Tests....
@Test
def testForeachWithIndex() {
var out = List[Int]()
ScalaUtils.foreachWithIndex(List(1,2,3,4)) { (i, num) =>
out :+= i * num
}
assertEquals(List(0,2,6,12),out)
}
@Test
def testMapWithIndex() {
val out = ScalaUtils.mapWithIndex(List(4,3,2,1)) { (i, num) =>
i * num
}
assertEquals(List(0,3,4,3),out)
}
I use com0com - With Signed Driver, on windows 7 x64 to emulate COM3 AND COM4 as a pair.
Then i use COM Dataport Emulator to recieve from COM4.
Then i open COM3 with the app im developping (c#) and send data to COM3.
The data sent thru COM3 is received by COM4 and shown by 'COM Dataport Emulator' who can also send back a response (not automated).
So with this 2 great programs i managed to emulate Serial RS-232 comunication.
Hope it helps.
Both programs are free!!!!!
You can use http://pingdom.com/ to check your app; if done every minute or so, heroku won't idle your app and won't need to spin-up.
Estimated sanjan:
The idea behind Dijkstra's Algorithm is to explore all the nodes of the graph in an ordered way. The algorithm stores a priority queue where the nodes are ordered according to the cost from the start, and in each iteration of the algorithm the following operations are performed:
It's true that the algorithm calculates the cost of the path between the start (A in your case) and all the rest of the nodes, but you can stop the exploration of the algorithm when it reaches the goal (Z in your example). At this point you know the cost between A and Z, and the path connecting them.
I recommend you to use a library which implements this algorithm instead of coding your own. In Java, you might take a look to the Hipster library, which has a very friendly way to generate the graph and start using the search algorithms.
Here you have an example of how to define the graph and start using Dijstra with Hipster.
// Create a simple weighted directed graph with Hipster where
// vertices are Strings and edge values are just doubles
HipsterDirectedGraph<String,Double> graph = GraphBuilder.create()
.connect("A").to("B").withEdge(4d)
.connect("A").to("C").withEdge(2d)
.connect("B").to("C").withEdge(5d)
.connect("B").to("D").withEdge(10d)
.connect("C").to("E").withEdge(3d)
.connect("D").to("F").withEdge(11d)
.connect("E").to("D").withEdge(4d)
.buildDirectedGraph();
// Create the search problem. For graph problems, just use
// the GraphSearchProblem util class to generate the problem with ease.
SearchProblem p = GraphSearchProblem
.startingFrom("A")
.in(graph)
.takeCostsFromEdges()
.build();
// Search the shortest path from "A" to "F"
System.out.println(Hipster.createDijkstra(p).search("F"));
You only have to substitute the definition of the graph for your own, and then instantiate the algorithm as in the example.
I hope this helps!
You have — essentially — no use for __slots__
.
For the time when you think you might need __slots__
, you actually want to use Lightweight or Flyweight design patterns. These are cases when you no longer want to use purely Python objects. Instead, you want a Python object-like wrapper around an array, struct, or numpy array.
class Flyweight(object):
def get(self, theData, index):
return theData[index]
def set(self, theData, index, value):
theData[index]= value
The class-like wrapper has no attributes — it just provides methods that act on the underlying data. The methods can be reduced to class methods. Indeed, it could be reduced to just functions operating on the underlying array of data.
See here: Git doesn't clone all branches on subsequent clones?
If you really want this by pulling branches instead of push --mirror
, you can have a look here:
"fetch --all" in a git bare repository doesn't synchronize local branches to the remote ones
This answer provides detailed steps on how to achieve that relatively easily:
If you're ever dynamically generating page content or loading content through AJAX, the following example is really the way you should go:
body
of the document, so regardless of what elements are added, moved, removed and re-added, all descendants of body
matching the selector specified will retain proper binding.The Code:
// Define the element we wish to bind to.
var bind_to = ':input';
// Prevent double-binding.
$(document.body).off('change', bind_to);
// Bind the event to all body descendants matching the "bind_to" selector.
$(document.body).on('change keyup', bind_to, function(event) {
alert('something happened!');
});
Please notice! I'm making use of $.on()
and $.off()
rather than other methods for several reasons:
$.live()
and $.die()
are deprecated and have been omitted from more recent versions of jQuery.$.change()
and $.keyup()
separately, or pass the same function declaration to each function called; Duplicating logic... Which is absolutely unacceptable.$.bind()
does not dynamically bind to elements as they are created. Therefore if you bind to :input
and then add an input to the DOM, that bind method is not attached to the new input. You'd then need to explicitly un-bind and then re-bind to all elements in the DOM (otherwise you'll end up with binds being duplicated). This process would need to be repeated each time an input was added to the DOM.<form action="portfolio.html">
<button type="link" class="btn btn-primary btn-lg">View Work</button>
</form>
I just figured this out, and it links perfectly to another page without having my default link settings over ride my button classes! :)
Groovy is a dynamically typed language, whose syntax is very close to Java, with a number of syntax improvements that allow for lighter code and less boilerplate. It can run through an interpreter as well as being compiled, which makes it good for fast prototyping, scripts, and learning dynamic languages without having to learn a new syntax (assuming you know Java). As of Groovy 2.0, it also has growing support for static compilation. Groovy supports closures and has support for programming in a somewhat functional style, although it's still fairly far from the traditional definition of functional programming.
Clojure is a dialect of Lisp with a few advanced features like Software Transactional Memory. If you like Lisp and would like to use something like it under the JVM, Clojure is for you. It's possibly the most functional language running on the JVM, and certainly the most famous one. Also, it has a stronger emphasis on immutability than other Lisp dialects, which takes it closer to the heart of functional language enthusiasts.
Scala is a fully object oriented language, more so than Java, with one of the most advanced type systems available on non-research languages, and certainly the most advanced type system on the JVM. It also combines many concepts and features of functional languages, without compromising the object orientation, but its compromise on functional language characteristics put off some enthusiasts of the latter.
Groovy has good acceptance and a popular web framework in Grails. It also powers the Gradle build system, which is becoming a popular alternative to Maven. I personally think it is a language with limited utility, particularly as Jython and JRuby start making inroads on the JVM-land, compared to the others.
Clojure, even discounting some very interesting features, has a strong appeal just by being a Lisp dialect on JVM. It might limit its popularity, granted, but I expect it will have loyal community around it for a long time.
Scala can compete directly with Java, and give it a run for its money on almost all aspects. It can't compete in popularity at the moment, of course, and the lack of a strong corporate backing may hinder its acceptance on corporate environments. It's also a much more dynamic language than Java, in the sense of how the language evolves. From the perspective of the language, that's a good thing. From the perspective of users who plan on having thousands of lines of code written in it, not so.
As a final disclosure, I'm very familiar with Scala, and only acquainted with the other two.
If you are mocking the behavior (with something like doNothing()
) there should really be no need to call to verify*()
. That said, here's my stab at re-writing your test method:
@PrepareForTest({InternalUtils.class})
@RunWith(PowerMockRunner.class)
public class InternalServiceTest { //Note the renaming of the test class.
public void testProcessOrder() {
//Variables
InternalService is = new InternalService();
Order order = mock(Order.class);
//Mock Behavior
when(order.isSuccessful()).thenReturn(true);
mockStatic(Internalutils.class);
doNothing().when(InternalUtils.class); //This is the preferred way
//to mock static void methods.
InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());
//Execute
is.processOrder(order);
//Verify
verifyStatic(InternalUtils.class); //Similar to how you mock static methods
//this is how you verify them.
InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());
}
}
I grouped into four sections to better highlight what is going on:
I choose to declare any instance variables / method arguments / mock collaborators here. If it is something used in multiple tests, consider making it an instance variable of the test class.
This is where you define the behavior of all of your mocks. You're setting up return values and expectations here, prior to executing the code under test. Generally speaking, if you set the mock behavior here you wouldn't need to verify the behavior later.
Nothing fancy here; this just kicks off the code being tested. I like to give it its own section to call attention to it.
This is when you call any method starting with verify
or assert
. After the test is over, you check that the things you wanted to have happen actually did happen. That is the biggest mistake I see with your test method; you attempted to verify the method call before it was ever given a chance to run. Second to that is you never specified which static method you wanted to verify.
This is mostly personal preference on my part. There is a certain order you need to do things in but within each grouping there is a little wiggle room. This helps me quickly separate out what is happening where.
I also highly recommend going through the examples at the following sites as they are very robust and can help with the majority of the cases you'll need:
After reading through various solutions, I'd like to add that the reason those solutions work is to rely on the concept of scope chain. It's the way JavaScript resolve a variable during execution.
var
and its arguments
. window
.In the initial code:
funcs = {};
for (var i = 0; i < 3; i++) {
funcs[i] = function inner() { // function inner's scope contains nothing
console.log("My value: " + i);
};
}
console.log(window.i) // test value 'i', print 3
When funcs
gets executed, the scope chain will be function inner -> global
. Since the variable i
cannot be found in function inner
(neither declared using var
nor passed as arguments), it continues to search, until the value of i
is eventually found in the global scope which is window.i
.
By wrapping it in an outer function either explicitly define a helper function like harto did or use an anonymous function like Bjorn did:
funcs = {};
function outer(i) { // function outer's scope contains 'i'
return function inner() { // function inner, closure created
console.log("My value: " + i);
};
}
for (var i = 0; i < 3; i++) {
funcs[i] = outer(i);
}
console.log(window.i) // print 3 still
When funcs
gets executed, now the scope chain will be function inner -> function outer
. This time i
can be found in the outer function's scope which is executed 3 times in the for loop, each time has value i
bound correctly. It won't use the value of window.i
when inner executed.
More detail can be found here
It includes the common mistake in creating closure in the loop as what we have here, as well as why we need closure and the performance consideration.
Maybe you can try the following :
var i = 0;
function AjaxSendForm(url, placeholder, form, append) {
var data = $(form).serialize();
append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
$.ajax({
type: 'POST',
url: url,
data: data,
beforeSend: function() {
// setting a timeout
$(placeholder).addClass('loading');
i++;
},
success: function(data) {
if (append) {
$(placeholder).append(data);
} else {
$(placeholder).html(data);
}
},
error: function(xhr) { // if error occured
alert("Error occured.please try again");
$(placeholder).append(xhr.statusText + xhr.responseText);
$(placeholder).removeClass('loading');
},
complete: function() {
i--;
if (i <= 0) {
$(placeholder).removeClass('loading');
}
},
dataType: 'html'
});
}
This way, if the beforeSend
statement is called before the complete
statement i
will be greater than 0 so it will not remove the class. Then only the last call will be able to remove it.
I cannot test it, let me know if it works or not.
I'm going to go right ahead and offer a solution using jQuery, which means you will need to import the library if you haven't already...
Import the jQuery library in your page mark-up:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
Then create another *.js script file (I call mine ExecutePageMethod
, since that is the only method it is going to expose) and import it:
<script type="text/javascript" src="/ExecutePageMethod.js" ></script>
Within the newly added file, add the following code (I remember pulling this from elsewhere, so someone else deserves credit for it really):
function ExecutePageMethod(page, fn, paramArray, successFn, errorFn) {
var paramList = '';
if (paramArray.length > 0) {
for (var i = 0; i < paramArray.length; i += 2) {
if (paramList.length > 0) paramList += ',';
paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
}
}
paramList = '{' + paramList + '}';
$.ajax({
type: "POST",
url: page + "/" + fn,
contentType: "application/json; charset=utf-8",
data: paramList,
dataType: "json",
success: successFn,
error: errorFn
});
}
You will then need to augment your .NET page method with the appropriate attributes, as such:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string MyMethod()
{
return "Yay!";
}
Now, within your page mark-up, within a script
block or from another script file, you can call the method, like so:
ExecutePageMethod("PageName.aspx", "MyMethod", [], OnSuccess, OnFailure);
Obviously you will need to implement the OnSuccess
and OnFailure
methods.
To consume the results, say in the OnSuccess
method, you can use the parseJSON method, which, if the results become more complex (in the case or returning an array of types, for instance) this method will parse it into objects:
function OnSuccess(result) {
var parsedResult = jQuery.parseJSON(result.d);
}
This ExecutePageMethod
code is particularly useful since it it reusable, so rather than having to manage an $.ajax
call for each page method you might want to execute, you just need to pass the page, method name and arguments to this method.
Just to expand on the previous answer colorRampPalette
can handle more than two colors.
So for a more expanded "heat map" type look you can....
colfunc<-colorRampPalette(c("red","yellow","springgreen","royalblue"))
plot(rep(1,50),col=(colfunc(50)), pch=19,cex=2)
The resulting image:
After you add the .gitignore
file and commit it, it will no longer show up in the "untracked files" list.
git add .gitignore
git commit -m "add .gitignore file"
git status
To expand on Pavlo's answer https://stackoverflow.com/a/34063808/1069914, you can have multiple child items justify-content: flex-start
in their behavior but have the last item justify-content: flex-end
.container {
height: 100px;
border: solid 10px skyblue;
display: flex;
justify-content: flex-end;
}
.container > *:not(:last-child) {
margin-right: 0;
margin-left: 0;
}
/* set the second to last-child */
.container > :nth-last-child(2) {
margin-right: auto;
margin-left: 0;
}
.block {
width: 50px;
background: tomato;
border: 1px solid black;
}
_x000D_
<div class="container">
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block" style="width:150px">I should be at the end of the flex container (i.e. justify-content: flex-end)</div>
</div>
_x000D_
signal
isn't the most reliable way as it differs in implementations. I would recommend using sigaction
. Tom's code would now look like this :
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
void my_handler(int s){
printf("Caught signal %d\n",s);
exit(1);
}
int main(int argc,char** argv)
{
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = my_handler;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGINT, &sigIntHandler, NULL);
pause();
return 0;
}
Under the circumstances, you're almost certainly better off skipping the check for self-assignment -- when you're only assigning one member that seems to be a simple type (probably a double), it's generally faster to do that assignment than avoid it, so you'd end up with:
SimpleCircle & SimpleCircle::operator=(const SimpleCircle & rhs)
{
itsRadius = rhs.getRadius(); // or just `itsRadius = rhs.itsRadius;`
return *this;
}
I realize that many older and/or lower quality books advise checking for self assignment. At least in my experience, however, it's sufficiently rare that you're better off without it (and if the operator depends on it for correctness, it's almost certainly not exception safe).
As an aside, I'd note that to define a circle, you generally need a center and a radius, and when you copy or assign, you want to copy/assign both.
Use Query.setParameterList()
, Javadoc here.
There are four variants to pick from.
W3C doc says regarding "border-radius" property: "supported in IE9+, Firefox, Chrome, Safari, and Opera".
Hence I assume you're testing on IE8 or below.
For "regular elements" there is a solution compatible with IE8 & other old/poor browsers. See below.
HTML:
<div class="myWickedClass">
<span class="myCoolItem">Some text</span> <span class="myCoolItem">Some text</span> <span class="myCoolItem"> Some text</span> <span class="myCoolItem">Some text</span>
</div>
CSS:
.myWickedClass{
padding: 0 5px 0 0;
background: #F7D358 url(../img/roundedCorner_right.png) top right no-repeat scroll;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
font: normal 11px Verdana, Helvetica, sans-serif;
color: #A4A4A4;
}
.myWickedClass > .myCoolItem:first-child {
padding-left: 6px;
background: #F7D358 url(../img/roundedCorner_left.png) 0px 0px no-repeat scroll;
}
.myWickedClass > .myCoolItem {
padding-right: 5px;
}
You need to create both roundedCorner_right.png & roundedCorner_left.png. These are work around for IE8 (& below) to fake the rounded corner feature.
So in this example above we apply the left rounded corner to the first span element in the containing div, & we apply the right rounded corner to the containing div. These images overlap the browser-provided "squary corners" & give the illusion of being part of a rounded element.
The idea for inputs would be to do the same logic. However, input is an empty element, " element is empty, it contains attributes only", in other word, you cannot wrap a span into an input such as <input><span class="myCoolItem"></span></input>
to then use background images like in the previous example.
Hence the solution seems to be to do the opposite: wrap the input into another element. see this answer rounded corners of input elements in IE
The Predicate will always return a boolean, by definition.
Predicate<T>
is basically identical to Func<T,bool>
.
Predicates are very useful in programming. They are often used to allow you to provide logic at runtime, that can be as simple or as complicated as necessary.
For example, WPF uses a Predicate<T>
as input for Filtering of a ListView's ICollectionView. This lets you write logic that can return a boolean determining whether a specific element should be included in the final view. The logic can be very simple (just return a boolean on the object) or very complex, all up to you.
Once you have Selected a group of sheets, you can use Selection
Consider:
Sub luxation()
ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Select
Selection.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:="C:\TestFolder\temp.pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
End Sub
EDIT#1:
Further testing has reveled that this technique depends on the group of cells selected on each worksheet. To get a comprehensive output, use something like:
Sub Macro1()
Sheets("Sheet1").Activate
ActiveSheet.UsedRange.Select
Sheets("Sheet2").Activate
ActiveSheet.UsedRange.Select
Sheets("Sheet3").Activate
ActiveSheet.UsedRange.Select
ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Select
Selection.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\Users\James\Desktop\pdfmaker.pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
True
End Sub