I am using MVC4, I used following approach to redirect a custom html screen upon authorization breach.
Extend AuthorizeAttribute
say CutomAuthorizer
override the OnAuthorization
and HandleUnauthorizedRequest
Register the CustomAuthorizer
in the RegisterGlobalFilters
.
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new CustomAuthorizer());
}
upon identifying the unAuthorized
access call HandleUnauthorizedRequest
and redirect to the concerned controller action as shown below.
public class CustomAuthorizer : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
bool isAuthorized = IsAuthorized(filterContext); // check authorization
base.OnAuthorization(filterContext);
if (!isAuthorized && !filterContext.ActionDescriptor.ActionName.Equals("Unauthorized", StringComparison.InvariantCultureIgnoreCase)
&& !filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.Equals("LogOn", StringComparison.InvariantCultureIgnoreCase))
{
HandleUnauthorizedRequest(filterContext);
}
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result =
new RedirectToRouteResult(
new RouteValueDictionary{{ "controller", "LogOn" },
{ "action", "Unauthorized" }
});
}
}
I'm not sure if this is what you had in mind, but I ended up on this question because I was unable to install node_modules
inside my project dir as it was mounted on a filesystem that did not support symlinks (a VM "shared" folder).
I found the following workaround:
package.json
file to a temp folder on a different filesystemnpm install
therenode_modules
directory back into the project dir, using cp -r --dereference
to expand symlinks into copies.I hope this helps someone else who ends up on this question when looking for a way to move node_modules
to a different filesystem.
There is another workaround, which I found on the github issue that @Charminbear linked to, but this doesn't work with grunt
because it does not support NODE_PATH
as per https://github.com/browserify/resolve/issues/136:
lets say you have
/media/sf_shared
and you can't install symlinks in there, which means you can't actually npm install from/media/sf_shared/myproject
because some modules use symlinks.
$ mkdir /home/dan/myproject && cd /home/dan/myproject
$ ln -s /media/sf_shared/myproject/package.json
(you can symlink in this direction, just can't create one inside of /media/sf_shared)$ npm install
$ cd /media/sf_shared/myproject
$ NODE_PATH=/home/dan/myproject/node_modules node index.js
Both attributes are needed and also recheck all the form elements has "name" attribute. if you are using form submit concept, other wise just use div tag instead of form element.
<input [(ngModel)]="firstname" name="something">
If you don't want to modify the original object (using some ES6 operators):
const keys = Object.keys(objectWithNulls).filter(key => objectWithNulls[key]);
const pairs = keys.map(key => ({ [key]: objectWithNulls[key] }));
const objectWithoutNulls = pairs.reduce((val, acc) => ({ ...val, ...acc }));
The filter(key => objectWithNulls[key])
returns anything that is truthy, so will reject any values such as0
or false
, as well as undefined
or null
. Can be easily changed to filter(key => objectWithNulls[key] !== undefined)
or something similar if this is unwanted behaviour.
selectedIndex is a JavaScript Select Property. For jQuery you can use this code:
jQuery(document).ready(function($) {
$("#dropDownMenuKategorie").change(function() {
// I personally prefer using console.log(), but if you want you can still go with the alert().
console.log($(this).children('option:selected').index());
});
});
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['uid'] === $id) {
return $key;
}
}
return null;
}
This will work. You should call it like this:
$id = searchForId('100', $userdb);
It is important to know that if you are using ===
operator compared types have to be exactly same, in this example you have to search string
or just use ==
instead ===
.
Based on angoru answer. In later versions of PHP (>= 5.5.0
) you can use one-liner.
$key = array_search('100', array_column($userdb, 'uid'));
Here is documentation: http://php.net/manual/en/function.array-column.php.
Using IntelliJ IDEA. To generate class diagram select package and press Ctrl + Alt + U:
By default, it displays only class names and not all dependencies. To change it: right click -> Show Categories... and Show dependencies:
To genarate dependencies diagram (UML Deployment diagram) and you use maven go View -> Tool Windows -> Maven Projects and press Ctrl + Alt + U:
Also it is possible to generate more others diagrams. See documentation.
In addition to kieran's answer, apparently, modern browsers have an Object.keys
function. In this case, you could do this:
Object.keys(jsonArray).length;
More details in this answer on How to list the properties of a javascript object
Empty just check is the refered variable/array has an value if you check the php doc(empty) you'll see this things are considered emtpy
* "" (an empty string) * 0 (0 as an integer) * "0" (0 as a string) * NULL * FALSE * array() (an empty array) * var $var; (a variable declared, but without a value in a class)
while isset check if the variable isset and not null which can also be found in the php doc(isset)
D
or dd
deletes and copies the line to the register. You can use Vx
which only deletes the line and stays in the normal mode.
#include <conio.h>
if (kbhit() != 0) {
cout << getch() << endl;
}
This uses kbhit()
to check if the keyboard is being pressed and uses getch()
to get the character that is being pressed.
I want to add to this thread that it may also have to do with other dependencies.
For instance, nothing I updated or set for NodeJS, MongoDB or Mongoose were the issue - however - connect-mongodb-session
had been updated and starting slinging the same error. The solution, in this case, was to simply rollback the version of connect-mongodb-session
from version 2.3.0
to 2.2.0
.
If you have a POSIX-2008 compliant system (any modern Linux), you can use the safe and convenient asprintf()
function: It will malloc()
enough memory for you, you don't need to worry about the maximum string size. Use it like this:
char* string;
if(0 > asprintf(&string, "Formatting a number: %d\n", 42)) return error;
log_out(string);
free(string);
This is the minimum effort you can get to construct the string in a secure fashion. The sprintf()
code you gave in the question is deeply flawed:
There is no allocated memory behind the pointer. You are writing the string to a random location in memory!
Even if you had written
char s[42];
you would be in deep trouble, because you can't know what number to put into the brackets.
Even if you had used the "safe" variant snprintf()
, you would still run the danger that your strings gets truncated. When writing to a log file, that is a relatively minor concern, but it has the potential to cut off precisely the information that would have been useful. Also, it'll cut off the trailing endline character, gluing the next log line to the end of your unsuccessfully written line.
If you try to use a combination of malloc()
and snprintf()
to produce correct behavior in all cases, you end up with roughly twice as much code than I have given for asprintf()
, and basically reprogram the functionality of asprintf()
.
If you are looking at providing a wrapper of log_out()
that can take a printf()
style parameter list itself, you can use the variant vasprintf()
which takes a va_list
as an argument. Here is a perfectly safe implementation of such a wrapper:
//Tell gcc that we are defining a printf-style function so that it can do type checking.
//Obviously, this should go into a header.
void log_out_wrapper(const char *format, ...) __attribute__ ((format (printf, 1, 2)));
void log_out_wrapper(const char *format, ...) {
char* string;
va_list args;
va_start(args, format);
if(0 > vasprintf(&string, format, args)) string = NULL; //this is for logging, so failed allocation is not fatal
va_end(args);
if(string) {
log_out(string);
free(string);
} else {
log_out("Error while logging a message: Memory allocation failed.\n");
}
}
This can be used to find all the numeric values (even those formatted as text) in a sheet and convert them to single (CSng function).
For Each r In Sheets("Sheet1").UsedRange.SpecialCells(xlCellTypeConstants)
If IsNumeric(r) Then
r.Value = CSng(r.Value)
r.NumberFormat = "0.00"
End If
Next
wp_trim_words()
This function trims text to a certain number of words and returns the trimmed text.
$excerpt = wp_trim_words( get_the_content(), 40, '<a href="'.get_the_permalink().'">More Link</a>');
Get truncated string with specified width using mb_strimwidth()
php function.
$excerpt = mb_strimwidth( strip_tags(get_the_content()), 0, 100, '...' );
Using add_filter()
method of WordPress on the_content
filter hook.
add_filter( "the_content", "limit_content_chr" );
function limit_content_chr( $content ){
if ( 'post' == get_post_type() ) {
return mb_strimwidth( strip_tags($content), 0, 100, '...' );
} else {
return $content;
}
}
Using custom php function to limit content characters.
function limit_content_chr( $content, $limit=100 ) {
return mb_strimwidth( strip_tags($content), 0, $limit, '...' );
}
// using above function in template tags
echo limit_content_chr( get_the_content(), 50 );
Either write a class that implements Runnable, and pass whatever you need in a suitably defined constructor, or write a class that extends Thread with a suitably defined constructor that calls super() with appropriate parameters.
In Rails 5, the has_key? method checks if key exists in hash. The syntax to use it is:
YourHash.has_key? :yourkey
Hi starbeamrainbowlabs ,
You can do this with the following:
var oldValue = "pic quality, hello" ;
var newValue = "hello";
var oldValueLength = oldValue.length ;
var newValueLength = newValue.length ;
var from = oldValue.search(newValue) ;
var to = from + newValueLength ;
var nes = oldValue.substr(0,from) + oldValue.substr(to,oldValueLength);
console.log(nes);
I tested this in my javascript console so you can also check this out Thanks
```yaml
{
"this-json": "looks awesome..."
}
If you want to have keys a different colour to the parameters, set your language as yaml
@Ankanna's answer gave me the idea of going through github's supported language list and yaml
was my best find.
With the Material Components Library you can use the CircularProgressIndicator
:
Something like:
<com.google.android.material.progressindicator.CircularProgressIndicator
app:indicatorColor="@color/...."
app:trackColor="@color/...."
app:circularRadius="64dp"/>
You can use these attributes:
circularRadius
: defines the radius of the circular progress indicatortrackColor
: the color used for the progress track. If not defined, it will be set to the indicatorColor
and apply the android:disabledAlpha
from the theme.indicatorColor
: the single color used for the indicator in determinate/indeterminate mode. By default it uses theme primary colorUse progressIndicator.setProgressCompat((int) value, true);
to update the value in the indicator.
Note: it requires at least the version 1.3.0-alpha04
.
Please Search Google given to the world by Larry Page and Sergey Brin.
BufferedWriter out = null;
try {
FileWriter fstream = new FileWriter("out.txt", true); //true tells to append data.
out = new BufferedWriter(fstream);
out.write("\nsue");
}
catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
finally {
if(out != null) {
out.close();
}
}
The Database that we are using should be mentioned under search_path in Postgres SQL Configuration file. This can be done by editing Postgressql configuration file by setting search_path along with database name for example: TESTDB.
It worked for me after making the above change.
The issue for you is that you are using mm
. You should use MM
. MM
is for month and mm
is for minutes. Try with yyyy-MM-dd HH:mm
Other approach:
It can be as simple as this (other option is to use joda-time)
static final long ONE_MINUTE_IN_MILLIS=60000;//millisecs
Calendar date = Calendar.getInstance();
long t= date.getTimeInMillis();
Date afterAddingTenMins=new Date(t + (10 * ONE_MINUTE_IN_MILLIS));
As This answer's states, you can use Array.sort
.
arr.sort(function(a,b){return new Date(a.updated_at) - new Date(b.updated_at)})
arr = [_x000D_
{_x000D_
"updated_at" : "2012-01-01T06:25:24Z",_x000D_
"foo" : "bar"_x000D_
},_x000D_
{_x000D_
"updated_at" : "2012-01-09T11:25:13Z",_x000D_
"foo" : "bar"_x000D_
},_x000D_
{_x000D_
"updated_at" : "2012-01-05T04:13:24Z",_x000D_
"foo" : "bar"_x000D_
}_x000D_
];_x000D_
arr.sort(function(a,b){return new Date(a.updated_at) - new Date(b.updated_at)});_x000D_
console.log(arr);
_x000D_
I use mostly 978px width for my designs. Adv. of 978px : can be divided by 2,3.
As said, fs.readFile
is an asynchronous action. It means that when you tell node to read a file, you need to consider that it will take some time, and in the meantime, node continued to run the following code. In your case it's: console.log(content);
.
It's like sending some part of your code for a long trip (like reading a big file).
Take a look at the comments that I've written:
var content;
// node, go fetch this file. when you come back, please run this "read" callback function
fs.readFile('./Index.html', function read(err, data) {
if (err) {
throw err;
}
content = data;
});
// in the meantime, please continue and run this console.log
console.log(content);
That's why content
is still empty when you log it. node has not yet retrieved the file's content.
This could be resolved by moving console.log(content)
inside the callback function, right after content = data;
. This way you will see the log when node is done reading the file and after content
gets a value.
df.filter(df.location.contains('google.com'))
You can use plain SQL in
filter
df.filter("location like '%google.com%'")
or with DataFrame column methods
df.filter(df.location.like('%google.com%'))
Loop through divs every 10 seconds.
$(function () {
var counter = 0,
divs = $('#div1, #div2, #div3');
function showDiv () {
divs.hide() // hide all divs
.filter(function (index) { return index == counter % 3; }) // figure out correct div to show
.show('fast'); // and show it
counter++;
}; // function to loop through divs and show correct div
showDiv(); // show first div
setInterval(function () {
showDiv(); // show next div
}, 10 * 1000); // do this every 10 seconds
});
Since I was helped with my project by the answer above (I asked a duplicate question and was referred here), I am submitting an answer (my test code) for bracket notation when nesting within the var:
<html>_x000D_
<head>_x000D_
<script type="text/javascript">_x000D_
function displayFile(whatOption, whatColor) {_x000D_
var Test01 = {_x000D_
rectangle: {_x000D_
red: "RectangleRedFile",_x000D_
blue: "RectangleBlueFile"_x000D_
},_x000D_
square: {_x000D_
red: "SquareRedFile",_x000D_
blue: "SquareBlueFile"_x000D_
}_x000D_
};_x000D_
var filename = Test01[whatOption][whatColor];_x000D_
alert(filename);_x000D_
}_x000D_
</script>_x000D_
</head>_x000D_
<body>_x000D_
<p onclick="displayFile('rectangle', 'red')">[ Rec Red ]</p>_x000D_
<br/>_x000D_
<p onclick="displayFile('square', 'blue')">[ Sq Blue ]</p>_x000D_
<br/>_x000D_
<p onclick="displayFile('square', 'red')">[ Sq Red ]</p>_x000D_
</body>_x000D_
</html>
_x000D_
As a different font is likely to be already defined by the browser for form elements, here are 2 ways to use this font everywhere:
body, input, textarea {
font-family: Algerian;
}
body {
font-family: Algerian !important;
}
There'll still have a monospace font on elements like pre/code, kbd, etc but, in case you use these elements, you'd better use a monospace font there.
Important note: if very few people has this font installed on their OS, then the second font in the list will be used. Here you defined no second font so the default serif font will be used, and it'll be Times, Times New Roman except maybe on Linux.
Two options there: use @font-face if your font is free of use as a downloadable font or add fallback(s): a second, a third, etc and finally a default family (sans-serif, cursive (*), monospace or serif). The first of the list that exists on the OS of the user will be used.
(*) default cursive on Windows is Comic Sans. Except if you want to troll Windows users, don't do that :) This font is terrible except for your children birthdays where it's welcome.
I looked at Nate Barr's answer above, which you seemed to like. It doesn't seem very different from the simpler
html {background-color: grey}
This works for me.
Create a network with
docker network create --subnet=172.17.0.0/16 selnet
Run docker image
docker run --net selnet --ip 172.18.0.2 hub
At first, I got
docker: Error response from daemon: Invalid address 172.17.0.2: It does not belong to any of this network's subnets.
ERRO[0000] error waiting for container: context canceled
Solution: Increased the 2nd quadruple of the IP [.18. instead of .17.]
To fix this, you need to supply an extra parameter to openssl
when you're creating the cert, basically
-sha256 -extfile v3.ext
where v3.ext
is a file like so, with %%DOMAIN%%
replaced with the same name you use as your Common Name
. More info here and over here. Note that typically you'd set the Common Name
and %%DOMAIN%%
to the domain you're trying to generate a cert for. So if it was www.mysupersite.com
, then you'd use that for both.
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = %%DOMAIN%%
Another note: If all you're trying to do is stop chrome from throwing errors when viewing a self signed certificate, you can can tell Chrome to ignore all SSL errors for ALL sites by starting it with a special command line option, as detailed here on SuperUser
Tank´s Yogihosting
I have in my database one goups of tables from Open Streep Maps and I tested successful.
Distance work fine in meters.
SET @orig_lat=-8.116137;
SET @orig_lon=-34.897488;
SET @dist=1000;
SELECT *,(((acos(sin((@orig_lat*pi()/180)) * sin((dest.latitude*pi()/180))+cos((@orig_lat*pi()/180))*cos((dest.latitude*pi()/180))*cos(((@orig_lon-dest.longitude)*pi()/180))))*180/pi())*60*1.1515*1609.344) as distance FROM nodes AS dest HAVING distance < @dist ORDER BY distance ASC LIMIT 100;
I would start by turning off TCP offloading. There have been a few things that cause intermittent connectivity issues and this is the one that is usually the culprit.
Note: I have seen this setting cause problems on Win Server 2003 and Win Server 2008
http://blogs.msdn.com/b/mssqlisv/archive/2008/05/27/sql-server-intermittent-connectivity-issue.aspx
http://technet.microsoft.com/en-us/library/gg162682(v=ws.10).aspx
in Xcode 4.5 using storyboard, by far the easiest solution i've found when the value of the Back button doesn't have to change dynamically is to use the "Back Button" field associated with the Navigation Item of the View Controller to which you want the "Back" button to say something else.
e.g. in the screenshot below, i want the Back button for the view controller(s) that i push to have "Back" as the title of the Back button.
of course, this won't work if you need the back button to say something slightly different each time … there are all of the other solutions here for that.
Corrected as of 25.06.2019:
var newDate = new Date(date.setMonth(date.getMonth()+8));
Old From here:
var jan312009 = new Date(2009, 0, 31);
var eightMonthsFromJan312009 = jan312009.setMonth(jan312009.getMonth()+8);
I've done some research and it seems that the sys.argv might require an argument at the command line when running the script
Not might, but definitely requires. That's the whole point of sys.argv
, it contains the command line arguments. Like any python array, accesing non-existent element raises IndexError
.
Although the code uses try/except
to trap some errors, the offending statement occurs in the first line.
So the script needs a directory name, and you can test if there is one by looking at len(sys.argv)
and comparing to 1+number_of_requirements. The argv always contains the script name plus any user supplied parameters, usually space delimited but the user can override the space-split through quoting. If the user does not supply the argument, your choices are supplying a default, prompting the user, or printing an exit error message.
To print an error and exit when the argument is missing, add this line before the first use of sys.argv:
if len(sys.argv)<2:
print "Fatal: You forgot to include the directory name on the command line."
print "Usage: python %s <directoryname>" % sys.argv[0]
sys.exit(1)
sys.argv[0]
always contains the script name, and user inputs are placed in subsequent slots 1, 2, ...
see also:
You can loop through a hash map like this
<%
ArrayList list = new ArrayList();
TreeMap itemList=new TreeMap();
itemList.put("test", "test");
list.add(itemList);
pageContext.setAttribute("itemList", list);
%>
<c:forEach items="${itemList}" var="itemrow">
<input type="text" value="<c:out value='${itemrow.test}'/>"/>
</c:forEach>
For more JSTL functionality look here
queryParams
queryParams
is another input of routerLink
where they can be passed like
<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}">Somewhere</a>
fragment
<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}" [fragment]="yyy">Somewhere</a>
routerLinkActiveOptions
To also get routes active class set on parent routes:
[routerLinkActiveOptions]="{ exact: false }"
To pass query parameters to this.router.navigate(...)
use
let navigationExtras: NavigationExtras = {
queryParams: { 'session_id': sessionId },
fragment: 'anchor'
};
// Navigate to the login page with extras
this.router.navigate(['/login'], navigationExtras);
See also https://angular.io/guide/router#query-parameters-and-fragments
DECLARE @sql VARCHAR(MAX)
SET @sql=''
SELECT @sql=@sql+'drop procedure ['+name +'];' FROM sys.objects
WHERE type = 'p' AND is_ms_shipped = 0
exec(@sql);
Python 3
Ther are two ways to achieve this:
1) With built-in function count()
sentence = 'Mary had a little lamb'
print(sentence.count('a'))`
2) Without using a function
sentence = 'Mary had a little lamb'
count = 0
for i in sentence:
if i == "a":
count = count + 1
print(count)
$pristine
/$dirty
tells you whether the user actually changed anything, while $touched
/$untouched
tells you whether the user has merely been there/visited.
This is really useful for validation. The reason for $dirty
was always to avoid showing validation responses until the user has actually visited a certain control. But, by using only the $dirty
property, the user wouldn't get validation feedback unless they actually altered the value. So, an $invalid
field still wouldn't show the user a prompt if the user didn't change/interact with the value. If the user entirely ignored a required field, everything looked OK.
With Angular 1.3 and ng-touched
, you can now set a particular style on a control as soon as the user has blurred, regardless of whether they actually edited the value or not.
Here's a CodePen that shows the difference in behavior.
Make Sure the Select Run/Debug Configuration is wear or mobile as per your installation in android studio...
You're looking for the .filter()
function:
$scope.appIds = $scope.applicationsHere.filter(function(obj) {
return obj.selected;
});
That'll produce an array that contains only those objects whose "selected" property is true
(or truthy).
edit sorry I was getting some coffee and I missed the comments - yes, as jAndy noted in a comment, to filter and then pluck out just the "id" values, it'd be:
$scope.appIds = $scope.applicationsHere.filter(function(obj) {
return obj.selected;
}).map(function(obj) { return obj.id; });
Some functional libraries (like Functional, which in my opinion doesn't get enough love) have a .pluck()
function to extract property values from a list of objects, but native JavaScript has a pretty lean set of such tools.
Use the "geometry" package and write \newgeometry{left=3cm,bottom=0.1cm}
where you want to change your margins. When you want to reset your margins, you write \restoregeometry
.
For those who are trying to use 3.1.0 but after installing python says "cv2 module not found".
You likely have python but not python-dev.
sudo apt-get install python-dev
then reinstall 3.1.0 and it'll work.
As Ennui mentioned, IE 10 supports the -ms
prefixed version of Flexbox (IE 11 supports it unprefixed). The errors I can see in your code are:
display: -ms-flexbox
instead of display: -ms-flex
flex
values, like flex: 0 1 auto
to avoid ambiguitySo the final updated code is...
.flexbox form {
display: -webkit-flex;
display: -moz-flex;
display: -ms-flexbox;
display: -o-flex;
display: flex;
/* Direction defaults to 'row', so not really necessary to specify */
-webkit-flex-direction: row;
-moz-flex-direction: row;
-ms-flex-direction: row;
-o-flex-direction: row;
flex-direction: row;
}
.flexbox form input[type=submit] {
width: 31px;
}
.flexbox form input[type=text] {
width: auto;
/* Flex should have 3 values which is shorthand for
<flex-grow> <flex-shrink> <flex-basis> */
-webkit-flex: 1 1 auto;
-moz-flex: 1 1 auto;
-ms-flex: 1 1 auto;
-o-flex: 1 1 auto;
flex: 1 1 auto;
/* I don't think you need 'display: flex' on child elements * /
display: -webkit-flex;
display: -moz-flex;
display: -ms-flex;
display: -o-flex;
display: flex;
/**/
}
A dictionary doesn't keep an hash of the values, only the keys, so any search over it using a value is going to take at least linear time. Your best bet is to simply iterate over the elements in the dictionary and keep track of the matching keys or switch to a different data structure, perhaps maintain two dictionary mapping key->value and value->List_of_keys. If you do the latter you will trade storage for look up speed. It wouldn't take much to turn @Cybis example into such a data structure.
It is because you forgot to pass in event
into the click
function:
$('.menuOption').on('click', function (e) { // <-- the "e" for event
e.preventDefault(); // now it'll work
var categories = $(this).attr('rel');
$('.pages').hide();
$(categories).fadeIn();
});
On a side note, e
is more commonly used as opposed to the word event
since Event
is a global variable in most browsers.
Why don't you try to code it yourself? Take it as a challenge. :)
For a 3×3 matrix
(source: wolfram.com)
the matrix inverse is
(source: wolfram.com)
I'm assuming you know what the determinant of a matrix |A| is.
Images (c) Wolfram|Alpha and mathworld.wolfram (06-11-09, 22.06)
The answer given by @allen is reasonably generic but can lack in performance for larger dataframes:
Reduce does a lot better:
from functools import reduce
import pandas as pd
# make data
df = pd.DataFrame(index=range(1_000_000))
df['1'] = 'CO'
df['2'] = 'BOB'
df['3'] = '01'
df['4'] = 'BILL'
def reduce_join(df, columns):
assert len(columns) > 1
slist = [df[x].astype(str) for x in columns]
return reduce(lambda x, y: x + '_' + y, slist[1:], slist[0])
def apply_join(df, columns):
assert len(columns) > 1
return df[columns].apply(lambda row:'_'.join(row.values.astype(str)), axis=1)
# ensure outputs are equal
df1 = reduce_join(df, list('1234'))
df2 = apply_join(df, list('1234'))
assert df1.equals(df2)
# profile
%timeit df1 = reduce_join(df, list('1234')) # 733 ms
%timeit df2 = apply_join(df, list('1234')) # 8.84 s
Rather than giving background-size:100%;
We can give background-size:contain;
Check out this for different options avaliable: http://www.css3.info/preview/background-size/
Many of the other answers don't work for Swift 5. Below is the code update to Swift 5:
let formattedNumber = phoneNumberVariable.components(separatedBy: NSCharacterSet.decimalDigits.inverted).joined(separator: "")
if let url = NSURL(string: ("tel:" + (formattedNumber)!)) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url as URL, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url as URL)
}
}
PS:
Though @Test(expected = MyException.class)
and the ExpectedException rule are very good choices, there are some instances where the JUnit3-style exception catching is still the best way to go:
@Test public void yourTest() {
try {
systemUnderTest.doStuff();
fail("MyException expected.");
} catch (MyException expected) {
// Though the ExpectedException rule lets you write matchers about
// exceptions, it is sometimes useful to inspect the object directly.
assertEquals(1301, expected.getMyErrorCode());
}
// In both @Test(expected=...) and ExpectedException code, the
// exception-throwing line will be the last executed line, because Java will
// still traverse the call stack until it reaches a try block--which will be
// inside the JUnit framework in those cases. The only way to prevent this
// behavior is to use your own try block.
// This is especially useful to test the state of the system after the
// exception is caught.
assertTrue(systemUnderTest.isInErrorState());
}
Another library that claims to help here is catch-exception; however, as of May 2014, the project appears to be in maintenance mode (obsoleted by Java 8), and much like Mockito catch-exception can only manipulate non-final
methods.
to nearest 10 , should be as below
$number = ceil($input * 0.1)/0.1 ;
position: absolute
will position the element by coordinates, relative to the closest positioned ancestor, i.e. the closest parent which isn't position: static
.
Have your four divs nested inside the target div, give the target div position: relative
, and use position: absolute
on the others.
Structure your HTML similar to this:
<div id="container">
<div class="top left"></div>
<div class="top right"></div>
<div class="bottom left"></div>
<div class="bottom right"></div>
</div>
And this CSS should work:
#container {
position: relative;
}
#container > * {
position: absolute;
}
.left {
left: 0;
}
.right {
right: 0;
}
.top {
top: 0;
}
.bottom {
bottom: 0;
}
...
to make UITableView sections header not sticky or sticky:
change the table view's style - make it grouped for not sticky & make it plain for sticky section headers - do not forget: you can do it from storyboard without writing code. (click on your table view and change it is style from the right Side/ component menu)
if you have extra components such as custom views or etc. please check the table view's margins to create appropriate design. (such as height of header for sections & height of cell at index path, sections)
More universal can be: for each v Selection : v.value = "'" & v.value : next and selecting range of cells before execution
Old post I know. In order to run your app always in portrait mode even when orientation may be or is swapped etc (for example on tablets) I designed this function that is used to set the device in the right orientation without the need to know how the portrait and landscape features are organised on the device.
private void initActivityScreenOrientPortrait()
{
// Avoid screen rotations (use the manifests android:screenOrientation setting)
// Set this to nosensor or potrait
// Set window fullscreen
this.activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
DisplayMetrics metrics = new DisplayMetrics();
this.activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
// Test if it is VISUAL in portrait mode by simply checking it's size
boolean bIsVisualPortrait = ( metrics.heightPixels >= metrics.widthPixels );
if( !bIsVisualPortrait )
{
// Swap the orientation to match the VISUAL portrait mode
if( this.activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT )
{ this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); }
else { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ); }
}
else { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); }
}
Works like a charm!
NOTICE:
Change this.activity
by your activity or add it to the main activity and remove this.activity
;-)
Building on the excellent answer above by fir3rpho3nixx and David Schmitt, I have modified their code and added the ShouldInheritOrImplementTypedGenericInterface test (last one).
/// <summary>
/// Find out if a child type implements or inherits from the parent type.
/// The parent type can be an interface or a concrete class, generic or non-generic.
/// </summary>
/// <param name="child"></param>
/// <param name="parent"></param>
/// <returns></returns>
public static bool InheritsOrImplements(this Type child, Type parent)
{
var currentChild = parent.IsGenericTypeDefinition && child.IsGenericType ? child.GetGenericTypeDefinition() : child;
while (currentChild != typeof(object))
{
if (parent == currentChild || HasAnyInterfaces(parent, currentChild))
return true;
currentChild = currentChild.BaseType != null && parent.IsGenericTypeDefinition && currentChild.BaseType.IsGenericType
? currentChild.BaseType.GetGenericTypeDefinition()
: currentChild.BaseType;
if (currentChild == null)
return false;
}
return false;
}
private static bool HasAnyInterfaces(Type parent, Type child)
{
return child.GetInterfaces().Any(childInterface =>
{
var currentInterface = parent.IsGenericTypeDefinition && childInterface.IsGenericType
? childInterface.GetGenericTypeDefinition()
: childInterface;
return currentInterface == parent;
});
}
[Test]
public void ShouldInheritOrImplementNonGenericInterface()
{
Assert.That(typeof(FooImplementor)
.InheritsOrImplements(typeof(IFooInterface)), Is.True);
}
[Test]
public void ShouldInheritOrImplementGenericInterface()
{
Assert.That(typeof(GenericFooBase)
.InheritsOrImplements(typeof(IGenericFooInterface<>)), Is.True);
}
[Test]
public void ShouldInheritOrImplementGenericInterfaceByGenericSubclass()
{
Assert.That(typeof(GenericFooImplementor<>)
.InheritsOrImplements(typeof(IGenericFooInterface<>)), Is.True);
}
[Test]
public void ShouldInheritOrImplementGenericInterfaceByGenericSubclassNotCaringAboutGenericTypeParameter()
{
Assert.That(new GenericFooImplementor<string>().GetType()
.InheritsOrImplements(typeof(IGenericFooInterface<>)), Is.True);
}
[Test]
public void ShouldNotInheritOrImplementGenericInterfaceByGenericSubclassNotCaringAboutGenericTypeParameter()
{
Assert.That(new GenericFooImplementor<string>().GetType()
.InheritsOrImplements(typeof(IGenericFooInterface<int>)), Is.False);
}
[Test]
public void ShouldInheritOrImplementNonGenericClass()
{
Assert.That(typeof(FooImplementor)
.InheritsOrImplements(typeof(FooBase)), Is.True);
}
[Test]
public void ShouldInheritOrImplementAnyBaseType()
{
Assert.That(typeof(GenericFooImplementor<>)
.InheritsOrImplements(typeof(FooBase)), Is.True);
}
[Test]
public void ShouldInheritOrImplementTypedGenericInterface()
{
GenericFooImplementor<int> obj = new GenericFooImplementor<int>();
Type t = obj.GetType();
Assert.IsTrue(t.InheritsOrImplements(typeof(IGenericFooInterface<int>)));
Assert.IsFalse(t.InheritsOrImplements(typeof(IGenericFooInterface<String>)));
}
The answer given works but disables outgoing links. Below a version with an added bonus ease out (swing) and respects outgoing links.
$(document).ready(function () {
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
var target = this.hash;
var $target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
you can use list to define it.
objs = list()
for i in range(10):
objs.append(MyClass())
I needed to do the same and had to query a query to get the result
I set my first query up to bring in all IDs from the table and all other information needed to filter:
SELECT tMAIN.tLOTS.NoContract, tMAIN.ID
FROM tMAIN INNER JOIN tLOTS ON tMAIN.ID = tLOTS.id
WHERE (((tLOTS.NoContract)=False));
Save this as Q04_1 -0 this returned 1229 results (there are 63 unique records to query - soime with multiple LOTs)
SELECT DISTINCT ID
FROM q04_1;
Saved that as q04_2
I then wrote another query which brought in the required information linked to the ID
SELECT q04_2.ID, tMAIN.Customer, tMAIN.Category
FROM q04_2 INNER JOIN tMAIN ON q04_2.ID = tMAIN.ID;
Worked a treat and got me exactly what I needed - 63 unique records returned with customer and category details.
This is how I worked around it as I couldn't get the Group By working at all - although I am rather "wet behind the ears" weith SQL (so please be gentle and constructive with feedback)
In a .txt
file opened with Notepad++,
press Ctrl-F
go in the tab "Replace"
write the regex pattern \|.+
in the space Find what
and let the space Replace with blank
Then tick the choice matches newlines after the choice Regular expression
and press two times on the Replace button
Probably not what you want to hear, but a "feeds" table would be a great middleman for this sort of transaction, giving you a denormalized way of pivoting to all these data with a polymorphic relationship.
You could build it like this:
<?php
Schema::create('feeds', function($table) {
$table->increments('id');
$table->timestamps();
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->morphs('target');
});
Build the feed model like so:
<?php
class Feed extends Eloquent
{
protected $fillable = ['user_id', 'target_type', 'target_id'];
public function user()
{
return $this->belongsTo('User');
}
public function target()
{
return $this->morphTo();
}
}
Then keep it up to date with something like:
<?php
Vote::created(function(Vote $vote) {
$target_type = 'Vote';
$target_id = $vote->id;
$user_id = $vote->user_id;
Feed::create(compact('target_type', 'target_id', 'user_id'));
});
You could make the above much more generic/robust—this is just for demonstration purposes.
At this point, your feed items are really easy to retrieve all at once:
<?php
Feed::whereIn('user_id', $my_friend_ids)
->with('user', 'target')
->orderBy('created_at', 'desc')
->get();
Below is code snippet you can use to delete the bucket,
import boto3, botocore
from botocore.exceptions import ClientError
s3 = boto3.resource("s3",aws_access_key_id='Your-Access-Key',aws_secret_access_key='Your-Secret-Key')
s3.Object('Bucket-Name', 'file-name as key').delete()
Sorry to post answer for very old thread. my answer may help other in future.
string[] TobeDistinct = {"Name","City","State"};
DataTable dtDistinct = GetDistinctRecords(DTwithDuplicate, TobeDistinct);
//Following function will return Distinct records for Name, City and State column.
public static DataTable GetDistinctRecords(DataTable dt, string[] Columns)
{
DataTable dtUniqRecords = new DataTable();
dtUniqRecords = dt.DefaultView.ToTable(true, Columns);
return dtUniqRecords;
}
Get to your Gmail account's security settings and set permissions for "Less secure apps" to Enabled. Worked for me.
If it happens that you don't need this htm characte  
shile using str.replace(/(\r\n|\n|\r)/gm, "")
you can use this str.split('\n').join('');
cheers
I had to add a footer to my RecyclerView
and here I'm sharing my code snippet as I thought it might be useful. Please check the comments inside the code for better understanding of the overall flow.
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
public class RecyclerViewWithFooterAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int FOOTER_VIEW = 1;
private ArrayList<String> data; // Take any list that matches your requirement.
private Context context;
// Define a constructor
public RecyclerViewWithFooterAdapter(Context context, ArrayList<String> data) {
this.context = context;
this.data = data;
}
// Define a ViewHolder for Footer view
public class FooterViewHolder extends ViewHolder {
public FooterViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Do whatever you want on clicking the item
}
});
}
}
// Now define the ViewHolder for Normal list item
public class NormalViewHolder extends ViewHolder {
public NormalViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Do whatever you want on clicking the normal items
}
});
}
}
// And now in onCreateViewHolder you have to pass the correct view
// while populating the list item.
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
if (viewType == FOOTER_VIEW) {
v = LayoutInflater.from(context).inflate(R.layout.list_item_footer, parent, false);
FooterViewHolder vh = new FooterViewHolder(v);
return vh;
}
v = LayoutInflater.from(context).inflate(R.layout.list_item_normal, parent, false);
NormalViewHolder vh = new NormalViewHolder(v);
return vh;
}
// Now bind the ViewHolder in onBindViewHolder
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
try {
if (holder instanceof NormalViewHolder) {
NormalViewHolder vh = (NormalViewHolder) holder;
vh.bindView(position);
} else if (holder instanceof FooterViewHolder) {
FooterViewHolder vh = (FooterViewHolder) holder;
}
} catch (Exception e) {
e.printStackTrace();
}
}
// Now the critical part. You have return the exact item count of your list
// I've only one footer. So I returned data.size() + 1
// If you've multiple headers and footers, you've to return total count
// like, headers.size() + data.size() + footers.size()
@Override
public int getItemCount() {
if (data == null) {
return 0;
}
if (data.size() == 0) {
//Return 1 here to show nothing
return 1;
}
// Add extra view to show the footer view
return data.size() + 1;
}
// Now define getItemViewType of your own.
@Override
public int getItemViewType(int position) {
if (position == data.size()) {
// This is where we'll add footer.
return FOOTER_VIEW;
}
return super.getItemViewType(position);
}
// So you're done with adding a footer and its action on onClick.
// Now set the default ViewHolder for NormalViewHolder
public class ViewHolder extends RecyclerView.ViewHolder {
// Define elements of a row here
public ViewHolder(View itemView) {
super(itemView);
// Find view by ID and initialize here
}
public void bindView(int position) {
// bindView() method to implement actions
}
}
}
The above code snippet adds a footer to the RecyclerView
. You can check this GitHub repository for checking the implementation of adding both header and a footer.
From documentation: https://docs.djangoproject.com/en/1.10/ref/settings/
if DEBUG is False, you also need to properly set the ALLOWED_HOSTS setting. Failing to do so will result in all requests being returned as “Bad Request (400)”.
And from here: https://docs.djangoproject.com/en/1.10/ref/settings/#std:setting-ALLOWED_HOSTS
I am using something like this:
ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'www.mysite.com']
If you only need the first match, then use re.search
instead of re.findall
:
>>> m = re.search('\d+', 'aa33bbb44')
>>> m.group()
'33'
>>> m = re.search('\d+', 'aazzzbbb')
>>> m.group()
Traceback (most recent call last):
File "<pyshell#281>", line 1, in <module>
m.group()
AttributeError: 'NoneType' object has no attribute 'group'
Then you can use m
as a checking condition as:
>>> m = re.search('\d+', 'aa33bbb44')
>>> if m:
print('First number found = {}'.format(m.group()))
else:
print('Not Found')
First number found = 33
This can happen when you added Core Data to an existing project.
Check the:
<Name>/<Name>.xcdatamodeld/<Name>.xcdatamodel/contents
file.
This file contains an entry "sourceLanguage" that (by default) might have been set to "Swift". Change it to "Objective-C".
You can use the && symbol between commands to execute the second command only if the first succeeds. More info here http://commandwindows.com/command1.htm
'\r' = carriage return and '\n' = line feed.
In fact, there are some different behaviors when you use them in different OSes. On Unix it is '\n', but it is '\r''\n' on Windows.
Add the following dependencies
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.7</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.7</version>
</dependency>
Modify request as follows
$.ajax({
url:urlName,
type:"POST",
contentType: "application/json; charset=utf-8",
data: jsonString, //Stringified Json Object
async: false, //Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation
cache: false, //This will force requested pages not to be cached by the browser
processData:false, //To avoid making query String instead of JSON
success: function(resposeJsonObject){
// Success Message Handler
}
});
Controller side
@RequestMapping(value = urlPattern , method = RequestMethod.POST)
public @ResponseBody Person save(@RequestBody Person jsonString) {
Person person=personService.savedata(jsonString);
return person;
}
@RequestBody
- Covert Json object to java
@ResponseBody
- convert Java object to json
General Syntax:
7z a archive_name target parameters
Check your 7-Zip dir. Depending on the release you have, 7z may be replaced with 7za in the syntax.
Parameters:
Eg. This will prompt for a PW and hide file structures:
7z a archive_name target -p -mhe=on
Eg. No prompt, visible file structure:
7z a archive_name target -pPUT_PASSWORD_HERE
And so on. If you leave target blank, 7z will assume * in current directory and it will recurs directories by default.
if it is 64bit them - C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell**3.0**
and version could be different
Run this convenient SQL query to see running MySQL queries. It can be run from any environment you like, whenever you like, without any code changes or overheads. It may require some MySQL permissions configuration, but for me it just runs without any special setup.
SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST WHERE COMMAND != 'Sleep';
The only catch is that you often miss queries which execute very quickly, so it is most useful for longer-running queries or when the MySQL server has queries which are backing up - in my experience this is exactly the time when I want to view "live" queries.
You can also add conditions to make it more specific just any SQL query.
e.g. Shows all queries running for 5 seconds or more:
SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST WHERE COMMAND != 'Sleep' AND TIME >= 5;
e.g. Show all running UPDATEs:
SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST WHERE COMMAND != 'Sleep' AND INFO LIKE '%UPDATE %';
For full details see: http://dev.mysql.com/doc/refman/5.1/en/processlist-table.html
Simply running
sc.getConf().getAll()
should give you a list with all settings.
.youtube-thumb img {display:block;} or .youtube-thumb img {float:left;}
I don't think this is quite what your looking for, there's no way to display variable values that don't fail, but this may help you get closer to outputting the results the way you want.
You can use the TestResult object returned by the TestRunner.run() for results analysis and processing. Particularly, TestResult.errors and TestResult.failures
About the TestResults Object:
http://docs.python.org/library/unittest.html#id3
And some code to point you in the right direction:
>>> import random
>>> import unittest
>>>
>>> class TestSequenceFunctions(unittest.TestCase):
... def setUp(self):
... self.seq = range(5)
... def testshuffle(self):
... # make sure the shuffled sequence does not lose any elements
... random.shuffle(self.seq)
... self.seq.sort()
... self.assertEqual(self.seq, range(10))
... def testchoice(self):
... element = random.choice(self.seq)
... error_test = 1/0
... self.assert_(element in self.seq)
... def testsample(self):
... self.assertRaises(ValueError, random.sample, self.seq, 20)
... for element in random.sample(self.seq, 5):
... self.assert_(element in self.seq)
...
>>> suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
>>> testResult = unittest.TextTestRunner(verbosity=2).run(suite)
testchoice (__main__.TestSequenceFunctions) ... ERROR
testsample (__main__.TestSequenceFunctions) ... ok
testshuffle (__main__.TestSequenceFunctions) ... FAIL
======================================================================
ERROR: testchoice (__main__.TestSequenceFunctions)
----------------------------------------------------------------------
Traceback (most recent call last):
File "<stdin>", line 11, in testchoice
ZeroDivisionError: integer division or modulo by zero
======================================================================
FAIL: testshuffle (__main__.TestSequenceFunctions)
----------------------------------------------------------------------
Traceback (most recent call last):
File "<stdin>", line 8, in testshuffle
AssertionError: [0, 1, 2, 3, 4] != [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
----------------------------------------------------------------------
Ran 3 tests in 0.031s
FAILED (failures=1, errors=1)
>>>
>>> testResult.errors
[(<__main__.TestSequenceFunctions testMethod=testchoice>, 'Traceback (most recent call last):\n File "<stdin>"
, line 11, in testchoice\nZeroDivisionError: integer division or modulo by zero\n')]
>>>
>>> testResult.failures
[(<__main__.TestSequenceFunctions testMethod=testshuffle>, 'Traceback (most recent call last):\n File "<stdin>
", line 8, in testshuffle\nAssertionError: [0, 1, 2, 3, 4] != [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n')]
>>>
You can definitely use the section tag as a container. It is there to group content in a more semantically significant way than with a div or as the html5 spec says:
The section element represents a generic section of a document or application. A section, in this context, is a thematic grouping of content, typically with a heading. http://www.w3.org/TR/html5/sections.html#the-section-element
use this
android:background="@drawable/ic_play_arrow_black_24dp"
just set the background to the icon you want to center
import React, { useState } from "react"
const inputTextValue = ({ initialValue }) => {
const [value, setValue] = useState(initialValue);
return {
value,
onChange: (e) => { setValue(e.target.value) }
};
};
export default () => {
const textValue = inputTextValue("");
return (<>
<input {...textValue} />
</>
);
}
/*"Solution I Tired Changed Name of Funtion in Captial "*/
import React, { useState } from "react"
const InputTextValue = ({ initialValue }) => {
const [value, setValue] = useState(initialValue);
return {
value,
onChange: (e) => { setValue(e.target.value) }
};
};
export default () => {
const textValue = InputTextValue("");
return (<>
<input {...textValue} />
</>
);
}
You can also customize the card theme globally with ThemeData.cardTheme
:
MaterialApp(
title: 'savvy',
theme: ThemeData(
cardTheme: CardTheme(
shape: RoundedRectangleBorder(
borderRadius: const BorderRadius.all(
Radius.circular(8.0),
),
),
),
// ...
In Java, char is technically a "16-bit integer", so you can simply cast it to int and you'll get it's code. From Oracle:
The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
So you can simply cast it to int.
char registered = '®';
System.out.println(String.format("This is an int-code: %d", (int) registered));
System.out.println(String.format("And this is an hexa code: %x", (int) registered));
I had a similar issue when migrating over to React-Router v4 so I'll try to explain my solution below.
Please do not consider this answer as the right way to solve the problem, I imagine there's a good chance something better will arise as React Router v4 becomes more mature and leaves beta (It may even already exist and I just didn't discover it).
For context, I had this problem because I occasionally use Redux-Saga
to programmatically change the history object (say when a user successfully authenticates).
In the React Router docs, take a look at the <Router>
component and you can see you have the ability to pass your own history object via a prop. This is the essence of the solution - we supply the history object to React-Router
from a global module.
yarn add history
or npm install history --save
create a file called history.js
in your App.js
level folder (this was my preference)
// src/history.js
import createHistory from 'history/createBrowserHistory';
export default createHistory();`
Add this history object to your Router component like so
// src/App.js
import history from '../your/path/to/history.js;'
<Router history={history}>
// Route tags here
</Router>
Adjust the URL just like before by importing your global history object:
import history from '../your/path/to/history.js;'
history.push('new/path/here/');
Everything should stay synced up now, and you also have access to a way of setting the history object programmatically and not via a component/container.
I have not tried this option, but the following information is given in the vim help system (i.e. help eol):
'endofline' 'eol' boolean (default on)
local to buffer
{not in Vi}
When writing a file and this option is off and the 'binary' option
is on, no <EOL> will be written for the last line in the file. This
option is automatically set when starting to edit a new file, unless
the file does not have an <EOL> for the last line in the file, in
which case it is reset.
Normally you don't have to set or reset this option. When 'binary' is off the value is not used when writing the file. When 'binary' is on it is used to remember the presence of a for the last line in the file, so that when you write the file the situation from the original file can be kept. But you can change it if you want to.
You may be interested in the answer to a previous question as well: "Why should files end with a newline".
There are two options here.
Edit
@Html.Hidden("clubid", ViewBag.Club.id)
or
@using(Html.BeginForm("action", "controller",
new { clubid = @Viewbag.Club.id }, FormMethod.Post, null)
you can remove this alert by doing following:
<input type="text" pattern="[a-zA-Z]+"
oninvalid="setCustomValidity(' ')"
/>
just set the custom message to one blank space
The git remote show <origin name>
command will list all branches (including un-tracked branches). Then you can find the remote branch name that you need to fetch.
Example:
$ git remote show origin
Use these steps to fetch remote branches:
git fetch <origin name> <remote branch name>:<local branch name>
git checkout <local branch name > (local branch name should the name that you given fetching)
Example:
$ git fetch origin test:test
$ git checkout test
int x;
ifile >> x
while (!iFile.eof())
{
cerr << x << endl;
iFile >> x;
}
Upon investigation, it's also worth noting that when you want to start using docker in a new terminal window, the correct command is:
$(boot2docker shellinit)
I had tested these commands:
>> docker info
Get http:///var/run/docker.sock/v1.15/info: dial unix /var/run/docker.sock: no such file or directory
>> boot2docker shellinit
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/ca.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/cert.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/key.pem
export DOCKER_HOST=tcp://192.168.59.103:2376
export DOCKER_CERT_PATH=/Users/ddavison/.boot2docker/certs/boot2docker-vm
export DOCKER_TLS_VERIFY=1
>> docker info
Get http:///var/run/docker.sock/v1.15/info: dial unix /var/run/docker.sock: no such file or directory
Notice that docker info returned that same error. however.. when using $(boot2docker shellinit)
...
>> $(boot2docker init)
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/ca.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/cert.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/key.pem
>> docker info
Containers: 3
...
If you read the help file for ?boxplot
, you'll see there is a names=
parameter.
boxplot(apple, banana, watermelon, names=c("apple","banana","watermelon"))
In HTML you can specify a mailto:
address in the <form>
element's [action]
attribute.
<form action="mailto:[email protected]" method="GET">
<input name="subject" type="text" />
<textarea name="body"></textarea>
<input type="submit" value="Send" />
</form>
What this will do is allow the user's email client to create an email prepopulated with the fields in the <form>
.
What this will not do is send an email.
Remove the following hot fixes and updates
Restart the PC and try to uninstall now. This worked for me without problems.
If you don't want to use any libraries and you have reoccurrences in your data, you can use which
with sapply
as well.
new_order <- sapply(target, function(x,df){which(df$name == x)}, df=df)
df <- df[new_order,]
Just query the "memberOf" property and iterate though the return, example:
search.PropertiesToLoad.Add("memberOf");
StringBuilder groupNames = new StringBuilder(); //stuff them in | delimited
SearchResult result = search.FindOne();
int propertyCount = result.Properties["memberOf"].Count;
String dn;
int equalsIndex, commaIndex;
for (int propertyCounter = 0; propertyCounter < propertyCount;
propertyCounter++)
{
dn = (String)result.Properties["memberOf"][propertyCounter];
equalsIndex = dn.IndexOf("=", 1);
commaIndex = dn.IndexOf(",", 1);
if (-1 == equalsIndex)
{
return null;
}
groupNames.Append(dn.Substring((equalsIndex + 1),
(commaIndex - equalsIndex) - 1));
groupNames.Append("|");
}
return groupNames.ToString();
This just stuffs the group names into the groupNames string, pipe delimited, but when you spin through you can do whatever you want with them
Math.Floor()
rounds toward negative infinity
Math.Truncate
rounds up or down towards zero.
For example:
Math.Floor(-3.4) = -4
Math.Truncate(-3.4) = -3
while
Math.Floor(3.4) = 3
Math.Truncate(3.4) = 3
If you are curious as to which is the most performant check this out where I compare all the different Number -> String conversions.
Looks like 2+''
or 2+""
are the fastest.
A much simpler solution would be to download the file using Chrome. In this manner you don't have to manually click on the save button.
using System;
using System.Diagnostics;
using System.ComponentModel;
namespace MyProcessSample
{
class MyProcess
{
public static void Main()
{
Process myProcess = new Process();
myProcess.Start("chrome.exe","http://www.com/newfile.zip");
}
}
}
First of all realise it is impossible to completely prevent a video being downloaded, all you can do is make it more difficult. I.e. you hide the source of the video.
A web browser temporarily downloads the video in a buffer, so if could prevent download you would also be preventing the video being viewed as well.
You should also know that <1% of the total population of the world will be able to understand the source code making it rather safe anyway. That does not mean you should not hide it in the source as well - you should.
You should not disable right click, and even less you should display a message saying "You cannot save this video for copyright reasons. Sorry about that."
. As suggested in this answer.
This can be very annoying and confusing for the user. Apart from that; if they disable JavaScript on their browser they will be able to right click and save anyway.
Here is a CSS trick you could use:
video {
pointer-events: none;
}
CSS cannot be turned off in browser, protecting your video without actually disabling right click. However one problem is that controls
cannot be enabled either, in other words they must be set to false
. If you are going to inplament your own Play/Pause function or use an API that has buttons separate to the video
tag then this is a feasible option.
controls
also has a download button so using it is not such a good idea either.
Here is a JSFiddle example.
If you are going to disable right click using JavaScript then also store the source of the video in JavaScript as well. That way if the user disables JavaScript (allowing right click) the video will not load (it also hides the video source a little better).
From TxRegex answer:
<video oncontextmenu="return false;" controls>
<source type="video/mp4" id="video">
</video>
Now add the video via JavaScript:
document.getElementById("video").src = "https://www.w3schools.com/html/mov_bbb.mp4";
Functional JSFiddle
Another way to prevent right click involves using the embed
tag. This is does not however provide the controls to run the video so they would need to be inplamented in JavaScript:
<embed src="https://www.w3schools.com/html/mov_bbb.mp4"></embed>
As stated above, there are a couple of different problems possible. What we found is that the .DLL for the WCF library had been added as a reference to the client project. This, in turn, created problems with resolving the objects and thus caused the files to be "emptied" by code generation steps. While unchecking the use "Reuse Types..." can seem like an answer, it creates extra definitions of object types, which are proxies to the real types, in a new name space, which then causes all kinds of "compatibility" issues with the use of those types. Only if you really want to "hide" a type should you check this option.
Hiding the type would be appropriate when you don't want a "DLL" type dependency to "leak" into a project that you are trying to keep segregated from another. If the DLL for the WCF library project creeps into the client project references, then you will have this problem with all kinds of strange side effects since the type definitions are also in the DLL.
What is the len
of the equivalent nested list?
len([[2,3,1,0], [2,3,1,0], [3,2,1,1]])
With the more general concept of shape
, numpy
developers choose to implement __len__
as the first dimension. Python maps len(obj)
onto obj.__len__
.
X.shape
returns a tuple, which does have a len
- which is the number of dimensions, X.ndim
. X.shape[i]
selects the ith
dimension (a straight forward application of tuple indexing).
Use this way so that result will not be displayed while running stored procedure.
The query:
SELECT a.strUserID FROM tblUsers a WHERE a.lngUserID = lngUserID LIMIT 1 INTO @strUserID;
<script language="javascript" type="text/javascript">
function fixedlength(textboxID, keyEvent, maxlength) {
//validation for digits upto 'maxlength' defined by caller function
if (textboxID.value.length > maxlength) {
textboxID.value = textboxID.value.substr(0, maxlength);
}
else if (textboxID.value.length < maxlength || textboxID.value.length == maxlength) {
textboxID.value = textboxID.value.replace(/[^\d]+/g, '');
return true;
}
else
return false;
}
</script>
<asp:TextBox ID="txtNextVisit" runat="server" MaxLength="2" onblur="return fixedlength(this, event, 2);" onkeypress="return fixedlength(this, event, 2);" onkeyup="return fixedlength(this, event, 2);"></asp:TextBox>
All you have to do is:
You will be able to see historical attributions (using git blame
) and full history of changes (using git log
) for both files.
Suppose you want to create a copy of file foo
called bar
. In that case the workflow you'd use would look like this:
git mv foo bar
git commit
SAVED=`git rev-parse HEAD`
git reset --hard HEAD^
git mv foo copy
git commit
git merge $SAVED # This will generate conflicts
git commit -a # Trivially resolved like this
git mv copy foo
git commit
After you execute the above commands, you end up with a revision history that looks like this:
( revision history ) ( files )
ORIG_HEAD foo
/ \ / \
SAVED ALTERNATE bar copy
\ / \ /
MERGED bar,copy
| |
RESTORED bar,foo
When you ask Git about the history of foo
, it will:
copy
between MERGED and RESTORED,copy
came from the ALTERNATE parent of MERGED, andfoo
between ORIG_HEAD and ALTERNATE.From there it will dig into the history of foo
.
When you ask Git about the history of bar
, it will:
bar
came from the SAVED parent of MERGED, and foo
between ORIG_HEAD and SAVED.From there it will dig into the history of foo
.
It's that simple. :)
You just need to force Git into a merge situation where you can accept two traceable copies of the file(s), and we do this with a parallel move of the original (which we soon revert).
Targets
in Xcode
.Get Info
on your project's target (your current development name).Product Name
under Packaging
. Change its value to what you want your new project name to be.You can use a simple grep
to capture the number of occurrences effectively. I will use the -i
option to make sure STRING/StrING/string
get captured properly.
Command line that gives the files' name:
grep -oci string * | grep -v :0
Command line that removes the file names and prints 0 if there is a file without occurrences:
grep -ochi string *
Personally, I would use XSLT to transform the XML and remove the trailing colons. For example, suppose I have this input:
<?xml version="1.0" encoding="UTF-8"?>
<Document>
<Paragraph>This paragraph ends in a period.</Paragraph>
<Paragraph>This one ends in a colon:</Paragraph>
<Paragraph>This one has a : in the middle.</Paragraph>
</Document>
If I wanted to strip out trailing colons in my paragraphs, I would use this XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fn="http://www.w3.org/2005/xpath-functions"
version="2.0">
<!-- identity -->
<xsl:template match="/|@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!-- strip out colons at the end of paragraphs -->
<xsl:template match="Paragraph">
<xsl:choose>
<!-- if it ends with a : -->
<xsl:when test="fn:ends-with(.,':')">
<xsl:copy>
<!-- copy everything but the last character -->
<xsl:value-of select="substring(., 1, string-length(.)-1)"></xsl:value-of>
</xsl:copy>
</xsl:when>
<xsl:otherwise>
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
You can find dimension of an image on the page using something like
document.getElementById('someImage').width
file size, however, you will have to use something server-side
view:
class AddProductView(generic.TemplateView):
template_name = 'manager/add_product.html'
def get(self, request, *args, **kwargs):
form = ProductForm(self.request.GET or None, prefix="sch")
sub_form = ImageForm(self.request.GET or None, prefix="loc")
context = super(AddProductView, self).get_context_data(**kwargs)
context['form'] = form
context['sub_form'] = sub_form
return self.render_to_response(context)
def post(self, request, *args, **kwargs):
form = ProductForm(request.POST, prefix="sch")
sub_form = ImageForm(request.POST, prefix="loc")
...
template:
{% block container %}
<div class="container">
<br/>
<form action="{% url 'manager:add_product' %}" method="post">
{% csrf_token %}
{{ form.as_p }}
{{ sub_form.as_p }}
<p>
<button type="submit">Submit</button>
</p>
</form>
</div>
{% endblock %}
I wrote this answer about four years ago and my opinion hasn't changed. But since then there have been significant developments on the micro-services front. I added micro-services specific notes at the end...
I'll weigh in against the idea, with real-world experience to back up my vote.
I was brought on to a large application that had five contexts for a single database. In the end, we ended up removing all of the contexts except for one - reverting back to a single context.
At first the idea of multiple contexts seems like a good idea. We can separate our data access into domains and provide several clean lightweight contexts. Sounds like DDD, right? This would simplify our data access. Another argument is for performance in that we only access the context that we need.
But in practice, as our application grew, many of our tables shared relationships across our various contexts. For example, queries to table A in context 1 also required joining table B in context 2.
This left us with a couple poor choices. We could duplicate the tables in the various contexts. We tried this. This created several mapping problems including an EF constraint that requires each entity to have a unique name. So we ended up with entities named Person1 and Person2 in the different contexts. One could argue this was poor design on our part, but despite our best efforts, this is how our application actually grew in the real world.
We also tried querying both contexts to get the data we needed. For example, our business logic would query half of what it needed from context 1 and the other half from context 2. This had some major issues. Instead of performing one query against a single context, we had to perform multiple queries across different contexts. This has a real performance penalty.
In the end, the good news is that it was easy to strip out the multiple contexts. The context is intended to be a lightweight object. So I don't think performance is a good argument for multiple contexts. In almost all cases, I believe a single context is simpler, less complex, and will likely perform better, and you won't have to implement a bunch of work-arounds to get it to work.
I thought of one situation where multiple contexts could be useful. A separate context could be used to fix a physical issue with the database in which it actually contains more than one domain. Ideally, a context would be one-to-one to a domain, which would be one-to-one to a database. In other words, if a set of tables are in no way related to the other tables in a given database, they should probably be pulled out into a separate database. I realize this isn't always practical. But if a set of tables are so different that you would feel comfortable separating them into a separate database (but you choose not to) then I could see the case for using a separate context, but only because there are actually two separate domains.
Regarding micro-services, one single context still makes sense. However, for micro-services, each service would have its own context which includes only the database tables relevant to that service. In other words, if service x accesses tables 1 and 2, and service y accesses tables 3 and 4, each service would have its own unique context which includes tables specific to that service.
I'm interested in your thoughts.
I found a fix...
.text {
font-size: 15px; /* for firefox */
*font-size: 90%; /* % restart the antialiasing for ie, note the * hack */
font-weight: bold; /* needed, don't know why! */
}
This works for me:
string value = System.Configuration.ConfigurationManager.AppSettings[key];
You can set UINavigation Background color by using this code in any view controller
self.navigationController.navigationBar.backgroundColor = [UIColor colorWithRed:10.0f/255.0f green:30.0f/255.0f blue:200.0f/255.0f alpha:1.0f];
we can do like this:
in application.yml:
spring:
profiles:
active: test //modify here to switch between environments
include: application-${spring.profiles.active}.yml
in application-test.yml:
server:
port: 5000
and in application-local.yml:
server:
address: 0.0.0.0
port: 8080
then spring boot will start our app as we wish to.
Check the encoding in which you are generating the file, to make excel display the file correctly you must use the system default codepage.
Wich language are you using? if it's .Net you only need to use Encoding.Default while generating the file.
This command actually works
\curl -L https://get.rvm.io | bash -s stable --ruby
To hide warnings, you can also do
{r, warning=FALSE}
Actually you can also make the Junit test a runnable Jar and call the runnable jar as java -jar
In my case, I got the error on the setState line:
increment(){
this.setState(state => {
count: state.count + 1
});
}
I changed it to this, now it works
increment(){
this.setState(state => {
const count = state.count + 1
return {
count
};
});
}
Same principle as the solutions above. But I had issues with Firefox 52.0 (32 bit) where large files (>40 MBytes) are truncated at random positions. Re-scheduling the call of revokeObjectUrl() fixes this issue.
function saveFile(blob, filename) {
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, filename);
} else {
const a = document.createElement('a');
document.body.appendChild(a);
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = filename;
a.click();
setTimeout(() => {
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
}, 0)
}
}
The {% csrf_token %}
put in html templates inside <form></form>
translates to something like:
<input type='hidden' name='csrfmiddlewaretoken' value='Sdgrw2HfynbFgPcZ5sjaoAI5zsMZ4wZR' />
so why not just grep it in your JS like this:
token = $("#change_password-form").find('input[name=csrfmiddlewaretoken]').val()
and then pass it e.g doing some POST, like:
$.post( "/panel/change_password/", {foo: bar, csrfmiddlewaretoken: token}, function(data){
console.log(data);
});
Eg:
Datatable newTable = new DataTable();
foreach(string s1 in list)
{
if (s1 != string.Empty) {
dvProducts.RowFilter = "(CODE like '" + serachText + "*') AND (CODE <> '" + s1 + "')";
foreach(DataRow dr in dvProducts.ToTable().Rows)
{
newTable.ImportRow(dr);
}
}
}
ListView1.DataSource = newTable;
ListView1.DataBind();
The best way to access files from resource folder inside a jar is it to use the InputStream via getResourceAsStream
. If you still need a the resource as a file instance you can copy the resource as a stream into a temporary file (the temp file will be deleted when the JVM exits):
public static File getResourceAsFile(String resourcePath) {
try {
InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(resourcePath);
if (in == null) {
return null;
}
File tempFile = File.createTempFile(String.valueOf(in.hashCode()), ".tmp");
tempFile.deleteOnExit();
try (FileOutputStream out = new FileOutputStream(tempFile)) {
//copy stream
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
return tempFile;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Since after the pdf file is loaded, the iframe document will have a new DOM element <embed/>
, so we can do the check like this:
window.onload = function () {
//creating an iframe element
var ifr = document.createElement('iframe');
document.body.appendChild(ifr);
// making the iframe fill the viewport
ifr.width = '100%';
ifr.height = window.innerHeight;
// continuously checking to see if the pdf file has been loaded
self.interval = setInterval(function () {
if (ifr && ifr.contentDocument && ifr.contentDocument.readyState === 'complete' && ifr.contentDocument.embeds && ifr.contentDocument.embeds.length > 0) {
clearInterval(self.interval);
console.log("loaded");
//You can do print here: ifr.contentWindow.print();
}
}, 100);
ifr.src = src;
}
The recursive function is a function which calls by itself
It allows programmers to write efficient programs using a minimal amount of code.
The downside is that they can cause infinite loops and other unexpected results if not written properly.
I will explain both Simple Recursive function and Tail Recursive function
In order to write a Simple recursive function
From the given example:
public static int fact(int n){
if(n <=1)
return 1;
else
return n * fact(n-1);
}
From the above example
if(n <=1)
return 1;
Is the deciding factor when to exit the loop
else
return n * fact(n-1);
Is the actual processing to be done
Let me the break the task one by one for easy understanding.
Let us see what happens internally if I run fact(4)
public static int fact(4){
if(4 <=1)
return 1;
else
return 4 * fact(4-1);
}
If
loop fails so it goes to else
loop
so it returns 4 * fact(3)
In stack memory, we have 4 * fact(3)
Substituting n=3
public static int fact(3){
if(3 <=1)
return 1;
else
return 3 * fact(3-1);
}
If
loop fails so it goes to else
loop
so it returns 3 * fact(2)
Remember we called ```4 * fact(3)``
The output for fact(3) = 3 * fact(2)
So far the stack has 4 * fact(3) = 4 * 3 * fact(2)
In stack memory, we have 4 * 3 * fact(2)
Substituting n=2
public static int fact(2){
if(2 <=1)
return 1;
else
return 2 * fact(2-1);
}
If
loop fails so it goes to else
loop
so it returns 2 * fact(1)
Remember we called 4 * 3 * fact(2)
The output for fact(2) = 2 * fact(1)
So far the stack has 4 * 3 * fact(2) = 4 * 3 * 2 * fact(1)
In stack memory, we have 4 * 3 * 2 * fact(1)
Substituting n=1
public static int fact(1){
if(1 <=1)
return 1;
else
return 1 * fact(1-1);
}
If
loop is true
so it returns 1
Remember we called 4 * 3 * 2 * fact(1)
The output for fact(1) = 1
So far the stack has 4 * 3 * 2 * fact(1) = 4 * 3 * 2 * 1
Finally, the result of fact(4) = 4 * 3 * 2 * 1 = 24
The Tail Recursion would be
public static int fact(x, running_total=1) {
if (x==1) {
return running_total;
} else {
return fact(x-1, running_total*x);
}
}
public static int fact(4, running_total=1) {
if (x==1) {
return running_total;
} else {
return fact(4-1, running_total*4);
}
}
If
loop fails so it goes to else
loop
so it returns fact(3, 4)
In stack memory, we have fact(3, 4)
Substituting n=3
public static int fact(3, running_total=4) {
if (x==1) {
return running_total;
} else {
return fact(3-1, 4*3);
}
}
If
loop fails so it goes to else
loop
so it returns fact(2, 12)
In stack memory, we have fact(2, 12)
Substituting n=2
public static int fact(2, running_total=12) {
if (x==1) {
return running_total;
} else {
return fact(2-1, 12*2);
}
}
If
loop fails so it goes to else
loop
so it returns fact(1, 24)
In stack memory, we have fact(1, 24)
Substituting n=1
public static int fact(1, running_total=24) {
if (x==1) {
return running_total;
} else {
return fact(1-1, 24*1);
}
}
If
loop is true
so it returns running_total
The output for running_total = 24
Finally, the result of fact(4,1) = 24
Use DATE_ADD function
DATE_ADD(datecolumn, INTERVAL 30 MINUTE);
Android Studio on Windows 8:
C:\Users\username\AppData\Local\Android\sdk\extras\intel\Hardware_Accelerated_Execution_Manager\intelhaxm-android.exe
(in username : please enter valid username)
Install it and restart your Android Studio.
The above steps are similar for win 7 and also same for eclipse.
Update: Windows 10 (similar steps) - pointed out by RBT
To answer the question:
What is the fastest way to stream live video using JavaScript? Is WebSockets over TCP a fast enough protocol to stream a video of, say, 30fps?
Yes, Websocket can be used to transmit over 30 fps and even 60 fps.
The main issue with Websocket is that it is low-level and you have to deal with may other issues than just transmitting video chunks. All in all it's a great transport for video and also audio.
gacutil comes with Visual Studio, not with VSTS. It is part of Windows SDK and can be download separately at http://www.microsoft.com/downloads/details.aspx?FamilyId=F26B1AA4-741A-433A-9BE5-FA919850BDBF&displaylang=en . This installation will have gacutil.exe
included. But first check it here
C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin
you might have it installed.
As @devi mentioned
If you decide to grab gacutil files from existing installation, note that from .NET 4.0 is three files: gacutil.exe gacutil.exe.config and 1033/gacutlrc.dll
If I understand you correctly, you need to use -SearchBase:
Get-ADUser -SearchBase "OU=Accounts,OU=RootOU,DC=ChildDomain,DC=RootDomain,DC=com" -Filter *
Note that Get-ADUser defaults to using
-SearchScope Subtree
so you don't need to specify it. It's this that gives you all sub-OUs (and sub-sub-OUs, etc.).
No.
if ([[UIScreen mainScreen] bounds].size.height > 960)
on iPhone 5 is wrong
if ([[UIScreen mainScreen] bounds].size.height == 568)
You can set your cookie value containing expiry and get your expiry from cookie value.
// set
$expiry = time()+3600;
setcookie("mycookie", "mycookievalue|$expiry", $expiry);
// get
if (isset($_COOKIE["mycookie"])) {
list($value, $expiry) = explode("|", $_COOKIE["mycookie"]);
}
// Remember, some two-way encryption would be more secure in this case. See: https://github.com/qeremy/Cryptee
You need to make a second groupby object that groups by the states, and then use the div
method:
import numpy as np
import pandas as pd
np.random.seed(0)
df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
'office_id': list(range(1, 7)) * 2,
'sales': [np.random.randint(100000, 999999) for _ in range(12)]})
state_office = df.groupby(['state', 'office_id']).agg({'sales': 'sum'})
state = df.groupby(['state']).agg({'sales': 'sum'})
state_office.div(state, level='state') * 100
sales
state office_id
AZ 2 16.981365
4 19.250033
6 63.768601
CA 1 19.331879
3 33.858747
5 46.809373
CO 1 36.851857
3 19.874290
5 43.273852
WA 2 34.707233
4 35.511259
6 29.781508
the level='state'
kwarg in div
tells pandas to broadcast/join the dataframes base on the values in the state
level of the index.
You can also try by setting strictSSL to false
, like this:
{
url: "https://...",
method: "POST",
headers: {
"Content-Type": "application/json"},
strictSSL: false
}
How about this?
Map properties = new Properties();
Map<String, String> map = new HashMap<String, String>(properties);
Will cause a warning, but works without iterations.
var collections = db.getCollectionNames();
for(var i = 0; i< collections.length; i++){
print('Collection: ' + collections[i]); // print the name of each collection
db.getCollection(collections[i]).find().forEach(printjson); //and then print the json of each of its elements
}
I think this script might get what you want. It prints the name of each collection and then prints its elements in json.
This line of code might not work in IE 8 because of native support problems.
$(".hidden").attr("placeholder", "Type here to search");
You can try importing a JQuery placeholder plugin for this task. Simply import it to your libraries and initiate from the sample code below.
$('input, textarea').placeholder();
I know its old, but I've found the same issue. My project did build, I then updated Visual Studio to the latest & the project wouldnt build as it couldnt find a type definition from a separate assembly. The other assembly built OK, the main project referenced it correctly & nothing had changed since it built OK.
I cleaned the whole solution & rebuilt it, it failed. I built the assembly on its own, it built OK. The project didnt build. I cleaned & built multiple times, and it failed. I then called a colleague to look at it, when I built with him watching, it all built OK.
I think Visual Studio tooling is the problem, especially as I just updated it.
I was looking for this myself when we changed domain on our Wordpress website. It can't be done without some programming so this is what I did.
<?php
header("Content-Type: text/plain");
$host = "localhost";
$username = "root";
$password = "";
$database = "mydatabase";
$string_to_replace = 'old.example.com';
$new_string = 'new.example.com';
// Connect to database server
mysql_connect($host, $username, $password);
// Select database
mysql_select_db($database);
// List all tables in database
$sql = "SHOW TABLES FROM ".$database;
$tables_result = mysql_query($sql);
if (!$tables_result) {
echo "Database error, could not list tables\nMySQL error: " . mysql_error();
exit;
}
echo "In these fields '$string_to_replace' have been replaced with '$new_string'\n\n";
while ($table = mysql_fetch_row($tables_result)) {
echo "Table: {$table[0]}\n";
$fields_result = mysql_query("SHOW COLUMNS FROM ".$table[0]);
if (!$fields_result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($fields_result) > 0) {
while ($field = mysql_fetch_assoc($fields_result)) {
if (stripos($field['Type'], "VARCHAR") !== false || stripos($field['Type'], "TEXT") !== false) {
echo " ".$field['Field']."\n";
$sql = "UPDATE ".$table[0]." SET ".$field['Field']." = replace(".$field['Field'].", '$string_to_replace', '$new_string')";
mysql_query($sql);
}
}
echo "\n";
}
}
mysql_free_result($tables_result);
?>
Hope it helps anyone who's stumbling into this problem in the future :)
Currently, UUID's are as specified in RFC4122. An often neglected edge case is the NIL UUID, noted here. The following regex takes this into account and will return a match for a NIL UUID. See below for a UUID which only accepts non-NIL UUIDs. Both of these solutions are for versions 1 to 5 (see the first character of the third block).
Therefore to validate a UUID...
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/i
...ensures you have a canonically formatted UUID that is Version 1 through 5 and is the appropriate Variant as per RFC4122.
NOTE: Braces {
and }
are not canonical. They are an artifact of some systems and usages.
Easy to modify the above regex to meet the requirements of the original question.
HINT: regex group/captures
To avoid matching NIL UUID:
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
Had the 407 error from Android Studio. Tried adding the proxy, but nothing happened. Found out that it was related to company certificate, so I exported the one from my browser and added it to Git.
Export From Web Browser
Internet Options > Content > Certificates > Export (Follow wizard, I chose format "Base 64 encoded X.509(.CER))
In Git Bash
git config --global http.sslCAInfo c:\Utilities\Certificates\my_certificate
The following page was useful https://blogs.msdn.microsoft.com/phkelley/2014/01/20/adding-a-corporate-or-self-signed-certificate-authority-to-git-exes-store/
To add the proxy, like the other threads I used
git config --global http.proxy proxy.company.net:8080
git config --global https.proxy proxy.company.net:8080
List<string> mylist = new List<string>(new string[] { "element1", "element2", "element3" });
Create a folder named fonts in the assets folder and add the snippet from the below link.
Typeface tf = Typeface.createFromAsset(getApplicationContext().getAssets(),"fonts/fontname.ttf");
textview.setTypeface(tf);
They all attach this into function (or object) and the difference is in the function invocation (see below).
call attaches this into function and executes the function immediately:
var person = {
name: "James Smith",
hello: function(thing) {
console.log(this.name + " says hello " + thing);
}
}
person.hello("world"); // output: "James Smith says hello world"
person.hello.call({ name: "Jim Smith" }, "world"); // output: "Jim Smith says hello world"
bind attaches this into function and it needs to be invoked separately like this:
var person = {
name: "James Smith",
hello: function(thing) {
console.log(this.name + " says hello " + thing);
}
}
person.hello("world"); // output: "James Smith says hello world"
var helloFunc = person.hello.bind({ name: "Jim Smith" });
helloFunc("world"); // output: Jim Smith says hello world"
or like this:
...
var helloFunc = person.hello.bind({ name: "Jim Smith" }, "world");
helloFunc(); // output: Jim Smith says hello world"
apply is similar to call except that it takes an array-like object instead of listing the arguments out one at a time:
function personContainer() {
var person = {
name: "James Smith",
hello: function() {
console.log(this.name + " says hello " + arguments[1]);
}
}
person.hello.apply(person, arguments);
}
personContainer("world", "mars"); // output: "James Smith says hello mars", note: arguments[0] = "world" , arguments[1] = "mars"
Make this entry in dimens
<!--Floating action button-->
<dimen name="design_fab_image_size" tools:override="true">36dp</dimen>
Here 36dp is icon size on floating point button. This will set 36dp size for all icons for floating action button.
Updates As Per Comments
If you want to set icon size to particular Floating Action Button just go with Floating action button attributes like app:fabSize="normal" and android:scaleType="center".
<!--app:fabSize decides size of floating action button You can use normal, auto or mini as per need-->
app:fabSize="normal"
<!--android:scaleType decides how the icon drawable will be scaled on Floating action button. You can use center(to show scr image as original), fitXY, centerCrop, fitCenter, fitEnd, fitStart, centerInside.-->
android:scaleType="center"
<div id="cntnr">
<div class="tableHeader">
<table class="table-header table table-striped table-bordered">
<thead>
<tr>
<th>this</th>
<th>transmission</th>
<th>is</th>
<th>coming</th>
<th>to</th>
<th>you</th>
</tr>
</thead>
<tbody>
<tr>
<td>we've got it...</td>
<td>alright you are go</td>
<td>uh, we see the Earth now</td>
<td>we've got it...</td>
<td>alright you are go</td>
<td>uh, we see the Earth now</td>
</tr>
</tbody>
</table>
</div>
<div class="tableBody">
<table class="table-body table table-striped table-bordered">
<thead>
<tr>
<th>this</th>
<th>transmission</th>
<th>is</th>
<th>coming</th>
<th>to</th>
<th>you</th>
</tr>
</thead>
<tbody>
<tr>
<td>we've got it...</td>
<td>alright you are go</td>
<td>uh, we see the Earth now</td>
<td>we've got it...</td>
<td>alright you are go</td>
<td>uh, we see the Earth now</td>
</tr>
</tbody>
</table>
</div>
</div>
#cntnr {
width: auto;
height: 200px;
border: solid 1px #444;
overflow: auto;
}
.tableHeader {
position: fixed;
height: 40px;
overflow: hidden;
margin-right: 18px;
background: white;
}
.table-header tbody {
height: 0;
visibility: hidden;
}
.table-body thead {
height: 0;
visibility: hidden;
}
http://jsfiddle.net/cCarlson/L98m854d/
Drawback: The fixed header structure/logic is fairly dependent upon specific dimensions, so abstraction is probably not a viable option.
It bothered me too much while updating node version from 8.1.0 to 10.14.0
Here is what worked for me:
Open terminal (Ctrl+Alt+T).
Type which node
, which will give a path something like /usr/local/bin/node
Run the command sudo rm /usr/local/bin/node
to remove the binary (adjust the path according to what you found in step 2). Now node -v
shows you have no node version
Download a script and run it to set up the environment:
curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
Install using sudo apt-get install nodejs
Note: If you are getting error like
node /usr/bin/env: node: No such file or directory
just run
ln -s /usr/bin/nodejs /usr/bin/node
Now node -v
will give v10.14.0
Worked for me.
var scrollBottom = $(window).scrollTop() + $(window).height();
Is the value of your particular COMMENT column null?
Sometimes NOT LIKE doesn't know how to behave properly around nulls.
This means that you are doing a foreach on something that is not an array.
Check out all your foreach statements, and look if the thing before the as
, to make sure it is actually an array. Use var_dump
to dump it.
Then fix the one where it isn't an array.
How to reproduce this error:
<?php
$skipper = "abcd";
foreach ($skipper as $item){ //the warning happens on this line.
print "ok";
}
?>
Make sure $skipper
is an array.
If the directory is passed as a relative path and you will need to convert it to an absolute path before calling find. In the following example, the directory is passed as the first parameter to the script:
#!/bin/bash
# get absolute path
directory=`cd $1; pwd`
# print out list of files and directories
find $directory
Hide scroll bar, but while still being able to scroll using CSS
To hide the scrollbar use -webkit- because it is supported by major browsers (Google Chrome, Safari or newer versions of Opera). There are many other options for the other browsers which are listed below:
-webkit- (Chrome, Safari, newer versions of Opera):
.element::-webkit-scrollbar { width: 0 !important }
-moz- (Firefox):
.element { overflow: -moz-scrollbars-none; }
-ms- (Internet Explorer +10):
.element { -ms-overflow-style: none; }
ref: https://www.geeksforgeeks.org/hide-scroll-bar-but-while-still-being-able-to-scroll-using-css/
Besides the powerful options on the "Run Configurations.." on a well configured project you'll see the maven tasks on the Run As as well.
If you're going to say that HTML is a programming language, then you might as well include things such as word documents, as they too are based on ML, or 'Markup Language'.
So, no, HTML is a not a programming language. It is called "markup" for that reason.
Simply put--HTML defines content!
If You are creating table in mysql then use following :
create table package_template_mapping (
mapping_id int(10) not null auto_increment ,
template_id int(10) NOT NULL ,
package_id int(10) NOT NULL ,
remark varchar(100),
primary key (mapping_id) ,
UNIQUE KEY template_fun_id (template_id , package_id)
);
Your query apparently returned all correct dates, even considering the time.
If you're still not happy with the results, give DATEDIFF a shot and look for negaive/positive results between the two dates.
Make sure your mydate
column is a datetime
type.
There is a plugin for that, jquery-formatcurrency.
You can set the decimal separator (default .
) and currency symbol (default $
) for custom formatting or use the built in International Support. The format for Bahasa Indonesia (Indonesia) - Indonesian (Indonesia) coded id-ID looks closest to what you have provided.
Here's a way:
<html>
<head>
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var value = $('input[type="hidden"]')[0].value;
alert(value.split(/\?/)[1]);
});
</script>
</head>
<body>
<input type="hidden" value="/TEST/Name?3" />
</body>
</html>
The .cpp
file is configured to use precompiled header, therefore it must be included first (before iostream). For Visual Studio, it's name is usually "stdafx.h".
If there are no stdafx* files in your project, you need to go to this file's options and set it as “Not using precompiled headers”.
If your Activity extends ListActivity, you can simply override the OnListItemClick()
method like so:
/** {@inheritDoc} */
@Override
protected void onListItemClick(ListView l, View v, int pos, long id) {
super.onListItemClick(l, v, pos, id);
// TODO : Logic
}
Arrays are probably one of those things that can only be evaluated at runtime. Constants must be evaluated at compile time. Try using "readonly" instead of "const".
((http?|https|ftp|file)://)?((W|w){3}.)?[a-zA-Z0-9]+\.[a-zA-Z]+
check here:- https://www.freeformatter.com/java-regex-tester.html#ad-output
It sorts out theses entries correctly
You want the gcc
-specific noinline
attribute.
This function attribute prevents a function from being considered for inlining. If the function does not have side-effects, there are optimizations other than inlining that causes function calls to be optimized away, although the function call is live. To keep such calls from being optimized away, put
asm ("");
Use it like this:
void __attribute__ ((noinline)) foo()
{
...
}
You can use SVGs to connect two divs using only HTML and CSS:
<div id="div1" style="width: 100px; height: 100px; top:0; left:0; background:#777; position:absolute;"></div>
<div id="div2" style="width: 100px; height: 100px; top:300px; left:300px; background:#333; position:absolute;"></div>
(please use seperate css file for styling)
Create a svg line and use this line to connect above divs
<svg width="500" height="500"><line x1="50" y1="50" x2="350" y2="350" stroke="black"/></svg>
where,
x1,y1 indicates center of first div and
x2,y2 indicates center of second div
You can check how it looks in the snippet below
<div id="div1" style="width: 100px; height: 100px; top:0; left:0; background:#777; position:absolute;"></div>_x000D_
<div id="div2" style="width: 100px; height: 100px; top:300px; left:300px; background:#333; position:absolute;"></div>_x000D_
_x000D_
<svg width="500" height="500"><line x1="50" y1="50" x2="350" y2="350" stroke="black"/></svg>
_x000D_
Err, what about just calling Directory.Delete(path, true);
?
Alternatively to information_schema
it is possible to use pg_tables
:
select * from pg_tables where schemaname='public';
When the browser puts something in its cache, it also stores the Last-Modified
or ETag
header from the server.
The browser then sends a request with the If-Modified-Since
or If-None-Match
header, telling the server to send a 304 if the content still has that date or ETag.
The server needs some way of calculating a date-modified or ETag for each version of each resource; this typically comes from the filesystem or a separate database column.
Such is how I have it embedded and outputted to my HTML web page:
<div class="container">
<p class="text-center">Copyright ©
<script>
var CurrentYear = new Date().getFullYear()
document.write(CurrentYear)
</script>
</p>
</div>
Output to HTML page is as follows:
Copyright © 2018
Just put a
List<Person>
into the ViewBag and in the View cast it back to List
Try LIKE
construction, e.g. (assuming StudentId
is of type Char
, VarChar
etc.)
select *
from Students
where StudentId like '%' || TEXT || '%' -- <- TEXT - text to contain
Do you want the item in the list or the actual item itself (would assume the item itself).
Here are a bunch of options for you:
string result = _list.First(s => s == search);
string result = (from s in _list
where s == search
select s).Single();
string result = _list.Find(search);
int result = _list.IndexOf(search);
I think that the the align="center"
aligns the content, so if you wanted to use that method, you would need to use it in a 'wraper' div - a div that just wraps the rest.
text-align
is doing a similar sort of thing.
left:50%
is ignored unless you set the div's position to be something like relative or absolute.
The generally accepted methods is to use the following properties
width:500px; // this can be what ever unit you want, you just have to define it
margin-left:auto;
margin-right:auto;
the margins being auto means they grow/shrink to match the browser window (or parent div)
UPDATE
Thanks to Meo for poiting this out, if you wanted to you could save time and use the short hand propery for the margin.
margin:0 auto;
this defines the top and bottom as 0 (as it is zero it does not matter about lack of units) and the left and right get defined as 'auto' You can then, if you wan't override say the top margin as you would with any other CSS rules.
Most Recent working method:
getColor(R.color.snackBarAction)
Lists are mutable. whereas tuples are immutable. Accessing an offset element with index makes more sense in tuples than lists, Because the elements and their index cannot be changed.
use this method before show
public static ViewGroup getActivityFirstLayout(Context ctx)
{
return (ViewGroup)((ViewGroup) ActivityMaster.getActivity(ctx).findViewById(android.R.id.content)).getChildAt(0);
}
private boolean activityIsOk(Activity activity)
{
boolean s1 = !(activity == null || activity.isFinishing());
if(s1)
{
View v = LayoutMaster.getActivityFirstLayout(activity);
return v.isShown() && ViewCompat.isLaidOut(v);
}
return false;
}
From here:
http://www.christianengvall.se/undo-pushed-merge-git/
git revert -m 1 <merge commit hash>
Git revert adds a new commit that rolls back the specified commit.
Using -m 1 tells it that this is a merge and we want to roll back to the parent commit on the master branch. You would use -m 2 to specify the develop branch.
Like well explained in the link below, an identifying relation is somewhat like a weak entity type relation to its parent in the ER conceptual model. UML style CADs for data modeling do not use ER symbols or concepts, and the kind of relations are: identifying, non-identifying and non-specific.
Identifying ones are relations parent/child where the child is kind of a weak entity (even at the traditional ER model its called identifying relationship), which does not have a real primary key by its own attributes and therefore cannot be identified uniquely by its own. Every access to the child table, on the physical model, will be dependent (inclusive semantically) on the parent's primary key, which turns into part or total of the child's primary key (also being a foreign key), generally resulting in a composite key on the child side. The eventual existing keys of the child itself are only pseudo or partial-keys, not sufficient to identify any instance of that type of Entity or Entity Set, without the parent's PK.
Non-identifying relationship are the ordinary relations (partial or total), of completely independent entity sets, whose instances do not depend on each others' primary keys to be uniquely identified, although they might need foreign keys for partial or total relationships, but not as the primary key of the child. The child has its own primary key. The parent idem. Both independently. Depending on the cardinality of the relationship, the PK of one goes as a FK to the other (N side), and if partial, can be null, if total, must be not null. But, at a relationship like this, the FK will never be also the PK of the child, as when an identifying relationship is the case.
http://docwiki.embarcadero.com/ERStudioDA/XE7/en/Creating_and_Editing_Relationships
I have done that the more simple way, not as clean as it should be but it was a quick hack
$htmlContent = file_get_contents('pageURL');
// read all image tags into an array
preg_match_all('/<img[^>]+>/i',$htmlContent, $imgTags);
for ($i = 0; $i < count($imgTags[0]); $i++) {
// get the source string
preg_match('/src="([^"]+)/i',$imgTags[0][$i], $imgage);
// remove opening 'src=' tag, can`t get the regex right
$origImageSrc[] = str_ireplace( 'src="', '', $imgage[0]);
}
// will output all your img src's within the html string
print_r($origImageSrc);
var img = new Image();
img.onload = function(){
var height = img.height;
var width = img.width;
// code here to use the dimensions
}
img.src = url;
If you want to use do()
in your main method there are 2 choices because one is static but other (do()) not
new Foo().do();
static do()
methodHave a look at this sun tutorial
you can use a string formatter to pad any integer with zeros. It acts just like C's printf
.
>>> d = datetime.date.today()
>>> '%02d' % d.month
'03'
Updated for py36: Use f-strings! For general int
s you can use the d
formatter and explicitly tell it to pad with zeros:
>>> d = datetime.date.today()
>>> f"{d.month:02d}"
'07'
But datetime
s are special and come with special formatters that are already zero padded:
>>> f"{d:%d}" # the day
'01'
>>> f"{d:%m}" # the month
'07'
I would recommend to also look at the Thread Stack Size and see if you get more threads created. The default Thread Stack Size for JRockit 1.5/1.6 is 1 MB for 64-bit VM on Linux OS. 32K threads will require a significant amount of physical and virtual memory to honor this requirement.
Try to reduce the Stack Size to 512 KB as a starting point and see if it helps creating more threads for your application. I also recommend to explore horizontal scaling e.g. splitting your application processing across more physical or virtual machines.
When using a 64-bit VM, the true limit will depend on the OS physical and virtual memory availability and OS tuning parameters such as ulimitc. I also recommend the following article as a reference:
OutOfMemoryError: unable to create new native thread – Problem Demystified
instead of localhost of '0.0.0.0', use local network address as host in case of both - the server and the client - code.
host = '192.168.12.12' port = 12345
use this host address when binding and connecting to the socket.
server.bind((host, port)) client.connect((host, port))
this change solved the issue for me.
Well actually...
I wouldn't have the Fragment try to finish the Activity. That places too much authority on the Fragment in my opinion. Instead, I would use the guide here: http://developer.android.com/training/basics/fragments/communicating.html
Have the Fragment define an interface which the Activity must implement. Make a call up to the Activity, then let the Activity decide what to do with the information. If the activity wishes to finish itself, then it can.
If you want to get advantage of your local machine timezone you can use myDateTime.ToUniversalTime()
to get the UTC time from your local time or myDateTime.ToLocalTime()
to convert the UTC time to the local machine's time.
// convert UTC time from the database to the machine's time
DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
var localTime = databaseUtcTime.ToLocalTime();
// convert local time to UTC for database save
var databaseUtcTime = localTime.ToUniversalTime();
If you need to convert time from/to other timezones, you may use TimeZoneInfo.ConvertTime()
or TimeZoneInfo.ConvertTimeFromUtc()
.
// convert UTC time from the database to japanese time
DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
var japaneseTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
var japaneseTime = TimeZoneInfo.ConvertTimeFromUtc(databaseUtcTime, japaneseTimeZone);
// convert japanese time to UTC for database save
var databaseUtcTime = TimeZoneInfo.ConvertTimeToUtc(japaneseTime, japaneseTimeZone);
@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
Given annotation worked for me. Can have a try
For Example :-
public class Parent{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="cct_id")
private Integer cct_id;
@OneToMany(cascade=CascadeType.REMOVE, fetch=FetchType.EAGER,mappedBy="clinicalCareTeam", orphanRemoval=true)
@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
private List<Child> childs;
}
public class Child{
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="cct_id")
private Parent parent;
}
A complete example for scripted pipepline:
stage('Build'){
withEnv(["GOPATH=/ws","PATH=/ws/bin:${env.PATH}"]) {
sh 'bash build.sh'
}
}
As DSM
mentions, tuple
's are immutable, but even for lists, a more elegant solution is to use filter
:
tupleX = filter(str.isdigit, tupleX)
or, if condition
is not a function, use a comprehension:
tupleX = [x for x in tupleX if x > 5]
if you really need tupleX to be a tuple, use a generator expression and pass that to tuple
:
tupleX = tuple(x for x in tupleX if condition)
In Bootstrap 3.3.7 you can change the @input-border-focus value in the Forms section of the customizer:
I know I'm 4 years late but my answer is for anyone who may not have figured it out. I'm using a Samsung Galaxy S6, what worked for me was:
Disable USB debugging
Disable Developer mode
Unplug the device from the USB cable
Re-enable Developer mode
Re-enable USB debugging
Reconnect the USB cable to your device
It is important you do it in this order as it didn't work until it was done in this order.
You should be able to adjust the width using the .modal-dialog
class selector (in conjunction with media queries or whatever strategy you're using for responsive design):
.modal-dialog {
width: 400px;
}
There is no direct way. You either export XML and then right an XSLT to format it properly (this is the hard way). An easier way is to write multiple reports with no explicit page breaks so each exports into one sheet only in excel and then write a script that would merge for you. Either way it requires a postprocessing step.
EDIT: The below answer no longer works see here
In Chrome or Opera, open a new tab and navigate to chrome://view-http-cache/
Click on whichever file you want to view. You should then see a page with a bunch of text and numbers. Copy all the text on that page. Paste it in the text box below.
Press "Go". The cached data will appear in the Results section below.