ah homework...
So wait, you need to deduct the balance of items in stock from the total number of those items that have been ordered? I have to tell you that sounds a bit backwards. Generally I think people do it the other way round. Deduct the total number of items ordered from the balance.
If you really need to do that though... Assuming that ITEM is unique in stock_bal...
SELECT s.ITEM, SUM(m.QTY) - s.QTY AS result
FROM stock_bal s
INNER JOIN master_table m ON m.ITEM = s.ITEM
GROUP BY s.ITEM, s.QTY
Just a note that the constant
keyword use for safe-area margins has been updated to env
for 11.2 beta+
https://webkit.org/blog/7929/designing-websites-for-iphone-x/
The best way is checking out the changes.
Changing the file pom.xml in a project named project-name you can do it:
git status
# modified: project-name/pom.xml
git checkout project-name/pom.xml
git checkout master
# Checking out files: 100% (491/491), done.
# Branch master set up to track remote branch master from origin.
# Switched to a new branch 'master'
Removing the AspNetCoreHostingModel line in .cproj file worked for me. There wasn't such line in another project of mine which was working fine.
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
</PropertyGroup>
It's unfortunate that it seems JavaScript has no simple way to validate a date string to these days. This is the simplest way I can think of to parse dates in the format "m/d/yyyy" in modern browsers (that's why it doesn't specify the radix to parseInt, since it should be 10 since ES5):
const dateValidationRegex = /^\d{1,2}\/\d{1,2}\/\d{4}$/;_x000D_
function isValidDate(strDate) {_x000D_
if (!dateValidationRegex.test(strDate)) return false;_x000D_
const [m, d, y] = strDate.split('/').map(n => parseInt(n));_x000D_
return m === new Date(y, m - 1, d).getMonth() + 1;_x000D_
}_x000D_
_x000D_
['10/30/2000abc', '10/30/2000', '1/1/1900', '02/30/2000', '1/1/1/4'].forEach(d => {_x000D_
console.log(d, isValidDate(d));_x000D_
});
_x000D_
You have to define an SMTP
server and a port for this. All except like sending mails from live hosts.
This is a useful link regarding this.
NB: The port should be unused. Please take care that, Some applications like
Skype
uses the default ports and there by prevents sending mail.
You can use snprintf to get a substring of a char array with precision. Here is a file example called "substring.c":
#include <stdio.h>
int main()
{
const char source[] = "This is a string array";
char dest[17];
// get first 16 characters using precision
snprintf(dest, sizeof(dest), "%.16s", source);
// print substring
puts(dest);
} // end main
Output:
This is a string
Note:
For further information see printf man page.
Once you verified the versions, you may need to either:
a: Give administrative privileges for Genymotion via properties
OR
b: Change the location for the deployed devices via Settings/VirtualBox to somewhere more accessbile like D:/GenyMotion VMs/
The two common to print a blank line in Python-
The old school way:
print "hello\n"
Writing the word print alone would do that:
print "hello"
print
As a CS student, you might have heard about Mathematical induction. The recursive solution of Tower of Hanoi works analogously - only different part is to really get not lost with B and C as were the full tower ends up.
Starting from distro packages, you can either use:
sudo apt-get install python-virtualenv
which lets you create virtualenvs, or
sudo apt-get install python{,3}-pip
which lets you install arbitrary packages to your home directory.
If you're used to virtualenv, the first command gives you everything you need (remember, pip is bundled and will be installed in any virtualenv you create).
If you just want to install packages, the second command gives you what you need. Use pip like this:
pip install --user something
and put something like
PATH=~/.local/bin:$PATH
in your ~/.bashrc
.
If your distro is ancient and you don't want to use its packages at all (except for Python itself, probably), you can download virtualenv, either as a tarball or as a standalone script:
wget -O ~/bin/virtualenv https://raw.github.com/pypa/virtualenv/master/virtualenv.py
chmod +x ~/bin/virtualenv
If your distro is more of the bleeding edge kind, Python3.3 has built-in virtualenv-like abilities:
python3 -m venv ./venv
This runs way faster, but setuptools and pip aren't included.
I think if you really want to have a unique ID then the best approach is to use a library like:
uuid or uniqueid
Note: Unique ID is not the same as Random ID
To use only date time milliseconds approach is wrong.
Nowadays computers are fast enough and able to run more than one iteration of a loop in a single millisecond.
npm install uuid
Importing the library:
If you are using ES modules
import { v4 as uuidv4 } from 'uuid';
And for CommonJS:
const { v4: uuidv4 } = require('uuid');
Usage:
uuidv4();
// This will output something like: 9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d
Following code will solve json response if there Basic Authentication and Proxy implemented.Also IIS 7.5 Hosting Problm will resolve.
public string HttpGetByWebRequ(string uri, string username, string password)
{
//For Basic Authentication
string authInfo = username + ":" + password;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
//For Proxy
WebProxy proxy = new WebProxy("http://10.127.0.1:8080", true);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
request.Accept = "application/json; charset=utf-8";
request.Proxy = proxy;
request.Headers["Authorization"] = "Basic " + authInfo;
var response = (HttpWebResponse)request.GetResponse();
string strResponse = "";
using (var sr = new StreamReader(response.GetResponseStream()))
{
strResponse= sr.ReadToEnd();
}
return strResponse;
}
So, the trick here is to use absolute positioning calc
like this:
top: calc(50% - XYpx);
left: calc(50% - XYpx);
where XYpx is half the size of your image, in my case, the image was a square. Of course, in this now obsolete case, the image must also change its size proportionally in response to window resize to be able to remain at the center without looking out of proportion.
first of all, item should be removed from the list!
mDataSet.remove(getAdapterPosition());
then:
notifyItemRemoved(getAdapterPosition());
notifyItemRangeChanged(getAdapterPosition(),mDataSet.size());
As others have suggested, you can directly write a 2-dimensional array into a Range on sheet, however if your array is single-dimensional then you have two options:
Here is an example depicting both options:
Sub PrintArrayIn1Cell(myArr As Variant, cell As Range) cell = Join(myArr, ",") End Sub Sub PrintArrayAsRange(myArr As Variant, cell As Range) cell.Resize(UBound(myArr, 1), UBound(myArr, 2)) = myArr End Sub Sub TestPrintArrayIntoSheet() '2dArrayToSheet Dim arr As Variant arr = Split("a b c", " ") 'Printing in ONE-CELL: To print all array-elements as a single string separated by comma (a,b,c): PrintArrayIn1Cell arr, [A1] 'Printing in SEPARATE-CELLS: To print array-elements in separate cells: Dim arr2D As Variant arr2D = Application.WorksheetFunction.Transpose(arr) 'convert a 1D array into 2D array PrintArrayAsRange arr2D, Range("B1:B3") End Sub
Note: Transpose will render column-by-column output, to get row-by-row output transpose it again - hope that makes sense.
HTH
adb shell pm list packages
will give you a list of all installed package names.
You can then use dumpsys | grep -A18 "Package \[my.package\]"
to grab the package information such as version identifiers etc
This comes down to browser image support; it looks like the only mainstream browser that supports tiff is Safari:
http://en.wikipedia.org/wiki/Comparison_of_web_browsers#Image_format_support
Where are you getting the tiff images from? Is it possible for them to be generated in a different format?
If you have a static set of images then I'd recommend using something like PaintShop Pro to batch convert them, changing the format.
If this isn't an option then there might be some mileage in looking for a pre-written Java applet (or another browser plugin) that can display the images in the browser.
Here you have my working example. I have used a trick that is setting the image as background of the div container with background-size:cover and background-position:center center
I have placed the image with width:100% and opacity:0 making it invisible. Note that I am showing my image only because I have an special interest on calling the child click event.
Please note that altought I am ussing angular it is completely irrelevant.
<div class="foto-item" ng-style="{'background-image':'url('+foto.path+')'}">
<img class="materialboxed" ng-class="foto.picid" ng-src="{{foto.path}}" style="opacity: 0;filter: alpha(opacity=0);" width="100%" onclick="$('.materialboxed')/>
</div>
<style>
.foto-item {
height: 75% !important;
width: 100%;
position: absolute;
top: 0;
left: 0;
overflow:hidden;
background-size: cover;
background-position: center center;
}
</style>
The result is the one that you define as optimal in all cases
i downloaded paramiko full source code from pypi and did
python setup.py install
it worked flawlessly
all default pythondev / openssl /libffi packages are already present in rhel.
downloading rpms have rpm mismatch and more trouble
You can use find
command to get some set of files (here temp files are extracted). Then you can use du
command to get the file size of each file in human readable form using -h
switch.
find $HOME -type f -name "*~" -exec du -h {} \;
OUTPUT:
4.0K /home/turing/Desktop/JavaExmp/TwoButtons.java~
4.0K /home/turing/Desktop/JavaExmp/MyDrawPanel.java~
4.0K /home/turing/Desktop/JavaExmp/Instream.java~
4.0K /home/turing/Desktop/JavaExmp/RandomDemo.java~
4.0K /home/turing/Desktop/JavaExmp/Buff.java~
4.0K /home/turing/Desktop/JavaExmp/SimpleGui2.java~
As seen in Install crontab on CentOS, the crontab package in CentOS is vixie-cron
. Hence, do install it with:
yum install vixie-cron
And then start it with:
service crond start
To make it persistent, so that it starts on boot, use:
chkconfig crond on
On CentOS 7 you need to use cronie
:
yum install cronie
On CentOS 6 you can install vixie-cron
, but the real package is cronie
:
yum install vixie-cron
and
yum install cronie
In both cases you get the same output:
.../...
==================================================================
Package Arch Version Repository Size
==================================================================
Installing:
cronie x86_64 1.4.4-12.el6 base 73 k
Installing for dependencies:
cronie-anacron x86_64 1.4.4-12.el6 base 30 k
crontabs noarch 1.10-33.el6 base 10 k
exim x86_64 4.72-6.el6 epel 1.2 M
Transaction Summary
==================================================================
Install 4 Package(s)
Note that if the user may be in multiple zones used in the query, you may probably want to add .distinct()
. Otherwise you get one user multiple times:
users_in_zones = User.objects.filter(zones__in=[zone1, zone2, zone3]).distinct()
Interestingly, I had this problem too...so I search and found this thread....I found that this worked well for me:
echo "Hello world" | grep "" > test.txt
However - When I had closed that terminal and opened a new one, I discovered that the problem went away! I wish I had kept that terminal open to compare the settings. My current terminal is a bash shell. Not sure what caused that issue to begin with - anyone?
To complete answers in case of editing default value :
In your rails console :
rails g migration MigrationName
In the migration :
def change
change_column :tables, :field_name, :field_type, default: value
end
Will look like :
def change
change_column :members, :approved, :boolean, default: true
end
I think that it's not supported. If you have a look at this DefaultValueAccessor
directive (see https://github.com/angular/angular/blob/master/modules/angular2/src/common/forms/directives/default_value_accessor.ts#L23). You will see that the value used to update the bound element is $event.target.value
.
This doesn't apply in the case of inputs with type file
since the file object can be reached $event.srcElement.files
instead.
For more details, you can have a look at this plunkr: https://plnkr.co/edit/ozZqbxIorjQW15BrDFrg?p=info:
@Component({
selector: 'my-app',
template: `
<div>
<input type="file" (change)="onChange($event)"/>
</div>
`,
providers: [ UploadService ]
})
export class AppComponent {
onChange(event) {
var files = event.srcElement.files;
console.log(files);
}
}
Try this:
public static void main(String[] args) {
String str = "My name is Milan, people know me as Milan Vasic.";
Pattern p = Pattern.compile("(Milan)(?! Vasic)");
Matcher m = p.matcher(str);
StringBuffer sb = new StringBuffer();
while(m.find()) {
m.appendReplacement(sb, "Milan Vasic");
}
m.appendTail(sb);
System.out.println(sb);
}
You will have to pass a context
object to it. Either this
if you have a reference to the class in an activty, or getApplicationContext()
public class MyActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
RegularClass regularClass = new RegularClass(this);
}
}
Then you can use it in the constructor (or set it to an instance variable):
public class RegularClass(){
private Context context;
public RegularClass(Context current){
this.context = current;
}
public findResource(){
context.getResources().getXml(R.xml.samplexml);
}
}
Where the constructor accepts Context
as a parameter
Doesn't too much matter. Whatever makes you happy will work. There aren't a lot of silly rules because Python projects can be simple.
/scripts
or /bin
for that kind of command-line interface stuff/tests
for your tests/lib
for your C-language libraries/doc
for most documentation/apidoc
for the Epydoc-generated API docs.And the top-level directory can contain README's, Config's and whatnot.
The hard choice is whether or not to use a /src
tree. Python doesn't have a distinction between /src
, /lib
, and /bin
like Java or C has.
Since a top-level /src
directory is seen by some as meaningless, your top-level directory can be the top-level architecture of your application.
/foo
/bar
/baz
I recommend putting all of this under the "name-of-my-product" directory. So, if you're writing an application named quux
, the directory that contains all this stuff is named /quux
.
Another project's PYTHONPATH
, then, can include /path/to/quux/foo
to reuse the QUUX.foo
module.
In my case, since I use Komodo Edit, my IDE cuft is a single .KPF file. I actually put that in the top-level /quux
directory, and omit adding it to SVN.
Given exportPath
and queryResults
as String variables, the following block creates a results.zip
file under exportPath
and writes the content of queryResults
to a results.txt
file inside the zip.
URI uri = URI.create("jar:file:" + exportPath + "/results.zip");
Map<String, String> env = Collections.singletonMap("create", "true");
try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
Path filePath = zipfs.getPath("/results.txt");
byte[] fileContent = queryResults.getBytes();
Files.write(filePath, fileContent, StandardOpenOption.CREATE);
}
Solution native Javascript :
document.getElementById("theSelectId").insertBefore(new Option('', ''), document.getElementById("theSelectId").firstChild);
example : http://codepen.io/anon/pen/GprybL
Open the Eclipse Installation Folder on Windows Machine
Find the eclipse.ini
Open the eclipse.ini File and add the below two lines before -vmargs
-vm
C:\Users\IshaqKhan\jdk1.8.0_173\bin\javaw.exe
This is pretty must just a copy of that projects demo page and shows uploading a single file on form submit with upload progress.
(function (angular) {
'use strict';
angular.module('uploadModule', [])
.controller('uploadCtrl', [
'$scope',
'$upload',
function ($scope, $upload) {
$scope.model = {};
$scope.selectedFile = [];
$scope.uploadProgress = 0;
$scope.uploadFile = function () {
var file = $scope.selectedFile[0];
$scope.upload = $upload.upload({
url: 'api/upload',
method: 'POST',
data: angular.toJson($scope.model),
file: file
}).progress(function (evt) {
$scope.uploadProgress = parseInt(100.0 * evt.loaded / evt.total, 10);
}).success(function (data) {
//do something
});
};
$scope.onFileSelect = function ($files) {
$scope.uploadProgress = 0;
$scope.selectedFile = $files;
};
}
])
.directive('progressBar', [
function () {
return {
link: function ($scope, el, attrs) {
$scope.$watch(attrs.progressBar, function (newValue) {
el.css('width', newValue.toString() + '%');
});
}
};
}
]);
}(angular));
HTML
<form ng-submit="uploadFile()">
<div class="row">
<div class="col-md-12">
<input type="text" ng-model="model.fileDescription" />
<input type="number" ng-model="model.rating" />
<input type="checkbox" ng-model="model.isAGoodFile" />
<input type="file" ng-file-select="onFileSelect($files)">
<div class="progress" style="margin-top: 20px;">
<div class="progress-bar" progress-bar="uploadProgress" role="progressbar">
<span ng-bind="uploadProgress"></span>
<span>%</span>
</div>
</div>
<button button type="submit" class="btn btn-default btn-lg">
<i class="fa fa-cloud-upload"></i>
<span>Upload File</span>
</button>
</div>
</div>
</form>
EDIT: Added passing a model up to the server in the file post.
The form data in the input elements would be sent in the data property of the post and be available as normal form values.
First, I think you're calling it the wrong thing. "JSON" stands for "JavaScript Object Notation" - it's just a specification for representing some data in a string that explicitly mimics JavaScript object (and array, string, number and boolean) literals. You're trying to build up a JavaScript object dynamically - so the word you're looking for is "object".
With that pedantry out of the way, I think that you're asking how to set object and array properties.
// make an empty object
var myObject = {};
// set the "list1" property to an array of strings
myObject.list1 = ['1', '2'];
// you can also access properties by string
myObject['list2'] = [];
// accessing arrays is the same, but the keys are numbers
myObject.list2[0] = 'a';
myObject['list2'][1] = 'b';
myObject.list3 = [];
// instead of placing properties at specific indices, you
// can push them on to the end
myObject.list3.push({});
// or unshift them on to the beginning
myObject.list3.unshift({});
myObject.list3[0]['key1'] = 'value1';
myObject.list3[1]['key2'] = 'value2';
myObject.not_a_list = '11';
That code will build up the object that you specified in your question (except that I call it myObject instead of myJSON). For more information on accessing properties, I recommend the Mozilla JavaScript Guide and the book JavaScript: The Good Parts.
I got home and tried the below code and it does not work. For anyone wondering, the clipboard does not just magically convert stuff like I'd hoped. Rather, it allows an application to sort of "upload" a data object with a variety of paste formats, and then then you paste (which in my metaphor would be the "download") the program being pasted into specifies its preferred format. I personally ended up using this code, which has been recommended previously, and it was enormously easy to use and very effective. After you have imported the code (in VStudio, Project -> Add Existing Files) you then just go html to rtf like this:
return HtmlToRtfConverter.ConvertHtmlToRtf(myRtfString);
or the opposite direction:
return RtfToHtmlConverter.ConvertHtmlToRtf(myHtmlString);
Most if not all of the above answers provide comprehensive, often Library-based solutions to the problem at hand. I am away from my computer and thus cannot test the idea, but one alternative, cheap and vaguely hack-y method would be the following.
private string HTMLFromRtf(string rtfString)
{
Clipboard.SetData(DataFormats.Rtf, rtfString);
return Clipboard.GetData(DataFormats.Html);
}
Again, not totally sure if this would work, but just messing around with some html on my iPhone I suspect it would. Documentation is here. More in depth explanation/docs RE the getting and setting of data models in the clipboard can be found here.
(Yes I am fully aware I'm here years later, but I assume this question is one which some people still want answered).
Word boundaries would work perfectly here, such as with:
\b\w{3,8}\b
\b\w{2,}
\b\w{,10}\b
\b\w{5}\b
Some languages such as Java and C++ are double-escape required:
\\b\\w{3,8}\\b
\\b\\w{2,}
\\b\\w{,10}\\b
\\b\\w{5}\\b
PS: \\b\\w{,10}\\b
may not work for all languages or flavors.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegularExpression{
public static void main(String[] args){
final String regex = "\\b\\w{3,8}\\b";
final String string = "words with length three to eight";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
}
}
}
Full match: words
Full match: with
Full match: length
Full match: three
Full match: eight
Another good-to-know method is to use negative lookarounds:
(?<!\w)\w{3,8}(?!\w)
(?<!\w)\w{2,}
(?<!\w)\w{,10}(?!\w)
(?<!\w)\w{5}(?!\w)
(?<!\\w)\\w{3,8}(?!\\w)
(?<!\\w)\\w{2,}
(?<!\\w)\\w{,10}(?!\\w)
(?<!\\w)\\w{5}(?!\\w)
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegularExpression{
public static void main(String[] args){
final String regex = "(?<!\\w)\\w{1,10}(?!\\w)";
final String string = "words with length three to eight";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
}
}
}
Full match: words
Full match: with
Full match: length
Full match: three
Full match: to
Full match: eight
jex.im visualizes regular expressions:
If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.
you should examine the specification before using 'remainder' operator % :
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.17.3
// bad enough implementation of isEven method, for fun. so any worse?
boolean isEven(int num)
{
num %= 10;
if(num == 1)
return false;
else if(num == 0)
return true;
else
return isEven(num + 2);
}
isEven = isEven(a);
A while
loop can be simulated in cmd.exe
with:
:still_more_files
if %countfiles% leq 21 (
rem change countfile here
goto :still_more_files
)
For example, the following script:
@echo off
setlocal enableextensions enabledelayedexpansion
set /a "x = 0"
:more_to_process
if %x% leq 5 (
echo %x%
set /a "x = x + 1"
goto :more_to_process
)
endlocal
outputs:
0
1
2
3
4
5
For your particular case, I would start with the following. Your initial description was a little confusing. I'm assuming you want to delete files in that directory until there's 20 or less:
@echo off
set backupdir=c:\test
:more_files_to_process
for /f %%x in ('dir %backupdir% /b ^| find /v /c "::"') do set num=%%x
if %num% gtr 20 (
cscript /nologo c:\deletefile.vbs %backupdir%
goto :more_files_to_process
)
In IMPALA, not having order in the GROUP_CONCAT can be problematic, over at Coders'Co. we have some sort of a workaround for that (we need it for Rax/Impala). If you need the GROUP_CONCAT result with an ORDER BY clause in IMPALA, take a look at this blog post: http://raxdb.com/blog/sorting-by-regex/
There are five common ways by which a class data store data that cannot be modified outside the storing class' control:
Because strings are of variable length, they cannot be value-type primitives, nor can their character data be stored in a struct. Among the remaining choices, the only one which wouldn't require that strings' character data be stored in some kind of immutable object would be #5. While it would be possible to design a framework around option #5, that choice would require that any code which wanted a copy of a string that couldn't be changed outside its control would have to make a private copy for itself. While it hardly be impossible to do that, the amount of extra code required to do that, and the amount of extra run-time processing necessary to make defensive copies of everything, would far outweigh the slight benefits that could come from having string
be mutable, especially given that there is a mutable string type (System.Text.StringBuilder
) which accomplishes 99% of what could be accomplished with a mutable string
.
To simplify, make sure to add a hash bang to the top of your ExecStart script, i.e.
#!/bin/bash
python -u alwayson.py
There's a free Java API called JFreeWebSearch which uses the already mentioned Faroo: http://www.ke.tu-darmstadt.de/resources/jfreewebsearch
The examples above don't correctly apply this
or pass arguments
correctly to the function override. Underscore _.wrap() wraps existing functions, applies this
and passes arguments
correctly. See: http://underscorejs.org/#wrap
I know this question is old but in case if anyone will look for it in the future. It is possible to have two captcha's on one page. Pink to documentation is here: https://developers.google.com/recaptcha/docs/display Example below is just a copy form doc and you dont have to specify different layouts.
<script type="text/javascript">
var verifyCallback = function(response) {
alert(response);
};
var widgetId1;
var widgetId2;
var onloadCallback = function() {
// Renders the HTML element with id 'example1' as a reCAPTCHA widget.
// The id of the reCAPTCHA widget is assigned to 'widgetId1'.
widgetId1 = grecaptcha.render('example1', {
'sitekey' : 'your_site_key',
'theme' : 'light'
});
widgetId2 = grecaptcha.render(document.getElementById('example2'), {
'sitekey' : 'your_site_key'
});
grecaptcha.render('example3', {
'sitekey' : 'your_site_key',
'callback' : verifyCallback,
'theme' : 'dark'
});
};
</script>
My Code Is Very Easy To Understand
var year = 2015;
var LeapYear = year % 4;
if (LeapYear==0) {
alert("This is Leap Year");
} else {
alert("This is not leap year");
}
A simple way is you can do as follows
public static String stripQueryStringAndHashFromPath(String uri) {
return uri.replaceAll(("(\\?.*|\\#.*)"), "");
}
Chris Stewart wrote there:
Splash screens just waste your time, right? As an Android developer, when I see a splash screen, I know that some poor dev had to add a three-second delay to the code.
Then, I have to stare at some picture for three seconds until I can use the app. And I have to do this every time it’s launched. I know which app I opened. I know what it does. Just let me use it!
Splash Screens the Right Way
I believe that Google isn’t contradicting itself; the old advice and the new stand together. (That said, it’s still not a good idea to use a splash screen that wastes a user’s time. Please don’t do that.)
However, Android apps do take some amount of time to start up, especially on a cold start. There is a delay there that you may not be able to avoid. Instead of leaving a blank screen during this time, why not show the user something nice? This is the approach Google is advocating. Don’t waste the user’s time, but don’t show them a blank, unconfigured section of the app the first time they launch it, either.
If you look at recent updates to Google apps, you’ll see appropriate uses of the splash screen. Take a look at the YouTube app, for example.
Taken from http://www.dotnetspider.com/resources/189-AutoPostBack-What-How-works.aspx:
Autopostback
is the mechanism by which the page will be posted back to the server automatically based on some events in the web controls. In some of the web controls, the property called auto post back, if set to true, will send the request to the server when an event happens in the control.Whenever we set the autopostback attribute to true on any of the controls, the .NET framework will automatically insert a few lines of code into the HTML generated to implement this functionality.
- A JavaScript method with name __doPostBack (eventtarget, eventargument)
- Two hidden variables with name __EVENTTARGET and __EVENTARGUMENT
- OnChange JavaScript event to the control
Several answers have discussed the problems with the concept of overridable static methods. However sometimes you come across a pattern where it seems like that's just what you want to use.
For example, I work with an object-relational layer that has value objects, but also has commands for manipulating the value objects. For various reasons, each value object class has to define some static methods that let the framework find the command instance. For example, to create a Person you'd do:
cmd = createCmd(Person.getCreateCmdId());
Person p = cmd.execute();
and to load a Person by ID you'd do
cmd = createCmd(Person.getGetCmdId());
cmd.set(ID, id);
Person p = cmd.execute();
This is fairly convenient, however it has its problems; notably the existence of the static methods can not be enforced in the interface. An overridable static method in the interface would be exactly what we'd need, if only it could work somehow.
EJBs solve this problem by having a Home interface; each object knows how to find its Home and the Home contains the "static" methods. This way the "static" methods can be overridden as needed, and you don't clutter up the normal (it's called "Remote") interface with methods that don't apply to an instance of your bean. Just make the normal interface specify a "getHome()" method. Return an instance of the Home object (which could be a singleton, I suppose) and the caller can perform operations that affect all Person objects.
Use this ..
$str = rawurldecode($_SERVER['REQUEST_URI']);
$arr = explode("{",$str);
$arr1 = explode("}", $arr[1]);
$jsS = '{'.$arr1[0].'}';
$data = json_decode($jsS,true);
Now ..
use $data['elemname']
to access the values.
send jsonp request with JSON Object.
Request format :
$.ajax({
method : 'POST',
url : 'xxx.com',
data : JSONDataObj, //Use JSON.stringfy before sending data
dataType: 'jsonp',
contentType: 'application/json; charset=utf-8',
success : function(response){
console.log(response);
}
})
I believe telnet 74.255.12.25 8089
. Why don't u try both
i solved this by http://willcodeforcoffee.com/2007/01/31/cakephp-error-500-too-many-redirects/ just uncomment or add this:
RewriteBase /
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
to your .htaccess file
easy but not efficient:
list(df.education).count('9th')
Here is what I figured, and this happened recently on Windows 10 after an update was installed. From what I gathered, a Windows Defender update was installed which assumed my "Project.dll"(an asp.net core project) behaved like a virus so it was deleted.
So, one of the first things I suggest you do before you start installing/uninstalling stuffs is to check to confirm your "Project.dll" is where it should be.
Copy it back to the location if it is no longer there.
If you are having difficulty copying the file back add an exclusion to your project folder in windows defender. ( Learn how to do that here. )
This worked for me instantly, and I repeated it across application multiple servers.
Simply & Easy : JavaScript code :
function JoinedOrNot(){
var cat = document.getElementById("mySelect");
if(cat.value == "yes"){
document.getElementById("mySelect1").disabled = false;
}else{
document.getElementById("mySelect1").disabled = true;
}
}
just add in this line [onChange="JoinedOrNot()"] : <select id="mySelect" onchange="JoinedOrNot()">
it's work fine ;)
Depends on the type. You are adding the small overhead of having to make a reference and dereference. For types with a size equal or smaller than pointers that are using the default copy ctor, it would probably be faster to pass by value.
No this is not possible, SVG elements do not have background-...
presentation attributes.
To simulate this effect you could draw a rectangle behind the text attribute with fill="green"
or something similar (filters). Using JavaScript you could do the following:
var ctx = document.getElementById("the-svg"),
textElm = ctx.getElementById("the-text"),
SVGRect = textElm.getBBox();
var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
rect.setAttribute("x", SVGRect.x);
rect.setAttribute("y", SVGRect.y);
rect.setAttribute("width", SVGRect.width);
rect.setAttribute("height", SVGRect.height);
rect.setAttribute("fill", "yellow");
ctx.insertBefore(rect, textElm);
I was having this problem in Safari and Chrome (Mac) and discovered that .scrollTop
would work on $("body")
but not $("html, body")
, FF and IE however works the other way round. A simple browser detect fixes the issue:
if($.browser.safari)
bodyelem = $("body")
else
bodyelem = $("html,body")
bodyelem.scrollTop(100)
The jQuery browser value for Chrome is Safari, so you only need to do a detect on that.
Hope this helps someone.
Convert the image to a byte[]
and store that in the database.
Add this column to your model:
public byte[] Content { get; set; }
Then convert your image to a byte array and store that like you would any other data:
public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
using(var ms = new MemoryStream())
{
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
}
public Image ByteArrayToImage(byte[] byteArrayIn)
{
using(var ms = new MemoryStream(byteArrayIn))
{
var returnImage = Image.FromStream(ms);
return returnImage;
}
}
Source: Fastest way to convert Image to Byte array
var image = new ImageEntity()
{
Content = ImageToByteArray(image)
};
_context.Images.Add(image);
_context.SaveChanges();
When you want to get the image back, get the byte array from the database and use the ByteArrayToImage
and do what you wish with the Image
This stops working when the byte[]
gets to big. It will work for files under 100Mb
For new Xcode 11.xxx and Swift 5.xx, where the target it set to iOS 13+.
For the new project structure, AppDelegate does not have to do anything regarding rootViewController.
A new class is there to handle window(UIWindowScene) class -> 'SceneDelegate' file.
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = // Your RootViewController in here
self.window = window
window.makeKeyAndVisible()
}
}
From version 1.7 and later it should be:
git diff --staged
Simple: Just create a (nested) PHP array and call json_encode
on it. Numeric arrays translate into JSON lists ([]
), associative arrays and PHP objects translate into objects ({}
). Example:
$a = array(
array('foo' => 'bar'),
array('foo' => 'baz'));
$json = json_encode($a);
Gives you:
[{"foo":"bar"},{"foo":"baz"}]
I was trying to find the meaning of GRANT USAGE on *.* TO
and found here. I can clarify that GRANT USAGE on *.* TO user IDENTIFIED BY PASSWORD password
will be granted when you create the user with the following command (CREATE
):
CREATE USER 'user'@'localhost' IDENTIFIED BY 'password';
When you grant privilege with GRANT
, new privilege s will be added on top of it.
I've run into a stupid mistake on my part. I had a systems wide and a user variable path set for my golang workspace on my windows 10 machine. When I removed the redundant systems variable pathway and logged off and back on, I was able to call .exe files in bash and call go env with success.
Although OP has been answered this is another problem that could keep bash from seeing your pathways. I just tested bash again with this problem and it does seem to give a conflict of some sort that blocks bash from following either of the paths.
Aditya or others, can you join or match up t2 with t1 in your example, i.e. translated to my code,
with t1 as (select * from AA where FIRSTNAME like 'Kermit'),
t2 as (select * from BB B join t1 on t1.FIELD1 = B.FIELD1)
I am not clear whether only WHERE is supported for joining, or what joining approach is supported within the 2nd WITH entity. Some of the examples have the WHERE A=B down in the body of the select "below" the WITH clauses.
The error I'm getting following these WITH declarations is the identifiers (field names) in B are not recognized, down in the body of the rest of the SQL. So the WITH syntax seems to run OK, but cannot access the results from t2.
A PDOStatement
(which you have in $users
) is a forward-cursor. That means, once consumed (the first foreach
iteration), it won't rewind to the beginning of the resultset.
You can close the cursor after the foreach
and execute the statement again:
$users = $dbh->query($sql);
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
$users->execute();
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
Or you could cache using tailored CachingIterator
with a fullcache:
$users = $dbh->query($sql);
$usersCached = new CachedPDOStatement($users);
foreach ($usersCached as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
foreach ($usersCached as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
You find the CachedPDOStatement
class as a gist. The caching itertor is probably more sane than storing the resultset into an array because it still offers all properties and methods of the PDOStatement
object it has wrapped.
Try this
import ("strconv")
value := "123"
number,err := strconv.ParseUint(value, 10, 32)
finalIntNum := int(number) //Convert uint64 To int
Let's make it a POSIX oneliner:
a="/$0"; a=${a%/*}; a=${a#/}; a=${a:-.}; BASEDIR=$(cd "$a"; pwd)
Tested on many Bourne-compatible shells including the BSD ones.
As far as I know I am the author and I put it into public domain. For more info see: https://www.jasan.tk/posts/2017-05-11-posix_shell_dirname_replacement/
I was facing the same issue. After many tries below solution worked for me.
Before installing VC++ install your windows updates. 1. Go to Start - Control Panel - Windows Update 2. Check for the updates. 3. Install all updates. 4. Restart your system.
After that you can follow the below steps.
@ABHI KUMAR
Download the Visual C++ Redistributable 2015
Visual C++ Redistributable for Visual Studio 2015 (64-bit)
Visual C++ Redistributable for Visual Studio 2015 (32-bit)
(Reinstal if already installed) then restart your computer or use windows updates for download auto.
For link download https://www.microsoft.com/de-de/download/details.aspx?id=48145.
Can Declare As the in ng-init also getting true
<!doctype html>
<html ng-app="plunker" >
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl" ng-init="testModel['item1']= true">
<label><input type="checkbox" name="test" ng-model="testModel['item1']" /> Testing</label><br />
<label><input type="checkbox" name="test" ng-model="testModel['item2']" /> Testing 2</label><br />
<label><input type="checkbox" name="test" ng-model="testModel['item3']" /> Testing 3</label><br />
<input type="button" ng-click="submit()" value="Submit" />
</body>
</html>
And You Can Select the First One and Object Also Shown here true,false,flase
I know I'm late, but I've only ever had this error if my Response.Redirect
is in a Try...Catch
block.
Never put a Response.Redirect into a Try...Catch block. It's bad practice
As an alternative to putting the Response.Redirect into the Try...Catch block, I'd break up the method/function into two steps.
inside the Try...Catch block performs the requested actions and sets a "result" value to indicate success or failure of the actions.
outside of the Try...Catch block does the redirect (or doesn't) depending on what the "result" value is.
This code is far from perfect and probably should not be copied since I haven't tested it.
public void btnLogin_Click(UserLoginViewModel model)
{
bool ValidLogin = false; // this is our "result value"
try
{
using (Context Db = new Context)
{
User User = new User();
if (String.IsNullOrEmpty(model.EmailAddress))
ValidLogin = false; // no email address was entered
else
User = Db.FirstOrDefault(x => x.EmailAddress == model.EmailAddress);
if (User != null && User.PasswordHash == Hashing.CreateHash(model.Password))
ValidLogin = true; // login succeeded
}
}
catch (Exception ex)
{
throw ex; // something went wrong so throw an error
}
if (ValidLogin)
{
GenerateCookie(User);
Response.Redirect("~/Members/Default.aspx");
}
else
{
// do something to indicate that the login failed.
}
}
Since your files are not yet committed in branch1
:
git stash
git checkout branch2
git stash pop
or
git stash
git checkout branch2
git stash list # to check the various stash made in different branch
git stash apply x # to select the right one
As commented by benjohn (see git stash
man page):
To also stash currently untracked (newly added) files, add the argument
-u
, so:
git stash -u
Use this for slivers AppBar
SliverAppBar (
automaticallyImplyLeading: false,
elevation: 0,
brightness: Brightness.light,
backgroundColor: Colors.white,
pinned: true,
),
Use this for normal Appbar
appBar: AppBar(
title: Text
("You decide on the appbar name"
style: TextStyle(color: Colors.black,),
elevation: 0,
brightness: Brightness.light,
backgroundColor: Colors.white,
automaticallyImplyLeading: false,
),
just select '0' as the value for the desired column
.NET stores all strings as a sequence of UTF-16 code units. (This is close enough to "Unicode characters" for most purposes.)
Fortunately for you, Unicode was designed such that ASCII values map to the same number in Unicode, so after you've converted each character to an integer, you can just check whether it's in the ASCII range. Note that you can use an implicit conversion from char
to int
- there's no need to call a conversion method:
string text = "Here's some text including a \u00ff non-ASCII character";
foreach (char c in text)
{
int unicode = c;
Console.WriteLine(unicode < 128 ? "ASCII: {0}" : "Non-ASCII: {0}", unicode);
}
Use a column to let each date be shown as month number; another column for day number:
A B C D
----- ----- ----------- --------
1 8 6 8/6/2010 12.70
2 8 7 8/7/2010 10.50
3 8 7 8/7/2010 7.10
4 8 9 8/9/2010 10.50
5 8 10 8/10/2010 15.00
The formula for A1
is =Month(C1)
The formula for B1
is =Day(C1)
For Month sums, put the month number next to each month:
E F G
----- ----- -------------
1 7 July $1,000,010
2 8 Aug $1,200,300
The formula for G1
is =SumIf($A$1:$A$100, E1, $D$1:$D$100)
. This is a portable formula; just copy it down.
Total for the day will be be a bit more complicated, but you can probably see how to do it.
Try something like this. This should center any huge element in the middle vertically and horizontally with respect to its parent no matter both of their sizes.
.parent {
position: relative;
overflow: hidden;
//optionally set height and width, it will depend on the rest of the styling used
}
.child {
position: absolute;
top: -9999px;
bottom: -9999px;
left: -9999px;
right: -9999px;
margin: auto;
}
If all you want to do is access placeholder value from code, there is the @Value
annotation:
@Value("${settings.some.property}")
String someValue;
To access placeholders From SPEL use this syntax:
#('${settings.some.property}')
To expose configuration to views that have SPEL turned off, one can use this trick:
package com.my.app;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.stereotype.Component;
@Component
public class PropertyPlaceholderExposer implements Map<String, String>, BeanFactoryAware {
ConfigurableBeanFactory beanFactory;
@Override
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = (ConfigurableBeanFactory) beanFactory;
}
protected String resolveProperty(String name) {
String rv = beanFactory.resolveEmbeddedValue("${" + name + "}");
return rv;
}
@Override
public String get(Object key) {
return resolveProperty(key.toString());
}
@Override
public boolean containsKey(Object key) {
try {
resolveProperty(key.toString());
return true;
}
catch(Exception e) {
return false;
}
}
@Override public boolean isEmpty() { return false; }
@Override public Set<String> keySet() { throw new UnsupportedOperationException(); }
@Override public Set<java.util.Map.Entry<String, String>> entrySet() { throw new UnsupportedOperationException(); }
@Override public Collection<String> values() { throw new UnsupportedOperationException(); }
@Override public int size() { throw new UnsupportedOperationException(); }
@Override public boolean containsValue(Object value) { throw new UnsupportedOperationException(); }
@Override public void clear() { throw new UnsupportedOperationException(); }
@Override public String put(String key, String value) { throw new UnsupportedOperationException(); }
@Override public String remove(Object key) { throw new UnsupportedOperationException(); }
@Override public void putAll(Map<? extends String, ? extends String> t) { throw new UnsupportedOperationException(); }
}
And then use the exposer to expose properties to a view:
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver" id="tilesViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
<property name="attributesMap">
<map>
<entry key="config">
<bean class="com.my.app.PropertyPlaceholderExposer" />
</entry>
</map>
</property>
</bean>
Then in view, use the exposed properties like this:
${config['settings.some.property']}
This solution has the advantage that you can rely on standard placeholder implementation injected by the context:property-placeholder tag.
Now as a final note, if you really need a to capture all placeholder properties and their values, you have to pipe them through StringValueResolver to make sure that placeholders work inside the property values as expected. The following code will do that.
package com.my.app;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.util.StringValueResolver;
public class AppConfig extends PropertyPlaceholderConfigurer implements Map<String, String> {
Map<String, String> props = new HashMap<String, String>();
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props)
throws BeansException {
this.props.clear();
for (Entry<Object, Object> e: props.entrySet())
this.props.put(e.getKey().toString(), e.getValue().toString());
super.processProperties(beanFactory, props);
}
@Override
protected void doProcessProperties(ConfigurableListableBeanFactory beanFactoryToProcess,
StringValueResolver valueResolver) {
super.doProcessProperties(beanFactoryToProcess, valueResolver);
for(Entry<String, String> e: props.entrySet())
e.setValue(valueResolver.resolveStringValue(e.getValue()));
}
// Implement map interface to access stored properties
@Override public Set<String> keySet() { return props.keySet(); }
@Override public Set<java.util.Map.Entry<String, String>> entrySet() { return props.entrySet(); }
@Override public Collection<String> values() { return props.values(); }
@Override public int size() { return props.size(); }
@Override public boolean isEmpty() { return props.isEmpty(); }
@Override public boolean containsValue(Object value) { return props.containsValue(value); }
@Override public boolean containsKey(Object key) { return props.containsKey(key); }
@Override public String get(Object key) { return props.get(key); }
@Override public void clear() { throw new UnsupportedOperationException(); }
@Override public String put(String key, String value) { throw new UnsupportedOperationException(); }
@Override public String remove(Object key) { throw new UnsupportedOperationException(); }
@Override public void putAll(Map<? extends String, ? extends String> t) { throw new UnsupportedOperationException(); }
}
The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5
. From the comment you put this needed to be declared elsewhere in your code
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
The error was because you are trying to execute a method that does not exist.
PS C:\Users\Matt> $md5 | gm
TypeName: System.Security.Cryptography.MD5CryptoServiceProvider
Name MemberType Definition
---- ---------- ----------
Clear Method void Clear()
ComputeHash Method byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...
The .ComputeHash()
of $md5.ComputeHash()
was the null valued expression. Typing in gibberish would create the same effect.
PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PowerShell by default allows this to happen as defined its StrictMode
When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.
The only solution I have found is not to set the index to a previous frame and wait (then OpenCV stops reading frames, anyway), but to initialize the capture one more time. So, it looks like this:
cap = cv2.VideoCapture(camera_url)
while True:
ret, frame = cap.read()
if not ret:
cap = cv.VideoCapture(camera_url)
continue
# do your processing here
And it works perfectly!
Be careful with the answers above. sqljdbc4.jar is not distributed with under a public license which is why it is difficult to include it in a jar for runtime and distribution. See my answer below for more details and a much better solution. Your life will become much easier as mine did once I found this answer.
Just something to watch out for......
In SQL Server 2008 R2 SSMS, the "Script Constraint as -> DROP And CREATE To" command produces T-SQL like below
USE [MyDatabase]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DEF_Detail_IsDeleted]') AND type = 'D')
BEGIN
ALTER TABLE [Patient].[Detail] DROP CONSTRAINT [DEF_Detail_IsDeleted]
END
GO
USE [MyDatabase]
GO
ALTER TABLE [Patient].[Detail] ADD CONSTRAINT [DEF_Detail_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]
GO
Out of the box, this script does NOT drop the constraint because the SELECT returns 0 rows. (see post Microsoft Connect).
The name of the default constraint is wrong but I gather it also has something to do with the OBJECT_ID function because changing the name doesn't fix the problem.
To fix this, I removed the usage of OBJECT_ID and used the default constraint name instead.
(SELECT * FROM dbo.sysobjects WHERE [name] = (N'DEF_Detail_IsDeleted') AND type = 'D')
this is how you do it with ActionLIstener
import java.awt.FlowLayout;
import java.awt.event.*;
import javax.swing.*;
public class MyWind extends JFrame{
public MyWind() {
initialize();
}
private void initialize() {
setSize(300, 300);
setLayout(new FlowLayout(FlowLayout.LEFT));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextField field = new JTextField();
field.setSize(200, 50);
field.setText(" ");
JComboBox comboBox = new JComboBox();
comboBox.setEditable(true);
comboBox.addItem("item1");
comboBox.addItem("item2");
//
// Create an ActionListener for the JComboBox component.
//
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//
// Get the source of the component, which is our combo
// box.
//
JComboBox comboBox = (JComboBox) event.getSource();
Object selected = comboBox.getSelectedItem();
if(selected.toString().equals("item1"))
field.setText("30");
else if(selected.toString().equals("item2"))
field.setText("40");
}
});
getContentPane().add(comboBox);
getContentPane().add(field);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MyWind().setVisible(true);
}
});
}
}
Do as following.
1. Add the Style to the XML
<style name="MyTabLayoutTextAppearance" parent="TextAppearance.Design.Tab">
<item name="android:textSize">14sp</item>
</style>
2. Apply Style
Find the Layout containing the TabLayout and add the style. The added line is bold.
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
app:tabTextAppearance="@style/MyTabLayoutTextAppearance"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
In plain English: Get the parent element. Check it's height, and save that value. Then loop through all the child elements and check their individual heights.
This is dirty, but you might get the basic idea: http://jsfiddle.net/VgDgz/
nvm use 8.11.4
Just go with nvm use node_version
The best way to do this is probably to use a third party library.
There's an implementation of what you're looking for in jQuery UI jQuery UI and in dojo dojo. jQuery is more popular, but dojo allows you to declaratively define widgets in HTML, which sounds more like what you're looking for.
Which one you use will depend on your style, but both are developed for cross browser work, and both will be updated more often than copy and paste code.
If you are building the code yourself, then this issue could be overcome by giving "-target 1.5" to the java compiler (or by setting the corresponding option in your IDE or your build config).
The correct way to do this is the following (thanks QT Support Team):
CONFIG(debug, debug|release) {
DESTDIR = build/debug
}
CONFIG(release, debug|release) {
DESTDIR = build/release
}
OBJECTS_DIR = $$DESTDIR/.obj
MOC_DIR = $$DESTDIR/.moc
RCC_DIR = $$DESTDIR/.qrc
UI_DIR = $$DESTDIR/.u
Use a native SQL query by specifying a @NamedNativeQuery
annotation on the entity class, or by using the EntityManager.createNativeQuery
method. You will need to specify the type of the ResultSet using an appropriate class, or use a ResultSet mapping.
A polyfill is a shim which replaces the original call with the call to a shim.
For example, say you want to use the navigator.mediaDevices object, but not all browsers support this. You could imagine a library that provided a shim which you might use like this:
<script src="js/MediaShim.js"></script>
<script>
MediaShim.mediaDevices.getUserMedia(...);
</script>
In this case, you are explicitly calling a shim instead of using the original object or method. The polyfill, on the other hand, replaces the objects and methods on the original objects.
For example:
<script src="js/adapter.js"></script>
<script>
navigator.mediaDevices.getUserMedia(...);
</script>
In your code, it looks as though you are using the standard navigator.mediaDevices object. But really, the polyfill (adapter.js in the example) has replaced this object with its own one.
The one it has replaced it with is a shim. This will detect if the feature is natively supported and use it if it is, or it will work around it using other APIs if it is not.
So a polyfill is a sort of "transparent" shim. And this is what Remy Sharp (who coined the term) meant when saying "if you removed the polyfill script, your code would continue to work, without any changes required in spite of the polyfill being removed".
The effect of the 301 would be that the search engines will index /option-a instead of /option-x. Which is probably a good thing since /option-x is not reachable for the search index and thus could have a positive effect on the index. Only if you use this wisely ;-)
After the redirect put exit(); to stop the rest of the script to execute
header("HTTP/1.1 301 Moved Permanently");
header("Location: /option-a");
exit();
In phpMyAdmin 4.0, you go to Status > Monitor. In there you can enable the slow query log and general log, see a live monitor, select a portion of the graph, see the related queries and analyse them.
If you download the jquery easing plugin (check it out),then you just have to add this to your main.js file:
$('a.smooth-scroll').on('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top + 20
}, 1500, 'easeInOutExpo');
event.preventDefault();
});
and also dont forget to add the smooth-scroll class to your a tags like this:
<li><a href="#about" class="smooth-scroll">About Us</a></li>
In case performance is more important than readability and as long as your condition consists of simple arithmetic operations, you can use aggregation pipeline. First, use $project to calculate the left hand side of the condition (take all fields to left hand side). Then use $match to compare with a constant and filter. This way you avoid javascript execution. Below is my test in python:
import pymongo
from random import randrange
docs = [{'Grade1': randrange(10), 'Grade2': randrange(10)} for __ in range(100000)]
coll = pymongo.MongoClient().test_db.grades
coll.insert_many(docs)
Using aggregate:
%timeit -n1 -r1 list(coll.aggregate([
{
'$project': {
'diff': {'$subtract': ['$Grade1', '$Grade2']},
'Grade1': 1,
'Grade2': 1
}
},
{
'$match': {'diff': {'$gt': 0}}
}
]))
1 loop, best of 1: 192 ms per loop
Using find and $where:
%timeit -n1 -r1 list(coll.find({'$where': 'this.Grade1 > this.Grade2'}))
1 loop, best of 1: 4.54 s per loop
I don't know that much JQuery but I've heard it allows to fire native events with this syntax.
$(document).ready(function(){
$('#countrylist').change(function(e){
// Your event handler
});
// And now fire change event when the DOM is ready
$('#countrylist').trigger('change');
});
You must declare the change event handler before calling trigger() or change() otherwise it won't be fired. Thanks for the mention @LenielMacaferi.
More information here.
You don't need an onclick. Assuming you're using Bootstrap 3 Bootstrap 3 Documentation
<div class="span4 proj-div" data-toggle="modal" data-target="#GSCCModal">Clickable content, graphics, whatever</div>
<div id="GSCCModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">× </button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
If you're using Bootstrap 2, you'd follow the markup here: http://getbootstrap.com/2.3.2/javascript.html#modals
Based on this page:
You can open SQL Compact 4.0 Databases from Visual Studio 2012 directly, by going to
and following the instructions there.
If you're okay with them being upgraded to 4.0, you can open older versions of SQL Compact Databases also - handy if you just want to have a look at some tables, etc for stuff like Windows Phone local database development.
(note I'm not sure if this requires a specific SKU of VS2012, if it helps I'm running Premium)
When I use postman to send a file which is 5.6M to an external network, I faced the same issue. The same action is succeeded on my own computer and local testing environment.
After checking all the server configs and HTTP headers, I found that the reason is Postman may have some trouble simulating requests to external HTTP requests. Finally, I did the sendfile request on the chrome HTML page successfully. Just as a reference :)
Just another example of walking down the directory structure to get exactly what you want. Note: I didn't exclude Library/
but Library/**/*
# .gitignore file
Library/**/*
!Library/Application Support/
!Library/Application Support/Sublime Text 3/
!Library/Application Support/Sublime Text 3/Packages/
!Library/Application Support/Sublime Text 3/Packages/User/
!Library/Application Support/Sublime Text 3/Packages/User/*macro
!Library/Application Support/Sublime Text 3/Packages/User/*snippet
!Library/Application Support/Sublime Text 3/Packages/User/*settings
!Library/Application Support/Sublime Text 3/Packages/User/*keymap
!Library/Application Support/Sublime Text 3/Packages/User/*theme
!Library/Application Support/Sublime Text 3/Packages/User/**/
!Library/Application Support/Sublime Text 3/Packages/User/**/*macro
!Library/Application Support/Sublime Text 3/Packages/User/**/*snippet
!Library/Application Support/Sublime Text 3/Packages/User/**/*settings
!Library/Application Support/Sublime Text 3/Packages/User/**/*keymap
!Library/Application Support/Sublime Text 3/Packages/User/**/*theme
> git add Library
> git status
On branch master
Your branch is up-to-date with 'origin/master'.
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
new file: Library/Application Support/Sublime Text 3/Packages/User/Default (OSX).sublime-keymap
new file: Library/Application Support/Sublime Text 3/Packages/User/ElixirSublime.sublime-settings
new file: Library/Application Support/Sublime Text 3/Packages/User/Package Control.sublime-settings
new file: Library/Application Support/Sublime Text 3/Packages/User/Preferences.sublime-settings
new file: Library/Application Support/Sublime Text 3/Packages/User/RESTer.sublime-settings
new file: Library/Application Support/Sublime Text 3/Packages/User/SublimeLinter/Monokai (SL).tmTheme
new file: Library/Application Support/Sublime Text 3/Packages/User/TextPastryHistory.sublime-settings
new file: Library/Application Support/Sublime Text 3/Packages/User/ZenTabs.sublime-settings
new file: Library/Application Support/Sublime Text 3/Packages/User/adrian-comment.sublime-macro
new file: Library/Application Support/Sublime Text 3/Packages/User/json-pretty-generate.sublime-snippet
new file: Library/Application Support/Sublime Text 3/Packages/User/raise-exception.sublime-snippet
new file: Library/Application Support/Sublime Text 3/Packages/User/trailing_spaces.sublime-settings
Yes.You can try with some hidden params.
$("#form").submit( function(eventObj) {
$("<input />").attr("type", "hidden")
.attr("name", "something")
.attr("value", "something")
.appendTo("#form");
return true;
});
You can easily crop a Mat using opencv funtions.
setMouseCallback("Original",mouse_call);
The mouse_call
is given below:
void mouse_call(int event,int x,int y,int,void*)
{
if(event==EVENT_LBUTTONDOWN)
{
leftDown=true;
cor1.x=x;
cor1.y=y;
cout <<"Corner 1: "<<cor1<<endl;
}
if(event==EVENT_LBUTTONUP)
{
if(abs(x-cor1.x)>20&&abs(y-cor1.y)>20) //checking whether the region is too small
{
leftup=true;
cor2.x=x;
cor2.y=y;
cout<<"Corner 2: "<<cor2<<endl;
}
else
{
cout<<"Select a region more than 20 pixels"<<endl;
}
}
if(leftDown==true&&leftup==false) //when the left button is down
{
Point pt;
pt.x=x;
pt.y=y;
Mat temp_img=img.clone();
rectangle(temp_img,cor1,pt,Scalar(0,0,255)); //drawing a rectangle continuously
imshow("Original",temp_img);
}
if(leftDown==true&&leftup==true) //when the selection is done
{
box.width=abs(cor1.x-cor2.x);
box.height=abs(cor1.y-cor2.y);
box.x=min(cor1.x,cor2.x);
box.y=min(cor1.y,cor2.y);
Mat crop(img,box); //Selecting a ROI(region of interest) from the original pic
namedWindow("Cropped Image");
imshow("Cropped Image",crop); //showing the cropped image
leftDown=false;
leftup=false;
}
}
For details you can visit the link Cropping the Image using Mouse
it might be because of authorisation issues; that was the case for me.
If you have for example: [Authorize("WriteAccess")]
or [Authorize("ReadAccess")]
at the top of your controller functions, try to comment them out.
You can also enable multiple GPU cores, like so:
import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]="0,2,3,4"
Use repr
and eval
:
>>> s = set([1,2,3])
>>> strs = repr(s)
>>> strs
'set([1, 2, 3])'
>>> eval(strs)
set([1, 2, 3])
Note that eval
is not safe if the source of string is unknown, prefer ast.literal_eval
for safer conversion:
>>> from ast import literal_eval
>>> s = set([10, 20, 30])
>>> lis = str(list(s))
>>> set(literal_eval(lis))
set([10, 20, 30])
help on repr
:
repr(object) -> string
Return the canonical string representation of the object.
For most object types, eval(repr(object)) == object.
I had the same issue. In this case imports [...]
is crucial, because it won't work if you don't import NgbModalModule
.
Error description says that components should be added to entryComponents
array and it is obvious, but make sure you have added this one in the first place:
imports: [
...
NgbModalModule,
...
],
You can do this in one query if you're willing to change its name:
ALTER TABLE table_name
DROP FOREIGN KEY `fk_name`,
ADD CONSTRAINT `fk_name2` FOREIGN KEY (`remote_id`)
REFERENCES `other_table` (`id`)
ON DELETE CASCADE;
This is useful to minimize downtime if you have a large table.
this error usually shows if the name of your struct is different from the initialization of your struct in the code, so normally, c will find the name of the struct you put and if the original struct is not found, this would usually appear, or if you point a pointer pointed into that pointer, the error will show up.
The accepted answer is correct, but I prefer:
@{int count = 0;}
@foreach (var item in Model.Resources)
{
@Html.Raw(count <= 3 ? "<div class=\"resource-row\">" : "")
// some code
@Html.Raw(count <= 3 ? "</div>" : "")
@(count++)
}
I hope this inspires someone, even though I'm late to the party.
For people checking the existence to drop View
use this
From SQL Server 2016 CTP3
you can use new DIE statements instead of big IF
wrappers
syntax
DROP VIEW [ IF EXISTS ] [ schema_name . ] view_name [ ...,n ] [ ; ]
Query :
DROP VIEW IF EXISTS view_name
More info here
I developed a jQuery plugin that allows you to call any core PHP function or even user defined PHP functions as methods of the plugin: jquery.php
After including jquery and jquery.php in the head of our document and placing request_handler.php on our server we would start using the plugin in the manner described below.
For ease of use reference the function in a simple manner:
var P = $.fn.php;
Then initialize the plugin:
P('init',
{
// The path to our function request handler is absolutely required
'path': 'http://www.YourDomain.com/jqueryphp/request_handler.php',
// Synchronous requests are required for method chaining functionality
'async': false,
// List any user defined functions in the manner prescribed here
// There must be user defined functions with these same names in your PHP
'userFunctions': {
languageFunctions: 'someFunc1 someFunc2'
}
});
And now some usage scenarios:
// Suspend callback mode so we don't work with the DOM
P.callback(false);
// Both .end() and .data return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25
// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]
Demonstrating PHP function chaining:
var data1 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).data();
var data2 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).end();
console.log( data1, data2 );
Demonstrating sending a JSON block of PHP pseudo-code:
var data1 =
P.block({
$str: "Let's use PHP's file_get_contents()!",
$opts:
[
{
http: {
method: "GET",
header: "Accept-language: en\r\n" +
"Cookie: foo=bar\r\n"
}
}
],
$context:
{
stream_context_create: ['$opts']
},
$contents:
{
file_get_contents: ['http://www.github.com/', false, '$context']
},
$html:
{
htmlentities: ['$contents']
}
}).data();
console.log( data1 );
The backend configuration provides a whitelist so you can restrict which functions can be called. There are a few other patterns for working with PHP described by the plugin as well.
I'm jumping in here a little late, but came across this page when pondering it myself. Of course I don't know how Facebook or Twitter justified it, but here is my own thought process for what it's worth.
In the end, I concluded that this practice is not that unsemantic (is that a word?). In fact, besides shortness and the nice association of "i is for icon," I think it's actually the most semantic choice for an icon when a straightforward <img>
tag is not practical.
1. The usage is consistent with the spec.
While it may not be what the W3 mainly had in mind, it seems to me the official spec for <i>
could accommodate an icon pretty easily. After all, the reply-arrow symbol is saying "reply" in another way. It expresses a technical term that may be unfamiliar to the reader and would be typically italicized. ("Here at Twitter, this is what we call a reply arrow.") And it is a term from another language: a symbolic language.
If, instead of the arrow symbol, Twitter used <i>shout out</i>
or <i>[Japanese character for reply]</i>
(on an English page), that would be consistent with the spec. Then why not <i>[reply arrow]</i>
? (I'm talking strictly HTML semantics here, not accessibility, which I'll get to.)
As far as I can see, the only part of the spec explicitly violated by icon usage is the "span of text" phrase (when the tag doesn't contain text also). It is clear that the <i>
tag is mainly meant for text, but that's a pretty small detail compared with the overall intent of the tag. The important question for this tag is not what format of content it contains, but what the meaning of that content is.
This is especially true when you consider that the line between "text" and "icon" can be almost nonexistent on websites. Text may look like more like an icon (as in the Japanese example) or an icon may look like text (as in a jpg button that says "Submit" or a cat photo with an overlaid caption) or text may be replaced or enhanced with an image via CSS. Text, image - who cares? It's all content. As long as everyone - humans with impairments, browsers with impairments, search engine spiders, and other machines of various kinds can understand that meaning, we've done our job.
So the fact that the writers of the spec didn't think (or choose) to clarify this shouldn't tie our hands from doing what makes sense and is consistent with the spirit of the tag. The <a>
tag was originally intended to take the user somewhere else, but now it might pop up a lightbox. Big whoop, right? If someone had figured out how to pop up a lightbox on click before the spec caught up, they still should have used the <a>
tag, not a <span>
, even if it wasn't entirely consistent with the current definition - because it came the closest and was still consistent with the spirit of the tag ("something will happen when you click here"). Same deal with <i>
- whatever type of thing you put inside it, or however creatively you use it, it expresses the general idea of an alternate or set-apart term.
2. The <i>
tag adds semantic meaning to an icon element.
The alternative option to carry an icon class by itself is <span>
, which of course has no semantic meaning whatsoever. When a machine asks the <span>
what it contains, it says, "I don't know. Could be anything." But the <i>
tag says, "I contain a different way of saying something than the usual way, or maybe an unfamiliar term." That's not the same as "I contain an icon," but it's a lot closer to it than <span>
got!
3. Eventually, common usage makes right.
In addition to the above, it's worth considering that machine readers (whether search engine, screen reader, or whatever) may at any time begin to take into account that Facebook, Twitter, and other websites use the <i>
tag for icons. They don't care about the spec as much as they care about extracting meaning from code by whatever means necessary. So they might use this knowledge of common usage to simply record that "there may be an icon here" or do something more advanced like triggering a look into the CSS for a hint to meaning, or who knows what. So if you choose to use the <i>
for icons on your website, you may be providing more meaning than the spec does.
Moreover, if this usage becomes widespread, it will likely be included in the spec in the future. Then you'll be going through your code, replacing <span>
s with <i>
's! So it may make sense to get on board with what seems to be the direction of the spec, especially when it doesn't clearly conflict with the current spec. Common usage tends to dictate language rules more than the other way around. If you're old enough, do you remember that "Web site" was the official spelling when the word was new? Dictionaries insisted there must be a space and Web must be capitalized. There were semantic reasons for that. But common usage said, "Whatever, that's stupid. I'm using 'website' because it's more concise and looks better." And before long, dictionaries officially acknowledged that spelling as correct.
4. So I'm going ahead and using it.
So, <i>
provides more meaning to machines because of the spec, it provides more meaning to humans because we easily associate "i" with "icon", and it's only one letter long. Win! And if you make sure to include equivalent text either inside the <i>
tag or right next to it (as Twitter does), then screen readers understand where to click to reply, the link is usable if CSS doesn't load, and human readers with good eyesight and a decent browser see a pretty icon. With all this in mind, I don't see the downside.
Probably the simplest way to do it is to create a delegate and then BeginInvoke
, followed by a wait at some time in the future, and an EndInvoke
.
public bool Foo(){
Thread.Sleep(100000); // Do work
return true;
}
public SomeMethod()
{
var fooCaller = new Func<bool>(Foo);
// Call the method asynchronously
var asyncResult = fooCaller.BeginInvoke(null, null);
// Potentially do other work while the asynchronous method is executing.
// Finally, wait for result
asyncResult.AsyncWaitHandle.WaitOne();
bool fooResult = fooCaller.EndInvoke(asyncResult);
Console.WriteLine("Foo returned {0}", fooResult);
}
You can provide your own sort function to list.sort()
:
The sort() method takes optional arguments for controlling the comparisons.
cmp specifies a custom comparison function of two arguments (list items) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument:
cmp=lambda x,y: cmp(x.lower(), y.lower())
. The default value isNone
.key specifies a function of one argument that is used to extract a comparison key from each list element:
key=str.lower
. The default value isNone
.reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.
In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once.
I think the easiest way to solve this issue, if you only need it on 1 or 2 boxes is by using the HTML input's "onsubmit" function.
Check this out and i will explain what it does:
<input type="text" name="val" onsubmit="if(this == ''){$this.val('empty');}" />
So we have created the HTML text box, assigned it a name ("val" in this case) and then we added the onsubmit code, this code checks to see if the current input box is empty and if it is, then, upon form submit it will fill it with the words empty.
Please note, this code should also function perfectly when using the HTML "Placeholder" tag as the placeholder tag doesn't actually assign a value to the input box.
If you don't care if the code within the timer
may take longer than your interval, use setInterval()
:
setInterval(function, delay)
That fires the function passed in as first parameter over and over.
A better approach is, to use setTimeout
along with a self-executing anonymous
function:
(function(){
// do some stuff
setTimeout(arguments.callee, 60000);
})();
that guarantees, that the next call is not made before your code was executed. I used arguments.callee
in this example as function reference. It's a better way to give the function a name and call that within setTimeout
because arguments.callee
is deprecated in ecmascript 5.
I think there is a problem when the 'div' tags are too much nested. I am trying to parse some contacts from a facebook html file, and the Beautifulsoup is not able to find tags "div" with class "fcontent".
This happens with other classes as well. When I search for divs in general, it turns only those that are not so much nested.
The html source code can be any page from facebook of the friends list of a friend of you (not the one of your friends). If someone can test it and give some advice I would really appreciate it.
This is my code, where I just try to print the number of tags "div" with class "fcontent":
from BeautifulSoup import BeautifulSoup
f = open('/Users/myUserName/Desktop/contacts.html')
soup = BeautifulSoup(f)
list = soup.findAll('div', attrs={'class':'fcontent'})
print len(list)
I'm running on a Dell XPS 15. Rather than stuffing around with resolutions and magnifications and all that, I just did the following:
Everything seems to work fine and the display looks good (if a bit blurry/pixelly). The only difference i can see is that the title bar is in Windows XP style (oh no!!!).
I'm curious to know if this works for others and if anyone comes across any problems.
You can use the eclipse plugin as suggested by Oscar earlier. Or if you are a command line person, you can use Apache Axis WSDL2Java tool from command prompt. You can find more details here http://axis.apache.org/axis/java/reference.html#WSDL2JavaReference
Or even just:
<div id="full-size">
Your contents go here
</div>
html,body{ margin:0; padding:0; height:100%; width:100%; }
#full-size{
height:100%;
width:100%;
overflow:hidden; /* or overflow:auto; if you want scrollbars */
}
(html, body can be set to like.. 95%-99% or some such to account for slight inconsistencies in margins, etc.)
To customize tool bar style, first create tool bar custom style inheriting Widget.AppCompat.Toolbar, override properties and then add it to custom app theme as shown below, see http://www.zoftino.com/android-toolbar-tutorial for more information tool bar and styles.
<style name="MyAppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="toolbarStyle">@style/MyToolBarStyle</item>
</style>
<style name="MyToolBarStyle" parent="Widget.AppCompat.Toolbar">
<item name="android:background">#80deea</item>
<item name="titleTextAppearance">@style/MyTitleTextAppearance</item>
<item name="subtitleTextAppearance">@style/MySubTitleTextAppearance</item>
</style>
<style name="MyTitleTextAppearance" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
<item name="android:textSize">35dp</item>
<item name="android:textColor">#ff3d00</item>
</style>
<style name="MySubTitleTextAppearance" parent="TextAppearance.Widget.AppCompat.Toolbar.Subtitle">
<item name="android:textSize">30dp</item>
<item name="android:textColor">#1976d2</item>
</style>
This error happens because you didn't install composer on your project.
run composer install
command in your project path.
I checked all the answers and the best one seemed to be (which isn't):
<img src="image.png?cache=none">
at first.
However, if you add cache=none parameter (which is static "none" word), it doesn't effect anything, browser still loads from cache.
Solution to this problem was:
<img src="image.png?nocache=<?php echo time(); ?>">
where you basically add unix timestamp to make the parameter dynamic and no cache, it worked.
However, my problem was a little different: I was loading on the fly generated php chart image, and controlling the page with $_GET parameters. I wanted the image to be read from cache when the URL GET parameter stays the same, and do not cache when the GET parameters change.
To solve this problem, I needed to hash $_GET but since it is array here is the solution:
$chart_hash = md5(implode('-', $_GET));
echo "<img src='/images/mychart.png?hash=$chart_hash'>";
Edit:
Although the above solution works just fine, sometimes you want to serve the cached version UNTIL the file is changed. (with the above solution, it disables the cache for that image completely) So, to serve cached image from browser UNTIL there is a change in the image file use:
echo "<img src='/images/mychart.png?hash=" . filemtime('mychart.png') . "'>";
filemtime() gets file modification time.
As per my answer to this similar issue;
Try unlocking the relevant IIS configuration settings at server level, as follows:
If you're getting this error in the build somewhere else, while your IDE says everything is perfectly fine, then check that you are using the same Java versions in both places.
For example, Java 7 and Java 8 have different APIs, so calling a non-existent API in an older Java version would cause this error.
Your keystore is broken, and you will have to restore or regenerate it.
Just use the atol()
function:
#include <stdio.h>
#include <stdlib.h>
int main()
{
const char *c = "5";
int d = atol(c);
printf("%d\n", d);
}
It failed because you used ajax="false"
. This fires a full synchronous request which in turn causes a full page reload, causing the oncomplete
to be never fired (note that all other ajax-related attributes like process
, onstart
, onsuccess
, onerror
and update
are also never fired).
That it worked when you removed actionListener
is also impossible. It should have failed the same way. Perhaps you also removed ajax="false"
along it without actually understanding what you were doing. Removing ajax="false"
should indeed achieve the desired requirement.
Also is it possible to execute actionlistener and oncomplete simultaneously?
No. The script can only be fired before or after the action listener. You can use onclick
to fire the script at the moment of the click. You can use onstart
to fire the script at the moment the ajax request is about to be sent. But they will never exactly simultaneously be fired. The sequence is as follows:
onclick
JavaScript code is executedprocess
and current HTML DOM treeonstart
JavaScript code is executedprocess
actionListener
JSF backing bean method is executedaction
JSF backing bean method is executedupdate
and current JSF component treeonsuccess
JavaScript code is executedonerror
JavaScript code is executedupdate
based on ajax response and current HTML DOM treeoncomplete
JavaScript code is executedNote that the update
is performed after actionListener
, so if you were using onclick
or onstart
to show the dialog, then it may still show old content instead of updated content, which is poor for user experience. You'd then better use oncomplete
instead to show the dialog. Also note that you'd better use action
instead of actionListener
when you intend to execute a business action.
Try this:
With xlApp.ActiveSheet.Pictures.Insert(PicPath)
With .ShapeRange
.LockAspectRatio = msoTrue
.Width = 75
.Height = 100
End With
.Left = xlApp.ActiveSheet.Cells(i, 20).Left
.Top = xlApp.ActiveSheet.Cells(i, 20).Top
.Placement = 1
.PrintObject = True
End With
It's better not to .select anything in Excel, it is usually never necessary and slows down your code.
I'd go with COUNT(1)
. It is faster than COUNT(*)
because COUNT(*)
tests to see if at least one column in that row is != NULL. You don't need that, especially because you already have a condition in place (the WHERE
clause). COUNT(1)
instead tests the validity of 1
, which is always valid and takes a lot less time to test.
line=$(head -1 file)
Will work fine. (As previous answer). But
line=$(read -r FIRSTLINE < filename)
will be marginally faster as read
is a built-in bash command.
Use:
$.ajax({
url: 'feed/4', type: 'POST', data: "_METHOD=PUT&accessToken=63ce0fde", success: function(data) {
console.log(data);
}
});
Always remember to use _METHOD=PUT
.
Add this to the end of your proc: option(recompile)
This will make the report run almost as fast as the stored procedure
(&:name) is short for (&:name.to_proc) it is same as tags.map{ |t| t.name }.join(' ')
to_proc is actually implemented in C
Unless there is a single row in the ASSIGNMENT
table and ASSIGNMENT_20081120
is a local PL/SQL variable of type ASSIGNMENT%ROWTYPE
, this is not what you want.
Assuming you are trying to create a new table and copy the existing data to that new table
CREATE TABLE assignment_20081120
AS
SELECT *
FROM assignment
Note: The snippet would only work if the iframe is with the same origin.
Other answers proposed the load
event, but it fires after the new page in the iframe is loaded. You might need to be notified immediately after the URL changes, not after the new page is loaded.
Here's a plain JavaScript solution:
function iframeURLChange(iframe, callback) {_x000D_
var unloadHandler = function () {_x000D_
// Timeout needed because the URL changes immediately after_x000D_
// the `unload` event is dispatched._x000D_
setTimeout(function () {_x000D_
callback(iframe.contentWindow.location.href);_x000D_
}, 0);_x000D_
};_x000D_
_x000D_
function attachUnload() {_x000D_
// Remove the unloadHandler in case it was already attached._x000D_
// Otherwise, the change will be dispatched twice._x000D_
iframe.contentWindow.removeEventListener("unload", unloadHandler);_x000D_
iframe.contentWindow.addEventListener("unload", unloadHandler);_x000D_
}_x000D_
_x000D_
iframe.addEventListener("load", attachUnload);_x000D_
attachUnload();_x000D_
}_x000D_
_x000D_
iframeURLChange(document.getElementById("mainframe"), function (newURL) {_x000D_
console.log("URL changed:", newURL);_x000D_
});
_x000D_
<iframe id="mainframe" src=""></iframe>
_x000D_
This will successfully track the src
attribute changes, as well as any URL changes made from within the iframe itself.
Tested in all modern browsers.
I made a gist with this code as well. You can check my other answer too. It goes a bit in-depth into how this works.
No, the IEnumerable doesn't support adding items to it.
Your 'alternative' is:
var myList = new List(items);
myList.Add(otherItem);
Posting this for Xamarin users.
The key to detecting if the app was launched via a push notification is the AppDelegate.FinishedLaunching(UIApplication app, NSDictionary options)
method, and the options dictionary that's passed in.
The options dictionary will have this key in it if it's a local notification: UIApplication.LaunchOptionsLocalNotificationKey
.
If it's a remote notification, it will be UIApplication.LaunchOptionsRemoteNotificationKey
.
When the key is LaunchOptionsLocalNotificationKey
, the object is of type UILocalNotification
.
You can then look at the notification and determine which specific notification it is.
Pro-tip: UILocalNotification
doesn't have an identifier in it, the same way UNNotificationRequest
does. Put a dictionary key in the UserInfo containing a requestId so that when testing the UILocalNotification
, you'll have a specific requestId available to base some logic on.
I found that even on iOS 10+ devices that when creating location notifications using the UNUserNotificationCenter
's AddNotificationRequest
& UNMutableNotificationContent
, that when the app is not running(I killed it), and is launched by tapping the notification in the notification center, that the dictionary still contains the UILocalNotificaiton
object.
This means that my code that checks for notification based launch will work on iOS8 and iOS 10+ devices
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
_logger.InfoFormat("FinishedLaunching");
if(options != null)
{
if (options.ContainsKey(UIApplication.LaunchOptionsLocalNotificationKey))
{
//was started by tapping a local notification when app wasn't previously running.
//works if using UNUserNotificationCenter.Current.AddNotificationRequest OR UIApplication.SharedApplication.PresentLocalNotificationNow);
var localNotification = options[UIApplication.LaunchOptionsLocalNotificationKey] as UILocalNotification;
//I would recommended a key such as this :
var requestId = localNotification.UserInfo["RequestId"].ToString();
}
}
return true;
}
The fastest MySQL
solution, without inner queries and without GROUP BY
:
SELECT m.* -- get the row that contains the max value
FROM topten m -- "m" from "max"
LEFT JOIN topten b -- "b" from "bigger"
ON m.home = b.home -- match "max" row with "bigger" row by `home`
AND m.datetime < b.datetime -- want "bigger" than "max"
WHERE b.datetime IS NULL -- keep only if there is no bigger than max
Explanation:
Join the table with itself using the home
column. The use of LEFT JOIN
ensures all the rows from table m
appear in the result set. Those that don't have a match in table b
will have NULL
s for the columns of b
.
The other condition on the JOIN
asks to match only the rows from b
that have bigger value on the datetime
column than the row from m
.
Using the data posted in the question, the LEFT JOIN
will produce this pairs:
+------------------------------------------+--------------------------------+
| the row from `m` | the matching row from `b` |
|------------------------------------------|--------------------------------|
| id home datetime player resource | id home datetime ... |
|----|-----|------------|--------|---------|------|------|------------|-----|
| 1 | 10 | 04/03/2009 | john | 399 | NULL | NULL | NULL | ... | *
| 2 | 11 | 04/03/2009 | juliet | 244 | NULL | NULL | NULL | ... | *
| 5 | 12 | 04/03/2009 | borat | 555 | NULL | NULL | NULL | ... | *
| 3 | 10 | 03/03/2009 | john | 300 | 1 | 10 | 04/03/2009 | ... |
| 4 | 11 | 03/03/2009 | juliet | 200 | 2 | 11 | 04/03/2009 | ... |
| 6 | 12 | 03/03/2009 | borat | 500 | 5 | 12 | 04/03/2009 | ... |
| 7 | 13 | 24/12/2008 | borat | 600 | 8 | 13 | 01/01/2009 | ... |
| 8 | 13 | 01/01/2009 | borat | 700 | NULL | NULL | NULL | ... | *
+------------------------------------------+--------------------------------+
Finally, the WHERE
clause keeps only the pairs that have NULL
s in the columns of b
(they are marked with *
in the table above); this means, due to the second condition from the JOIN
clause, the row selected from m
has the biggest value in column datetime
.
Read the SQL Antipatterns: Avoiding the Pitfalls of Database Programming book for other SQL tips.
For Babel version 7, if your are using @babel/preset-env, to include polyfill all you have to do is add a flag 'useBuiltIns' with the value of 'usage' in your babel configuration. There is no need to require or import polyfill at the entry point of your App.
With this flag specified, babel@7 will optimize and only include the polyfills you needs.
To use this flag, after installation:
npm install --save-dev @babel/core @babel/cli @babel/preset-env
npm install --save @babel/polyfill
Simply add the flag:
useBuiltIns: "usage"
to your babel configuration file called "babel.config.js" (also new to Babel@7), under the "@babel/env" section:
// file: babel.config.js
module.exports = () => {
const presets = [
[
"@babel/env",
{
targets: { /* your targeted browser */ },
useBuiltIns: "usage" // <-----------------*** add this
}
]
];
return { presets };
};
Reference:
Update Aug 2019:
With the release of Babel 7.4.0 (March 19, 2019) @babel/polyfill is deprecated. Instead of installing @babe/polyfill, you will install core-js:
npm install --save core-js@3
A new entry corejs
is added to your babel.config.js
// file: babel.config.js
module.exports = () => {
const presets = [
[
"@babel/env",
{
targets: { /* your targeted browser */ },
useBuiltIns: "usage",
corejs: 3 // <----- specify version of corejs used
}
]
];
return { presets };
};
see example: https://github.com/ApolloTang/stackoverflow-eg--babel-v7.4.0-polyfill-w-core-v3
Reference:
You could do this with the CSS3 :target selector.
menu:hover block {
visibility: visible;
}
block:target {
visibility:hidden;
}
\d{1,2}[\,\.]{1}\d{1,2}
EDIT: update to meet the new requirements (comments) ;)
EDIT: remove unnecesary qtfier as per Bryan
^[0-9]{1,2}([,.][0-9]{1,2})?$
If you don't really need the button element, just move the classes to a regular link:
<div class="btn-group">
<a href="/save/1" class="btn btn-primary active">
<i class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></i> Save
</a>
<a href="/cancel/1" class="btn btn-default">Cancel</a>
</div>
Conversely, you can also change a button to appear like a link:
<button type="button" class="btn btn-link">Link</button>
Try This...
<html>_x000D_
_x000D_
<head>_x000D_
<script>_x000D_
function myFunction() {_x000D_
var number = "123";_x000D_
document.getElementById("myText").innerHTML = number;_x000D_
}_x000D_
</script>_x000D_
</head>_x000D_
_x000D_
<body onload="myFunction()">_x000D_
_x000D_
<h1>"The value for number is: " <span id="myText"></span></h1>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
I have a solution for GSuite accounts that doesnt have the "@gmail.com" sufix. Also I think it will work for GSuite accounts with the @gmail.com but havent tried it. First you should have the privileges to change the option "allos¿w less secure app" for your GSuite account. If you have the privileges (you can check in account settings->security) then you have to deactivate "two step factor authentication" go to the end of the page and set to "yes" for allow less secure applications. That's all. If you dont have privileges to change those options the solution for this thread will not work. Check https://support.google.com/a/answer/6260879?hl=en to make changes to "allow less..." option.
If you want to print the last 10 lines, use
tail(dataset, 10)
for the first 10, you could also do
head(dataset, 10)
I realize this post is old, but there's no marked solution and I just wanted to throw in how I resolved this.
The first Error 5: Access Denied
error was resolved by giving permissions to the output directory to the NETWORK SERVICE
account.
The second Started and then stopped
error seems to be a generic message when something faulted the service. Check the Event Viewer (specifically the 'Windows Logs > Application') for the real error message.
In my case, it was a bad service configuration setting in app.config.
PDFBox is the best library I've found for this purpose, it's comprehensive and really quite easy to use if you're just doing basic text extraction. Examples can be found here.
It explains it on the page, but one thing to watch out for is that the start and end indexes when using setStartPage() and setEndPage() are both inclusive. I skipped over that explanation first time round and then it took me a while to realise why I was getting more than one page back with each call!
Itext is another alternative that also works with C#, though I've personally never used it. It's more low level than PDFBox, so less suited to the job if all you need is basic text extraction.
In SQL server 2005 new datatypes were introduced: varchar(max)
and nvarchar(max)
They have the advantages of the old text type: they can contain op to 2GB of data, but they also have most of the advantages of varchar
and nvarchar
. Among these advantages are the ability to use string manipulation functions such as substring().
Also, varchar(max) is stored in the table's (disk/memory) space while the size is below 8Kb. Only when you place more data in the field, it's is stored out of the table's space. Data stored in the table's space is (usually) retrieved quicker.
In short, never use Text, as there is a better alternative: (n)varchar(max). And only use varchar(max) when a regular varchar is not big enough, ie if you expect teh string that you're going to store will exceed 8000 characters.
As was noted, you can use SUBSTRING on the TEXT datatype,but only as long the TEXT fields contains less than 8000 characters.
Back when the world was young and in the PC world you chose from .exe or .bat, the delineation was simple. Unix systems have always had shell scripts (/bin/sh, /bin/csh, /bin/ksh, etc) and Compiled languages (C/C++/Fortran).
To differentiate roles and responsibilities, the compiled languages (often referred to as 3rd Generation Languages) were seen a 'programming' languages and 'scripting' languages were seen as those that invoked an interpreter (often referred to as 4th Generation Languages). Scripting languages were often used as 'glue' to connect between multiple commands/compiled programs so that the user didn't have to worry about a set of steps in order to carry out their task - they developed a single file, that delineated what steps they wanted to accomplish, and this became a 'script' for anyone to follow.
Various people/groups wrote new interpreters to solve a specific problem domain. awk is one of the better-known ones, and it was used mostly for pattern matching and applying a series of data transforms on input. It worked well, but had a limited problem domain. The expansion of that domain was all but impossible because the source code was unavailable. Perl (Larry Wall, principle author/architect) tool scripting to the next level - and developed an interpreter that not only allowed the user to run system commands, manipulate input and output data, supported typeless variables, but also to access Unix system level APIs as functions from within the scripts themselves. It was probably one of the first widely used high-level scripting languages. It is with Perl (IMHO) that scripting languages crossed the arbitrary line and added the capabilities of programming languages.
Your question was specifically about Python. Because the python interpreter runs against a text file containing the python code, and that the python code can run anywhere that there is a python interpreter, I would say that it is a scripting language (in the same vein as Perl). You do not need to recompile the user python command file for each different OS/CPU Architecture (as you would with C/C++/Fortran), making it significantly more portable and easier to use.
Credit for this answer goes to Jerrold (Jerry) Heyman. Original thread: https://www.researchgate.net/post/Is_Python_a_Programming_language_or_Scripting_Language
I just whipped this up for CBV. Not used in production but generates a PDF for me. Probably needs work for the error reporting side of things but does the trick so far.
import StringIO
from cgi import escape
from xhtml2pdf import pisa
from django.http import HttpResponse
from django.template.response import TemplateResponse
from django.views.generic import TemplateView
class PDFTemplateResponse(TemplateResponse):
def generate_pdf(self, retval):
html = self.content
result = StringIO.StringIO()
rendering = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)
if rendering.err:
return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))
else:
self.content = result.getvalue()
def __init__(self, *args, **kwargs):
super(PDFTemplateResponse, self).__init__(*args, mimetype='application/pdf', **kwargs)
self.add_post_render_callback(self.generate_pdf)
class PDFTemplateView(TemplateView):
response_class = PDFTemplateResponse
Used like:
class MyPdfView(PDFTemplateView):
template_name = 'things/pdf.html'
Try keydown
instead of keypress
.
The keyboard events occur in this order: keydown
, keyup
, keypress
The problem with backspace probably is, that the browser will navigate back on keyup
and thus your page will not see the keypress
event.
Have a look in the syslogins or sysusers tables in the master schema. Not sure if this still still around in more recent MSSQL versions though. In MSSQL 2005 there are views called sys.syslogins and sys.sysusers.
grid.store = store;
store.load({ params: { start: 0, limit: 20} });
grid.getView().refresh();
You should probably set all of the cookie properties not just the value of it. setPath()
, setDomain()
... etc
You can use the following. They all wrap the window
object into a jQuery object.
$(window).load(function () {
topInViewport($("#mydivname"))
});
$(window).resize(function () {
topInViewport($("#mydivname"))
});
$(window).scroll(function () {
topInViewport($("#mydivname"))
});
Or bind to them all using on
:
$(window).on("load resize scroll",function(e){
topInViewport($("#mydivname"))
});
<html>
<table>
<tr>
<td style="padding-left: 5px;padding-bottom:3px; font-size:35px;"> <b>Datum:</b><br/>
November 2010 </td>
</table>
</html>
If you are using LESS
or Sass
, You can try this:
.btn {
&[disabled] {
opacity: 0.6;
}
&:hover, &:active {
&:not([disabled]) {
background-color: darken($orange, 15);
}
}
}
I had the same issue when switching from a dev branch to master branch. What I did was commit my changes and switch to the master branch. You might have uncommitted changes.
I write a function support dynamic variable string append, like PHP str append: str . str . ... etc.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
int str_append(char **json, const char *format, ...)
{
char *str = NULL;
char *old_json = NULL, *new_json = NULL;
va_list arg_ptr;
va_start(arg_ptr, format);
vasprintf(&str, format, arg_ptr);
// save old json
asprintf(&old_json, "%s", (*json == NULL ? "" : *json));
// calloc new json memory
new_json = (char *)calloc(strlen(old_json) + strlen(str) + 1, sizeof(char));
strcat(new_json, old_json);
strcat(new_json, str);
if (*json) free(*json);
*json = new_json;
free(old_json);
free(str);
return 0;
}
int main(int argc, char *argv[])
{
char *json = NULL;
/*
str_append(&json, "name: %d, %d, %d", 1, 2, 3);
str_append(&json, "sex: %s", "male");
str_append(&json, "end");
str_append(&json, "");
str_append(&json, "{\"ret\":true}");
*/
int i;
for (i = 0; i < 100; i++) {
str_append(&json, "id-%d", i);
}
printf("%s\n", json);
if (json) free(json);
return 0;
}
In Unix it is probably easier to use 'tr' command.
cat file1.txt | tr "\r" "\n" > file2.txt
In my case, I solved it when I changed in function that does sql query
after: return json_encode($array)
then: return $array
They are not managed, but measured and possibly limited (see getrlimit
system call, also on getrlimit(2)).
RSS means resident set size (the part of your virtual address space sitting in RAM).
You can query the virtual address space of process 1234 using proc(5) with cat /proc/1234/maps
and its status (including memory consumption) thru cat /proc/1234/status
Here's my code for adding a new row to a two-column TableLayoutColumn:
private void AddRow(Control label, Control value)
{
int rowIndex = AddTableRow();
detailTable.Controls.Add(label, LabelColumnIndex, rowIndex);
if (value != null)
{
detailTable.Controls.Add(value, ValueColumnIndex, rowIndex);
}
}
private int AddTableRow()
{
int index = detailTable.RowCount++;
RowStyle style = new RowStyle(SizeType.AutoSize);
detailTable.RowStyles.Add(style);
return index;
}
The label control goes in the left column and the value control goes in the right column. The controls are generally of type Label and have their AutoSize property set to true.
I don't think it matters too much, but for reference, here is the designer code that sets up detailTable:
this.detailTable.ColumnCount = 2;
this.detailTable.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.detailTable.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.detailTable.Dock = System.Windows.Forms.DockStyle.Fill;
this.detailTable.Location = new System.Drawing.Point(0, 0);
this.detailTable.Name = "detailTable";
this.detailTable.RowCount = 1;
this.detailTable.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.detailTable.Size = new System.Drawing.Size(266, 436);
this.detailTable.TabIndex = 0;
This all works just fine. You should be aware that there appear to be some problems with disposing controls from a TableLayoutPanel dynamically using the Controls property (at least in some versions of the framework). If you need to remove controls, I suggest disposing the entire TableLayoutPanel and creating a new one.
try creating connection string this way:
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "mysql7.000webhost.com";
conn_string.UserID = "a455555_test";
conn_string.Password = "a455555_me";
conn_string.Database = "xxxxxxxx";
using (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))
using (MySqlCommand cmd = conn.CreateCommand())
{ //watch out for this SQL injection vulnerability below
cmd.CommandText = string.Format("INSERT Test (lat, long) VALUES ({0},{1})",
OSGconv.deciLat, OSGconv.deciLon);
conn.Open();
cmd.ExecuteNonQuery();
}
You can retrieve the contents of an iframe
first and then use jQuery
selectors against them as usual.
$("#iframe-id").contents().find("img").attr("style","width:100%;height:100%")
$("#iframe-id").contents().find("img").addClass("fancy-zoom")
$("#iframe-id").contents().find("img").onclick(function(){ zoomit($(this)); });
Good Luck!
If you'd like to have your JAVA_HOME recognised by intellij, you can do one of these:
launchctl setenv JAVA_HOME "/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home"
As others have answered you can ignore JAVA_HOME by setting up SDK in project structure.
small scripts for drag and drop by angular
(function(angular) {
'use strict';
angular.module('drag', []).
directive('draggable', function($document) {
return function(scope, element, attr) {
var startX = 0, startY = 0, x = 0, y = 0;
element.css({
position: 'relative',
border: '1px solid red',
backgroundColor: 'lightgrey',
cursor: 'pointer',
display: 'block',
width: '65px'
});
element.on('mousedown', function(event) {
// Prevent default dragging of selected content
event.preventDefault();
startX = event.screenX - x;
startY = event.screenY - y;
$document.on('mousemove', mousemove);
$document.on('mouseup', mouseup);
});
function mousemove(event) {
y = event.screenY - startY;
x = event.screenX - startX;
element.css({
top: y + 'px',
left: x + 'px'
});
}
function mouseup() {
$document.off('mousemove', mousemove);
$document.off('mouseup', mouseup);
}
};
});
})(window.angular);
Another option is to use the getBoundingClientRect function. Please note that getBoundingClientRect will return an empty rect if the element's display is 'none'.
var elem = document.getElementById("myDiv");
if(elem) {
var rect = elem.getBoundingClientRect();
console.log(rect.width);
}
File->Project Structure->Project pane->"Android plugin version".
Make sure you don't confuse the Gradle version with the Android plugin version. The former is the build system itself, the latter is the plugin to the build system that knows how to build Android projects
Do you have an activity set up the be the launched activity when the application starts?
This is done in your Manifest.xml file, something like:
<activity android:name=".Main" android:label="@string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
$('.formData').attr('value','YOUR_VALUE')
Add <input>
to <td>
when it is clicked.
Change <input>
to <span>
when it is blurred.
One way I like to use is Vanilla JavaScript with template literal:
var templateLiteral = [`
<!-- HTML_CODE_COMES_HERE -->
`]
var head = document.querySelector("head");
head.innerHTML = templateLiteral;
On the File menu, choose Advanced Save Options, you can control it there.
Edit: Here's the documentation, you should have a file open first.
puts 'abcdefg'.start_with?('abc') #=> true
[edit] This is something I didn't know before this question: start_with
takes multiple arguments.
'abcdefg'.start_with?( 'xyz', 'opq', 'ab')
I like using pandas.apply() with python format().
import pandas as pd
s = pd.Series([1.357, 1.489, 2.333333])
make_float = lambda x: "${:,.2f}".format(x)
s.apply(make_float)
Also, it can be easily used with multiple columns...
df = pd.concat([s, s * 2], axis=1)
make_floats = lambda row: "${:,.2f}, ${:,.3f}".format(row[0], row[1])
df.apply(make_floats, axis=1)
NSString *str1 = @"Share Role Play Photo via Facebook, or Twitter for free coins per photo.";
NSString *str2 = @"Like Role Play on facebook for 50 free coins.";
NSString *str3 = @"Check out 'What's Hot' on other ways to receive free coins";
NSString *msg = [NSString stringWithFormat:@"%@\n%@\n%@", str1, str2, str3];
You can use the jquery .length property
var numItems = $('.item').length;
I would make your final select as:
SELECT EmplID
, EmplName
, InTime
, [TimeOut]
, [DateVisited]
, CONVERT(varchar(3),DATEDIFF(minute,InTime, TimeOut)/60) + ':' +
RIGHT('0' + CONVERT(varchar(2),DATEDIFF(minute,InTime,TimeOut)%60),2)
as TotalHours
from times
Order By EmplID, DateVisited
Any solution trying to use DATEDIFF(hour,...
is bound to be complicated (if it's correct) because DATEDIFF
counts transitions - DATEDIFF(hour,...09:59',...10:01')
will return 1 because of the transition of the hour from 9 to 10. So I'm just using DATEDIFF
on minutes.
The above can still be subtly wrong if seconds are involved (it can slightly overcount because its counting minute transitions) so if you need second or millisecond accuracy you need to adjust the DATEDIFF
to use those units and then apply suitable division constants (as per the hours one above) to just return hours and minutes.
Use the below approach to identify dates are sort or not
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
boolean decendingOrder = true;
for(int index=0;index<date.size() - 1; index++) {
if(simpleDateFormat.parse(date.get(index)).getTime() < simpleDateFormat.parse(date.get(index+1)).getTime()) {
decendingOrder = false;
break;
}
}
if(decendingOrder) {
System.out.println("Date are in Decending Order");
}else {
System.out.println("Date not in Decending Order");
}
}
@bogatron already gave the answer suggested by the matplotlib docs, which produces the right height, but it introduces a different problem. Now the width of the colorbar (as well as the space between colorbar and plot) changes with the width of the plot. In other words, the aspect ratio of the colorbar is not fixed anymore.
To get both the right height and a given aspect ratio, you have to dig a bit deeper into the mysterious axes_grid1
module.
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable, axes_size
import numpy as np
aspect = 20
pad_fraction = 0.5
ax = plt.gca()
im = ax.imshow(np.arange(200).reshape((20, 10)))
divider = make_axes_locatable(ax)
width = axes_size.AxesY(ax, aspect=1./aspect)
pad = axes_size.Fraction(pad_fraction, width)
cax = divider.append_axes("right", size=width, pad=pad)
plt.colorbar(im, cax=cax)
Note that this specifies the width of the colorbar w.r.t. the height of the plot (in contrast to the width of the figure, as it was before).
The spacing between colorbar and plot can now be specified as a fraction of the width of the colorbar, which is IMHO a much more meaningful number than a fraction of the figure width.
UPDATE:
I created an IPython notebook on the topic, where I packed the above code into an easily re-usable function:
import matplotlib.pyplot as plt
from mpl_toolkits import axes_grid1
def add_colorbar(im, aspect=20, pad_fraction=0.5, **kwargs):
"""Add a vertical color bar to an image plot."""
divider = axes_grid1.make_axes_locatable(im.axes)
width = axes_grid1.axes_size.AxesY(im.axes, aspect=1./aspect)
pad = axes_grid1.axes_size.Fraction(pad_fraction, width)
current_ax = plt.gca()
cax = divider.append_axes("right", size=width, pad=pad)
plt.sca(current_ax)
return im.axes.figure.colorbar(im, cax=cax, **kwargs)
It can be used like this:
im = plt.imshow(np.arange(200).reshape((20, 10)))
add_colorbar(im)
Looks like oldDTE.MyDateTime was null, so constructor tried to take it's Value - which threw.
In my case I was setting the RecyclerView's layoutManager
both in XML and in onViewCreated
. Removing the assignment in onViewCreated
fixed it.
with(_binding.list) {
// layoutManager = LinearLayoutManager(context)
adapter = MyAdapter().apply {
listViewModel.data.observe(viewLifecycleOwner,
Observer {
it?.let { setItems(it) }
})
}
}
I used some of the answers and found one that fit my case ( make sure all tasks are in the release branch).
Other methods works as well but I found that they might add lines that I do not need, like merge commits that add no value.
git fetch
git log origin/master..origin/release-1.1 --oneline --no-merges
or you can compare your current with master
git fetch
git log origin/master..HEAD --oneline --no-merges
git fetch
is there to make sure you are using updated info.
In this way each commit will be on a line and you can copy/paste that into an text editor and start comparing the tasks with the commits that will be merged.
A quick and copy/paste you can use for Chrome and Firefox would be: (change the stuff after the # to change the color)
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
-khtml-border-radius: 10px;
-border-radius: 10px;
-moz-box-shadow: 0 0 15px 5px #666;
-webkit-box-shadow: 0 0 15px 05px #666;
Matt Roberts' answer is correct for webkit browsers (safari, chrome, etc), but I thought someone out there might want a quick answer rather than be told to learn to program to make some shadows.
Use either the <button>
element or use an <input type="button"/>
.
onInputChange(evt) {
var tgt = evt.target || window.event.srcElement,
files = tgt.files;
if (FileReader && files && files.length) {
var fr = new FileReader();
fr.onload = function () {
var base64 = fr.result;
debugger;
}
fr.readAsDataURL(files[0]);
}
}
While Nate's answer is pretty good already, I'm going to expand on it more specifically for Visual Studio 2010 as requested, and include information on compiling in the various optional components which requires external libraries.
If you are using headers only libraries, then all you need to do is to unarchive the boost download and set up the environment variables. The instruction below set the environment variables for Visual Studio only, and not across the system as a whole. Note you only have to do it once.
C:\boost_1_47_0
).Microsoft.Cpp.<Platform>.user
, and select Properties
to open the Property Page for edit.VC++ Directories
on the left.Include Directories
section to include the path to your boost source files.If you want to use the part of boost that require building, but none of the features that requires external dependencies, then building it is fairly simple.
C:\boost_1_47_0
).bootstrap.bat
to build b2.exe (previously named bjam).Run b2:
b2 --toolset=msvc-10.0 --build-type=complete stage
; b2 --toolset=msvc-10.0 --build-type=complete architecture=x86 address-model=64 stage
Go for a walk / watch a movie or 2 / ....
Library Directories
section to include the path to your boost libraries output. (The default for the example and instructions above would be C:\boost_1_47_0\stage\lib
. Rename and move the directory first if you want to have x86 & x64 side by side (such as to <BOOST_PATH>\lib\x86
& <BOOST_PATH>\lib\x64
).If you want the optional components, then you have more work to do. These are:
Boost.IOStreams Bzip2 filters:
C:\bzip2-1.0.6
).-sBZIP2_SOURCE="C:\bzip2-1.0.6"
when running b2 in step 5.Boost.IOStreams Zlib filters
C:\zlib-1.2.5
).-sZLIB_SOURCE="C:\zlib-1.2.5"
when running b2 in step 5.Boost.MPI
project-config.jam
in the directory <BOOST_PATH>
that resulted from running bootstrap. Add in a line that read using mpi ;
(note the space before the ';').Boost.Python
To completely built the 32-bits version of the library requires 32-bits Python, and similarly for the 64-bits version. If you have multiple versions installed for such reason, you'll need to tell b2 where to find specific version and when to use which one. One way to do that would be to edit the file project-config.jam
in the directory <BOOST_PATH>
that resulted from running bootstrap. Add in the following two lines adjusting as appropriate for your Python installation paths & versions (note the space before the ';').
using python : 2.6 : C:\\Python\\Python26\\python ;
using python : 2.6 : C:\\Python\\Python26-x64\\python : : : <address-model>64 ;
Do note that such explicit Python specification currently cause MPI build to fail. So you'll need to do some separate building with and without specification to build everything if you're building MPI as well.
Follow the second set of instructions above to build boost.
Boost.Regex ICU support
C:\icu4c-4_8
).<ICU_PATH>\source\allinone
.-sICU_PATH="C:\icu4c-4_8"
when running b2 in step 5.If you just want to log the list of elements, you can use the list toString() method which already concatenates all the list elements.
Device: iPad Mini
OS: iOS 9 Beta 3
App downloaded from: Hockey App
Provisioning profile with Trust issues: Enterprise
In my case, when I navigate to Settings > General > Profiles, I could not see on any Apple provisioning profile. All I could see is a Configuration Profile which is HockeyApp Config.
Here are the steps that I followed:
That's it! You're done! You can now go back to your app and open it successfully. Hope this helped. :)
The communication link between the driver and the data source to which the driver was attempting to connect failed before the function completed processing. So usually its a network error. This could be caused by packet drops or badly configured Firewall/Switch.
You can handle all your actions in function of your message in onMessageReceived() in your service extending FirebaseMessagingService. In order to do that, you must send a message containing exclusively data, using for example Advanced REST client in Chrome. Then you send a POST to https://fcm.googleapis.com/fcm/send using in "Raw headers":
Content-Type: application/json Authorization: key=YOUR_PERSONAL_FIREBASE_WEB_API_KEY
And a json message in the field "Raw payload".
Warning, if there is the field "notification" in your json, your message will never be received when app in background in onMessageReceived(), even if there is a data field ! For example, doing that, message work just if app in foreground:
{
"condition": " 'Symulti' in topics || 'SymultiLite' in topics",
"priority" : "normal",
"time_to_live" : 0,
"notification" : {
"body" : "new Symulti update !",
"title" : "new Symulti update !",
"icon" : "ic_notif_symulti"
},
"data" : {
"id" : 1,
"text" : "new Symulti update !"
}
}
In order to receive your message in all cases in onMessageReceived(), simply remove the "notification" field from your json !
Example:
{
"condition": " 'Symulti' in topics || 'SymultiLite' in topics",
"priority" : "normal",
"time_to_live" : 0,,
"data" : {
"id" : 1,
"text" : "new Symulti update !",
"link" : "href://www.symulti.com"
}
}
and in your FirebaseMessagingService :
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String message = "";
obj = remoteMessage.getData().get("text");
if (obj != null) {
try {
message = obj.toString();
} catch (Exception e) {
message = "";
e.printStackTrace();
}
}
String link = "";
obj = remoteMessage.getData().get("link");
if (obj != null) {
try {
link = (String) obj;
} catch (Exception e) {
link = "";
e.printStackTrace();
}
}
Intent intent;
PendingIntent pendingIntent;
if (link.equals("")) { // Simply run your activity
intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
} else { // open a link
String url = "";
if (!link.equals("")) {
intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(link));
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
}
pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = null;
try {
notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notif_symulti) // don't need to pass icon with your message if it's already in your app !
.setContentTitle(URLDecoder.decode(getString(R.string.app_name), "UTF-8"))
.setContentText(URLDecoder.decode(message, "UTF-8"))
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(pendingIntent);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (notificationBuilder != null) {
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(id, notificationBuilder.build());
} else {
Log.d(TAG, "error NotificationManager");
}
}
}
}
Enjoy !
One of my favorite parts about registers is using them as macros!
Let's say you are dealing with a tab-delimited value file as such:
ID Df %Dev Lambda
1 0 0.000000 0.313682
2 1 0.023113 0.304332
3 1 0.044869 0.295261
4 1 0.065347 0.286460
5 1 0.084623 0.277922
6 1 0.102767 0.269638
7 1 0.119845 0.261601
Now you decide that you need to add a percentage sign at the end of the %Dev field (starting from 2nd line). We'll make a simple macro in the (arbitrarily selected) m
register as follows:
Press: qm
: To start recording macro under m
register.
EE
: Go to the end of the 3rd column.
a
: Insert mode to append to the end of this column.
%
: Type the percent sign we want to add.
<ESC>
: Get back into command mode.
j0
: Go to beginning of next line.
q
: Stop recording macro
We can now just type @m
to run this macro on the current line. Furthermore, we can type @@
to repeat, or 100@m
to do this 100 times! Life's looking pretty good.
At this point you should be saying, "But what does this have to do with registers?"
Excellent point. Let's investigate what is in the contents of the m
register by typing "mp
. We then get the following:
EEa%<ESC>j0
At first this looks like you accidentally opened a binary file in notepad, but upon second glance, it's the exact sequence of characters in our macro!
You are a curious person, so let's do something interesting and edit this line of text to insert a !
instead of boring old %
.
EEa!<ESC>j0
Then let's yank this into the n
register by typing B"nyE
. Then, just for kicks, let's run the n
macro on a line of our data using @n
....
It added a !
.
Essentially, running a macro is like pressing the exact sequence of keys in that macro's register. If that isn't a cool register trick, I'll eat my hat.
For large datasets a faster solution is required.
Making use of 'Text to Columns' functionality provides a fast solution.
Example based on column F, starting range at 25 to LastRow
Sub ConvTxt2Nr()
Dim SelectR As Range
Dim sht As Worksheet
Dim LastRow As Long
Set sht = ThisWorkbook.Sheets("DumpDB")
LastRow = sht.Cells(sht.Rows.Count, "F").End(xlUp).Row
Set SelectR = ThisWorkbook.Sheets("DumpDB").Range("F25:F" & LastRow)
SelectR.TextToColumns Destination:=Range("F25"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
:=Array(1, 1), TrailingMinusNumbers:=True
End Sub
Use continue;
instead of break;
to enter the next iteration of the loop without executing any more of the contained code.
foreach (Item item in myItemsList)
{
if (item.Name == string.Empty)
{
// Display error message and move to next item in list. Skip/ignore all validation
// that follows beneath
continue;
}
if (item.Weight > 100)
{
// Display error message and move to next item in list. Skip/ignore all validation
// that follows beneath
continue;
}
}
Official docs are here, but they don't add very much color.
You could insert both the key,value pair and its inverse into your map structure, but would have to convert the Integer to a string:
map.put("theKey", "theValue");
map.put("theValue", "theKey");
Using map.get("theValue") will then return "theKey".
It's a quick and dirty way that I've made constant maps, which will only work for a select few datasets:
If you want to keep <Integer, String>
you could maintain a second <String, Integer>
map to "put" the value -> key pairs.
#Try without dot notation
sample_dict = {'name': 'John', 'age': 29}
print(sample_dict['name']) # John
print(sample_dict['age']) # 29